Node JS and Coinbase - javascript

I am trying to integrate Coinbase with Node Js, but I am unable to execute the code given on the tutorial page. My code is
`var coinbase = require('coinbase');
var client = new coinbase.Client({'apiKey': mykey, 'apiSecret': mysecret});
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log('my bal: ' + acct.balance.amount + ' for ' + acct.name);
});
});`
I get t the following error:
accounts.forEach(account => {
^
typeError: Cannot read property 'forEach' of null
Looking forward to your answer! Thanks!

The error is clear: accounts is equal to null. You should check what's in err before working with accounts

hello you can use like this
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log(acct.name + ': ' + acct.balance.amount + ' ' + acct.id );
});
});

You could try with a different API keys and check if the keys are enabled.
var Client = require('coinbase').Client;
var client = new Client({
'apiKey': 'API KEY',
'apiSecret': 'API SECRET'
});
client.getAccounts({}, function (err, accounts) {
accounts.data.forEach(function (acct) {
console.log(acct.name + ': ' + acct.balance.amount + ' ' + acct.id);
});
});
Also accounts returns a lot of information but we are looking at the data block. Please refer the Coinbase API v2 documentation for complete sample response of the getAccounts() call - https://developers.coinbase.com/api/v2?javascript#account-resource
Let us know if this works. Good luck!

Related

Facebook Graph API Long-Lived Token

I am working with Facebook Graph API and I have followed the instruction on the official documentation page to obtain a Long-Lived Token using a previously extracted access token by running the below code
//Get long-lived access token
var longLiveToken = "https://graph.facebook.com/v8.0/oauth/" +
req.authInfo + "?grant_type=fb_exchange_token&client_id=" + process.env.FACEBOOK_CLIENT_ID +
"&client_secret=" + process.env.FACEBOOK_CLIENT_SECRET + "&fb_exchange_token=" + req.authInfo +
"&redirect_uri=http://localhost:4000/";
https.get(longLiveToken, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
console.log(d);
});
}).on('error', (e) => {
console.error(e);
});
However I am getting the below error message
'www-authenticate': 'OAuth "Facebook Platform" "invalid_request" "client_secret should not be passed to /oauth
My query is in line with the official documentation, not sure why I am getting this error message or how to go about resolving it
I figured out what is wrong with the code, I passed in wrong params. Below is the correct query
var longLiveToken = "https://graph.facebook.com/v8.0/oauth/" +
"access_token" + "?grant_type=fb_exchange_token&client_id=" + process.env.FACEBOOK_CLIENT_ID +
"&client_secret=" + process.env.FACEBOOK_CLIENT_SECRET + "&fb_exchange_token=" + req.authInfo;
You should not provide client_secret value. Try to not provide client parameters. Maybe you're providing wrong uri, or not passing required parameters. It works if you would take a look again.

My valid SendGrid API key not working in via NodeJS

I'm attempting you Send Grid's NodeJS code in a CSHTML web page to use their mail send service. For some reason the setApiKey command is not working and does not even exist according to the error in the console. Any idea what I'm doing wrong here?
const sgMail = require(['##sendgrid/mail']);
sgMail.setApiKey('MYAPIKEY');
const msg = {
to: email_id.value,
from: send_email.value,
subject: 'Subject',
html: '<div>From: ' + send_first_name.value + ' ' + send_last_name.value + '</div><div>Email: ' + send_email.value + '</div><div>Message: ' + message + '</div>',
};
sgMail.send(msg).then((sent) => {
console.log('email sent');
})
And here are two of the error messages - Mismatched anonymous define() module and TypeError: sgMail.setApiKey is not a function

Discord.js error = "message is not defined"

const Discord = require('discord.js');
exports.run = async (bot, message, args) => {
let userInfMent = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]))
message.channel.send(userInfo(userInfMent));
}
function userInfo(user) {
const Discord = require('discord.js');
let userInfMent = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]))
var userCreated = userInfMent.createdAt.toString().split(' ');
var lastMsg = userInfMent.lastMessage.createdAt.toString().split(' ')
const userInfoEmbed = new Discord.RichEmbed()
.addField('Никнейм: ', userInfMent.username)
.addField('Тег: ', userInfMent.tag)
.addField('ID: ', userInfMent.id)
.addField('Аккаунт был создан: ', userCreated[1] + ', ' + userCreated[2] + ', ' + userCreated[3])
.addField('Последнее сообщение: ', userInfMent.lastMessage + ' в ' + lastMsg[1] + ', ' + lastMsg[2] + ', ' + lastMsg[3] + ', ' + lastMsg[4])
.addField('Статус: ', userInfMent.presence.status)
.setColor('RANDOM')
.setThumbnail(userInfMent.avatarURL);
return userInfoEmbed
}
Hi. I'm a Node.js beginner.
When i start the command, in console i see the error:
(node:6312) UnhandledPromiseRejectionWarning: ReferenceError: message
is not defined
at userInfo (C:\Users\deris\Desktop\Проекты\Node.js\discord.js\JSBot-master\commands\userinfo.js:10:23)
at Object.exports.run (C:\Users\deris\Desktop\Проекты\Node.js\discord.js\JSBot-master\commands\userinfo.js:5:26)
message is only defined in the message event itself. So you can simply pass the message object as a parameter into your function.
// new function
function userInfo(user, message) {
//code here
}
Just remember that you'll have to add the additional parameter when you call the function.
message.channel.send(userInfo(userInfMent, message));
Message is not defined because you did not put the code in a Message Event.
I just been learning and found this one out.
Message.channel.send will not work inside a function. The function will read it as a variable. And since message hasn't been defined we draw the error.
outside the function the command will again work fine. I'm not sure if it's an error with the current builds or intentional. But there is your fix
Your using message.guild.member inside of the function and didn't define member which is causing the problem. Consider placing the function inside of the export

