braintree + NodeJS gives an "authentication Error " - node.js

I'm trying to build a payment gateway library using braintree's NodeJS library, I'm making an ajax call from front end with the card data.
Client-Side
var card_data = {
type: "AmEx",
number: "3XXXXXXXXXXXXXX",
expire_month: "XX",
expire_year: "201X",
cvv2: "XXX",
name: "sandeep",
price : "200",
currency : "USD"
};
Ajax call,
$.ajax({
method: "GET",
url: "http://localhost:3000/paymentPath_braintree",
data: card_data
}).done(function(message){
console.log(message);
}).fail(function(data, message){
console.log(message);
});
Server-Side
var braintreePay = require('braintree');
app.get("/payment_braintree", function(request, response){
var data = request.query;
var gateway = braintreePay.connect({
environment: braintreePay.Environment.Sandbox,
merchantId: "MymerchentID",
publicKey: "MypublicKey",
privateKey: "MyprivateKey",
});
var saleRequest = {
amount: data.price,
creditCard: {
number: data.number,
cvv: data.cvv2,
expirationMonth: data.expire_month,
expirationYear: data.expire_year.slice(2),
cardHolder: data.name
},
options: {
submitForSettlement: true
}
};
gateway.transaction.sale(saleRequest, function(error, result){
if(error){
console.log(error.name);
throw error;
}
if(result.success){
response.send(result.transaction.id);
} else {
response.send(result.message);
}
});
});
I have cross checked everything, from keys and card data everything is in order but i am getting an error in callback after making gateway.transaction.sale(...); called Authentication Error . Which i tried to figure out for hours but could not get through.
error object is
authenticationError: Authentication Error
arguments: undefined
message: "Authentication Error"
name: "authenticationError"
stack: undefined
type: "authenticationError"
Where am i going wrong?
I have created an account sandbox.braintreegateway those key credentials are from the account that i have created, i din't create an app like how its done in paypal.
I am going through lack of understanding in Braintree integration.
Are their any proper documented resource.

Related

Firebase fcm sendMulticast Error: "Exactly one of topic, token or condition is required"

I am using version 7.2.0 of firebase admin to send fcm push notification, using sendMutlicast method:
async function sendPushRequest({tokens, title, body, customData}) => {
const message = {
notification: {
title,
body,
},
data: customData,
tokens,
}
return firebase.messaging().sendMulticast(message)
}
This is the error I am getting
Error: Exactly one of topic, token or condition is required
at FirebaseMessagingError.Error (native)
at FirebaseMessagingError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:39:28)
...
I tried logging the data and here is the object that sendPushRequest function is called with:
{
tokens: [ null, null, null, 'home-test', null, null ], // this one is a recent sample, I've been getting this error for a while now
title: 'some string',
body: 'some other string',
customData: {
title: 'some string',
body: 'some other string',
bigText: 'again another string',
color: '#9f0e27',
smallIcon: 'notificon',
sound: 'default'
}
}
I'm not sure what is causing the error!
I struggled with this problem too, its quite difficult to configure google admin firebase in nodejs. I find out there is a package that can handle this nicely.
https://www.npmjs.com/package/fcm-notification
but it has some little problem . you can not pass it multiple firebase configuration. here is some example :
const fcm = require('fcm-notification');
const fcm_key = require('../config/customer/fcm.json');
const FcM = new fcm(fcm_key);
module.exports.sendToSingleUser = async (message, token) => {
let message_body = {
notification: {
...message
},
token: token
};
FcM.send(message_body, function (err, response) {
if (err) {
return err
} else {
return response
}
})
}
Facing this error too. Figure out that our tokens array contains null or undefiend value. Resolved by remove that from tokens array and everything works fine.

Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM

I got this code from my client iOS app on XCode console
Firebase registration token: diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h
diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h
NodeJS
console.log("START");
var FCM = require('fcm-node');
var serverKey = require('/Users/bheng/Desktop/Apps/APNS/node/mhn-app-firebase-adminsdk-bs45c-5ac3770488.json')
var fcm = new FCM(serverKey)
var collapseKey = 'new_message';
var message = {
to: 'diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
data: {
cpeMac: '000000000000',
type: 'malware'
},
notification: {
title: 'Hello baby',
body: 'Nice body',
tag: collapseKey,
icon: 'ic_notification',
color: '#18d821',
sound: 'default',
},
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!")
console.log(JSON.stringify(err));
} else {
console.log("Successfully sent with response: ", JSON.stringify(response))
}
})
console.log("END");
Result
When I run it
node app.js
I kept getting
START
END
Successfully sent with response: {"results":[{"error":{"code":"messaging/invalid-registration-token","message":"Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM."}}],"canonicalRegistrationTokenCount":0,"failureCount":1,"successCount":0,"multicastId":7577724855311354000}
How would one go about debugging this further?
your token has some additional random string such as
to: 'diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
just remove : diWY78iar8s: from your token string
console.log("START");
var FCM = require('fcm-node');
var serverKey = require('/Users/bheng/Desktop/Apps/APNS/node/mhn-app-firebase-adminsdk-bs45c-5ac3770488.json')
var fcm = new FCM(serverKey)
var collapseKey = 'new_message';
var message = {
to: 'APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
data: {
cpeMac: '000000000000',
type: 'malware'
},
notification: {
title: 'Hello baby',
body: 'Nice body',
tag: collapseKey,
icon: 'ic_notification',
color: '#18d821',
sound: 'default',
},
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!")
console.log(JSON.stringify(err));
} else {
console.log("Successfully sent with response: ", JSON.stringify(response))
}
})
console.log("END");
Response from FCM :
Successfully sent with response: { results: [ { messageId: '0:1543448946734425%479ec0e2479ec0e2' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 6133765431734591000 }
One of the interesting reasons for invalid registration is: that device have a different token. Maybe you are trying to use a past token.
In my case what happened was I was getting the FCMRegistrationToken from my colleague via Discord and the Ctrl+C Ctrl+V was modifying the token. On obtaining the token via email solved the issue.

AWS Cognito Node.JS User Authentication returns unknown problem

I'm using AWS Cognito with Node.JS.
I'm successfully registering and verifying users, but the Authentication is returning "unknown error, the response body from fetch is undefined."
I'm using node-fetch module along with amazon-cognito-identity-js (set as var AWSCognito on code below). User is not in a state of requiring password change and verified.
Have others experienced this and how did you resolve the issue?
Appreciate any guidance in advance....
Here's my code, my complete module is on npm as iditawsutils :
exports.authCognitoUser = function(theUserPoolID, theClientID, userName, userPassword) {
var authenticationData = {
Username : userName,
Password : userPassword
};
var authenticationDetails = new AWSCognito.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : theUserPoolID,
ClientId : theClientID
};
var userPool = new AWSCognito.CognitoUserPool(poolData);
var userData = {
Username : userName,
Pool : userPool
};
console.log('authentication details: ',authenticationDetails);
var cognitoUser = new AWSCognito.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
console.log('id token + ' + result.getIdToken().getJwtToken());
console.log('refresh token + ' + result.getRefreshToken().getToken());
return result;
},
onFailure: function(err) {
console.log(err.message || JSON.stringify(err));
return err;
},
});
}
//from the console log:
authentication details: AuthenticationDetails {
validationData: {},
authParameters: {},
username: 'thesmarterstuff',
password: 'passW0rd!’ }
Unknown error, the response body from fetch is: undefined
Use the following in your onFailure block to find more details about the error.
onFailure: function(err) {
console.log(new Error().stack);
console.log(err.message || JSON.stringify(err));
},
If you find the error occurring in your fetch line in Client.js, then this could be because currently NodeJS SDK, and most other SDKs do not support the default USER_SRP_AUTH.
You could check by adding a console.log in the Client.js
console.log(this.endpoint);
console.log(options);
Login to your AWS account, and make sure you have checked the option - Enable username-password (non-SRP) flow for app-based authentication (USER_PASSWORD_AUTH)
Then, in your code update it with the following setting.
cognitoUser.setAuthenticationFlowType('USER_PASSWORD_AUTH');

Getting error while making charges on connected Standalone Acount(Stripe)

I'm trying to make charges on connected standalone acount. I'm using parse cloud code for that...it gives me following error:
Error Domain=Parse Code=141 "ReferenceError: stripe is not defined
Below is my code..
var Stripe = require('stripe');
Stripe.initialize('**************************');
Parse.Cloud.define("hello", function(request, response) {
var token = request.params.stripeToken;
var userid = request.params.userId;
stripe.charges.create(
{
amount: 1000,
currency: "usd",
source: token,
description: "Example charge",
application_fee: 123
},
{stripe_account: userid},{
success: function(httpResponse) {
response.success("Purchase made!");
},
error: function(httpResponse) {
response.error(error);
}
});
});

Use the Mailchimp API

I'd like to use the Mailchimp Node.js API in my Parse Cloud Hosting app to subscribe a user to a mailing list. Parse doesn't support NPM but, given that the Mailchimp API has no dependencies, I thought I'd be able to copy the code into my project. However, the Mailchimp API uses the "https" module which Parse doesn't support.
Does anyone know of a way around this?
I've been unable to use the Mailchimp API directly but the REST API is pretty easy to use.
In main.js, create a Cloud Function. Enter your API key and update the REST URL to point at the correct Mailchimp data center (http://apidocs.mailchimp.com/api/2.0/)
var mailchimpApiKey = "<<REPLACE_WITH_YOUR_KEY>>";
Parse.Cloud.define("SubscribeUserToMailingList", function(request, response) {
if (!request.params ||
!request.params.email){
response.error("Must supply email address, firstname and lastname to Mailchimp signup");
return;
}
var mailchimpData = {
apikey : mailchimpApiKey,
id : request.params.listid,
email : {
email : request.params.email
},
merge_vars : request.params.mergevars
}
var url = "https://<<REPLACE_WITH_DATA_CENTRE>>.api.mailchimp.com/2.0/lists/subscribe.json";
Parse.Cloud.httpRequest({
method: 'POST',
url: url,
body: JSON.stringify(mailchimpData),
success: function(httpResponse) {
console.log(httpResponse.text);
response.success("Successfully subscribed");
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
console.error(httpResponse.text);
response.error('Mailchimp subscribe failed with response code ' + httpResponse.status);
}
});
});
Then, in the code which calls this function... (replace your list ID)
Parse.Cloud.run("SubscribeUserToMailingList", {
listid : "<<REPLACE_WITH_LIST_ID>>",
email : email,
mergevars : {
FNAME : firstName,
LNAME : lastName
}
})
.then(function(success){
console.log("Successfully subscribed");
// ...
},
function(error){
console.log("Unable to subscribe");
// ...
});
Install mailchimp in your project
npm install mailchimp-api
From client controller call the server-controller with required data
Don't forget to add $http to the top of controller
$http({
method : 'POST',
url : '/mailchimp-users/subscribe',
data : {user:this.name}}).
success(function(response) {
console.log("hai this is basic test" + response);
$scope.send = response.message;
}).error(function(response) {
$scope.error = response.message;
});
In server controller
Add this to the beginning of page
var MailchimpUser = mongoose.model('MailchimpUser'),
_ = require('lodash'),
mcapi = require('mailchimp-api');
var apiKey = '4bf6fb8820c333da4179216c3c2ef8fb-us10';
// Change this to your Key
var listID = 'ebbf193760';
var mc = new mcapi.Mailchimp(apiKey, {version: '2.0'});
Add this function
exports.subscribe = function(req, res) {
var entry = req.body.user;
var mcReq = {
apikey: '4bf6fb8820c333da4179216c3c2ef8fb-us10',
id: 'ebbf193760',
email: {email: entry + '#gmail.com'},
merge_vars: {
FNAME: 'subscriber-first-name',
LNAME: 'subscriber-last-name'
},
'double_optin': false,
'send_welcome': true
}
// submit subscription request to mail chimp
mc.lists.subscribe(mcReq, function(data) {
console.log(data);
}, function(error) {
console.log(error);
});
};
Add this route your route file
app.route('/mailchimp-users/subscribe')
.post(mailchimpUsers.subscribe);
Here's how I got it to work using the MailChimp API v3.0, the method below supports adding/updating a subscriber, as well as adding/removing him to/from a Group!
Prerequisite:
You need to get an MD5 hash method to convert the user's email into a hash.
Here's the one I used: http://www.webtoolkit.info/javascript-md5.html#.Vuz-yjZOwXV
Copy the code in the link, and paste it into a newly created file, name it "md5js.js" for example.
Update the code you copied to start with exports.MD5 = function (string) {
You can test the conversion you got from the copy/pasted module by comparing the result with this online tool: http://www.miraclesalad.com/webtools/md5.php
var jsmd5 = require('cloud/md5js.js');
// here replace that with your own data center (by looking at your API key).
var datacenter = "us13";
var MAILCHIMP_URL = "https://<any_string>:<apikey>#" + datacenter + ".api.mailchimp.com/3.0/";
var MAILCHIMP_LIST_NEWSLETTER_ID = <yourlistId>;
Parse.Cloud.define("SubscribeUserToMailingList", function(request, response) {
if (!request.params ||
!request.params.email){
response.error("Must supply email address, firstname and lastname to Mailchimp signup");
return;
}
var email = request.params.email;
var firstName = request.params.firstname;
var lastName = request.params.lastname;
// this converts the email string into an MD5 hash.
// this is Required if you want to use a "PUT" which allows add/update of an entry, compared to the POST that allows only adding a new subscriber.
var emailHash = jsmd5.MD5(email);
var mailchimpData = {
'email_address': email,
'status': "subscribed",
'merge_fields': {
'FNAME': firstName,
'LNAME': lastName
},
'interests': {
"<groupID>": true // optional, if you want to add the user to a "Group".
}
};
var url = MAILCHIMP_URL + "lists/" + MAILCHIMP_LIST_NEWSLETTER_ID + "/members/" + emailHash;
// using a "PUT" allows you to add/update an entry.
Parse.Cloud.httpRequest({
method: 'PUT',
url: url,
body: JSON.stringify(mailchimpData),
success: function(httpResponse) {
console.log(httpResponse.text);
response.success("Successfully subscribed");
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
console.error(httpResponse.text);
response.error('Mailchimp subscribe failed with response code ' + httpResponse.status);
}
});
});

Resources