Javascript Chrome API- cannot read property of undefined

I'm writing a little javascript application trying to use the Chrome sockets API. The code doesn't seem terribly relevant, though, because I'm getting an error on the very first line:
var socket = chrome.sockets.udp;
On that line, I get an Uncaught TypeError: cannot read property 'udp' of undefined. So chrome.sockets isn't being defined for some reason, but for the life of me I can't seem to figure out what. Is there something I need to include or import to use Chrome APIs? The API doc hasn't been helpful in that regard.
EDIT: background.js file:
var socket = chrome.sockets.udp;
var PORT = 5005;
var HOST = '127.0.0.1';
var sockInfo;
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('window.html', {
'bounds': {
'width': 400,
'height': 500
}
});
init();
});
function init(){
socket.create({}, function(_sockInfo){
sockInfo = _sockInfo;
socket.bind(sockInfo.socketId, HOST, PORT, function(result){
if(result < 0){
throw "Bind failed"
}
console.log("Socket created and bound.");
socket.onReceive.addListener(function(info){
console.log('Received packet from ' + info.remoteAddress +
' : ' + info.remotePort + ', length ' + info.data.length);
});
});
});
}

Node.js variable getting reset - undefined

I have a global variable (openTokSessionID) that is set by a function. When the function is run again, it should check to see if openTokSessionID is set. If it is, it should use the current value. Instead, however, it complains that openTokSessionID is undefined. My server code is below. Thanks for your help.
var http = require('http').createServer(handler),
io = require('socket.io').listen(http).set('log level', 1),
opentok = require('opentok'),
key = '', // Replace with your API key
secret = ''; // Replace with your API secret
var ot = new opentok.OpenTokSDK(key,secret);
ot.setEnvironment("staging.tokbox.com");
//ot.setEnvironment("api.opentok.com"); //only for production
http.listen(8080);
console.log('Chatserver listening on port 8080');
var nicknames = {};
var log = {};
var connectedUsersObject={};
var privateSessionObject={};
var data;
var openTokSessionID='';
function handler(req, res) {
res.writeHead(200);
res.end();
}
////////////////////////////////////////////SOCKET.IO FUNCTIONS///////////////////////////////////////////////////////
io.sockets.on('connection', function (socket) {
socket.on('private message', function(data) {
console.log('OpenTok Session ID is: ....' + openTokSessionID);
if(data.messageType=='openTokDemoRequest'){ //if new session, create unique session ID, add to current chat object
console.log(data.messageType + ' sender: ' + data.from);
var location = '127.0.0.1'; // use an IP or 'localhost'
console.log('message type is: "openTokDemoRequest". openTokSessionID is: ' + openTokSessionID);
var messageRecipient=data.from;
if(openTokSessionID==''){
console.log('The session ID is: ' + openTokSessionID + '++++++++');openTokSessionID= ot.create_session(location, function(openTokSessionID){
var data= {'to':messageRecipient, 'message':{'token': ot.generate_token({'session_id':openTokSessionID, 'role': "publisher"}), 'sessionID': openTokSessionID, 'apikey':key}, 'from': 'openTok', 'messageType':'demoTokenInfo', 'privateSessionID':''};
console.log('NEW session id is: ' + openTokSessionID + '. token is: ' + data.message.token);
// privateMessageSend(data);
// sendToUser(data);
connectedUsersObject[messageRecipient].emit('private message', data);
console.log ('message recipient is: ' + messageRecipient);
});
}
else{
console.log('OpenTok Session ID is: ////' + openTokSessionID);
var data= {'to':messageRecipient, 'message':{'token': ot.generate_token({'session_id':openTokSessionID, 'role': "publisher"}), 'sessionID': openTokSessionID, 'apikey':key}, 'from': 'openTok', 'messageType':'demoTokenInfo', 'privateSessionID':''};
console.log('session id is: ' + openTokSessionID + '. token is: ' + data.message.token);
connectedUsersObject[messageRecipient].emit('private message', data);
console.log ('message recipient is: ' + messageRecipient);
}
}
});
Here you're trying to use the return value from an asynchronous call, and as a result you're setting your variable to undefined:
openTokSessionID= ot.create_session(location, function(openTokSessionID){
...
Because you gave your callback argument the same name as your variable, it masked your variable within the callback so it looked OK the first time, but your actual variable got trashed.
You need to change it to something like:
ot.create_session(location, function(sessionID){
openTokSessionID = sessionID;
...

Categories