stripe params using javascript - javascript

I'm using Stripe in conjunction with Parse Cloud Code.
I can pass the token ID and the customer email, but I need their name too. Stripe doesn't have any straight JS docs so it's difficult to understand. How can I pass the name?
Here's my client side code:
Parse.Cloud.run('createCustomer',{
token: token.id,
email: token.email,
}, {
// Success handler
success: function(message) {
alert('Success: ' + message);
},
// Error handler
error: function(message) {
alert('Error: ' + message);
}
})
and the backend Cloud Code:
Parse.Cloud.define("createCustomer", function(request, response) {
console.log(request.params)
Stripe.Customers.create({
account_balance: 0,
email: request.params.email,
description: "stripe customer",
metadata: {
userId: request.params.objectId, // e.g PFUser object ID
createWithCard: true
}
}, {
success: function(httpResponse) {
response.success(name + userId); // return customerId
},
error: function(httpResponse) {
console.log(httpResponse");
response.error("Cannot create a new customer.");
}
});
});

This works for me. And yes, there is little documentation on this. :)
Parse.Cloud.define("createCustomer", function(request, response) {
Stripe.Customers.create({
card: request.params.cardToken, // the token id should be sent from the client
// account_balance: 0,
email: request.params.email,
description: 'new stripe user',
metadata: {
name: request.params.name
}
},
{
success: function(httpResponse) {
response.success(httpResponse); // return customerId
},
error: function(httpResponse) {
console.log(httpResponse);
response.error(httpResponse);
}
});
});

Related

Node JS Not Allowing Returned JSON into JSON String

I have written a Firebase cloud function to sign people up into my Firebase database. I have tested with POSTMAN and the function is working correctly.
The problem I am having is that I have a function that is getting a stripe ID and then needs to return that value. I want the customer id (customer.id in my reference) to append a JSON string I have created with the users info.
This way, when the function is done it needs to write all the data to firebase and then return the same JSON string variable to my app. This all works, but I cannot get the Stripe ID to append into my JSON array and be parsed.
I have been cowering the internet to try and find a solution, and I believe my syntax is correct, but its not working. I know the function is working because the console.log is outputting the stripe ID, its just not being added to the JSON variable that is being written to Firebase.
Anyone that could explain where I am going wrong would be much appreciated. I have referenced my issue points in the code below with // for comments.
exports.myCloudFunction=
functions.https.onRequest((req, res) => {
if (req.method !== 'POST') {
return;
}
const userDataInput = req.body;
console.log('Console Body:', req.body);
admin.auth().createUser({
email: userDataInput.email,
emailVerified: false,
phoneNumber: userDataInput.mobile,
password: userDataInput.password,
displayName: userDataInput.firstname + ' ' + userDataInput.lastname,
disabled: false
})
.then(async function (userRecord) {
console.log('User record:', userRecord);
var userObject = //CONSTRUCTED JSON STRING
{
first_name: userDataInput.firstname,
last_name: userDataInput.lastname,
mobile_number: userDataInput.mobile,
email: userDataInput.email,
timestamp: admin.database.ServerValue.TIMESTAMP,
driver_profile: { isDriverApproved: false, isDriverDisabled: false, isDriverStatusPending: false, isDriver: false, isPickupModeEnabled: false },
}
stripe.customers.create({
description: 'Firebase ID: ' + userRecord.uid,
email: userRecord.email,
name: userRecord.displayName,
phone: userRecord.phoneNumber
}, async function (err, customer) {
console.log('New Stripe ID Created', customer.id); // THIS WORKS< THE customer.id is outputting
try {
return userObject[{ stripe_id: customer.id }]; // THIS IS NOT WORKING, I WANT **customer.id** TO BE PUT INTO THE **userObject** JSON variable.
}
catch (error) {
console.error(error);
return res.status(200).send('Error: ' + error);
}
});
try {
await admin.database().ref('users/' + userRecord.uid).set(userObject);
return res.status(200).send({ returnData: userObject });
}
catch (error) {
console.error(error);
return res.status(200).send('Error: ' + error);
}
})
.catch(function (error) {
console.log('Error creating new user:', error);
res.status(500).send({ returnError: error });
});
});
I think that the return it won't return anything because is a callback
exports.myCloudFunction =
functions.https.onRequest((req, res) => {
if (req.method !== 'POST') {
return;
}
const userDataInput = req.body;
console.log('Console Body:', req.body);
admin.auth().createUser({
email: userDataInput.email,
emailVerified: false,
phoneNumber: userDataInput.mobile,
password: userDataInput.password,
displayName: userDataInput.firstname + ' ' + userDataInput.lastname,
disabled: false
})
.then(async function (userRecord) {
console.log('User record:', userRecord);
var userObject = //CONSTRUCTED JSON STRING
{
first_name: userDataInput.firstname,
last_name: userDataInput.lastname,
mobile_number: userDataInput.mobile,
email: userDataInput.email,
timestamp: admin.database.ServerValue.TIMESTAMP,
driver_profile: {
isDriverApproved: false,
isDriverDisabled: false,
isDriverStatusPending: false,
isDriver: false,
isPickupModeEnabled: false
},
}
stripe.customers.create({
description: 'Firebase ID: ' + userRecord.uid,
email: userRecord.email,
name: userRecord.displayName,
phone: userRecord.phoneNumber
}, async function (err, customer) {
console.log('New Stripe ID Created', customer.id); // THIS WORKS< THE customer.id is outputting
try {
// Move your logic to the final callback
userObject["stripe_id"] = customer.id;
await admin.database().ref('users/' + userRecord.uid).set(userObject);
return res.status(200).send({returnData: userObject});
} catch (error) {
console.error(error);
return res.status(200).send('Error: ' + error);
}
});
})
.catch(function (error) {
console.log('Error creating new user:', error);
res.status(500).send({returnError: error});
});
});
I think I found the error. There is an issue with your syntax
There is a line of code that is wrong
//replace
return userObject[{ stripe_id: customer.id }];
// for this
return userObject.stripe_id = customer.id;
Note: Try to separate your code better. It's kind of hard to read

What's the proper use of Bluebird or Q Promises in this situation?

I'm using a node machines package (machinepack-wepay) to communicate with Wepay and I'd like to be able to chain it properly.
Take the following example where we will be registering a user, creating an account and sending the email confirm. Along the way we will be storing some of the result info in mongo.
var WePay = require('machinepack-wepay');
// ... extraneous code removed for brevity
var member = req.session.member;
if( !_.has( member, 'wepay' ) ) {
WePay.userRegister({
clientId: config.wepay_client_id,
clientSecret: config.wepay_client_secret,
email: member.email,
scope: 'manage_accounts,collect_payments,view_user,send_money',
firstName: member.firstName,
lastName: member.lastName,
originalIp: req.headers['x-forwarded-for'],
originalDevice: req.headers['user-agent'],
tosAcceptanceTime: Math.floor(new Date() / 1000),
callbackUri: config.site_url + '/wepay/user?member=' + member.id,
useProduction: isProd
}).exec({
error: function (err) {
yourErrorHandler(err);
},
success: function (result) {
Member.update({id: member.id}, {wepay: result}, function (err, updated) {
if (err) {
yourErrorHandler(err);
}
else {
member = updated[0];
WePay.accountCreate({
accessToken: member.wepay.access_token,
name: 'Account Name',
description: 'My new account'
}).exec({
error: function (err) {
yourErrorHandler(err);
},
success: function (result) {
Member.update({id: member.id}, {wepay_account: result}, function (err, updated) {
if (err) {
sails.log.error("error updating page:", err);
}
req.session.member = updated[0];
// PATTERN CONTINUES HERE
});
}
});
}
});
}
});
}
else{
WePay.userDetails({
accessToken: member.wepay.access_token,
useProduction: false,
}).exec({
error: function (err){
yourErrorHandler(err);
},
success: function (result){
_.extend( member.wepay, result );
Member.update({id: req.session.current_page.id}, member, function (err, updated) {
if (err) {
sails.log.error("error updating page:", err);
}
req.session.member = updated[0];
// PATTERN CONTINUES HERE
});
},
});
}

Parse open source server sending push using cloud

I am now on the new parse open source server and I am trying to send a push notification using the cloud main.js. I sent a push using curl but can not in the .js file. Here is the code I have.
Parse.Cloud.define("PushNotification", function(request, response) {
console.log('sending push');
var Installation = new Parse.Query(Parse.Installation);
console.log(Installation);
Parse.Push.send({
where: Installation,
data: {
alert: request.params.Message,
badge: 0,
sound: 'default'
}
}, {
useMasterKey: true,
success: function() {
// Push sent!
console.log('Push sent');
response.success('success');
},
error: function(error) {
// There was a problem :(
response.error("Error push did not send");
console.log('sending push error: '+error);
}
});
It says that it sent but It did not. If any one could help that would be great!
I got a answer on github and I hope this will help any one else with the same problem. Here is the code I used.
Parse.Cloud.define("PushNotification", function(request, response) {
console.log('sending push');
var Installation = new Parse.Query(Parse.Installation);
console.log(Installation);
Parse.Push.send({
useMasterKey: true,
where: Installation,
data: {
//or you can put "" to not do a custom alert
alert: request.params.Message,
badge: 0,
sound: 'default'
}
}, {
useMasterKey: true,
success: function() {
// Push sent!
console.log('Push sent');
response.success('success');
},
error: function(error){
console.error(error);
}
});
});

Parse Cloud Code function get deviceToken By username

I am kinda new to the whole cloud code and I am having a bit of trouble fetching some data.
So what I basically want is a function that by giving it a 'username' that is located in the Parse.User database, it will return the user's objectId which I will then use to locate the user's session in the Parse.Session, from there I will get the installationId which I will then use in the Parse.Installation to get the device token.
Note: I have written a function that keeps only 1 session active per user.
My issue:
The Query of Parse.Session has a result which only contains 3 objects, and the installationId is not included,therefor I can not find out what is the installation id and then use it to search the Parse.Installation to get the device token.
input example:
Input:
{"from":"user1",
"msg":"hello",
"title":"Whatever title",
"to":"user2"}
Here is the existing code I currently have which doesn't work.
Parse.Cloud.define('gcm', function(request,response){
var username = request.params.to;
console.log("usr "+username);
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('username', username);
userQuery.find({
success: function(results){
var objectId = results[0].id;
console.log("obj id "+objectId);
var user = new Parse.User();
//Set your id to desired user object id
user.id = objectId;
var sessionQuery = new Parse.Query(Parse.Object.extend('Session'));
sessionQuery.include(user);
sessionQuery.find({
success: function(results1){
console.log("result classname type: "+typeof(results1[0]));
var installId = results1[0].installationId ; //here is the value which I want from the result, but the object is type of _Session which does not have installationId.
console.log("inst id "+installId);
var InstallationQuery = new Parse.Query(Parse.Installation);
InstallationQuery.equalTo('installationId',installId);
InstallationQuery.find({
success: function(results2){
var deviceToken = results2[0].get("deviceToken");
console.log("token "+deviceToken);
Parse.Cloud.httpRequest({
method: "POST",
url: " https://gcm-http.googleapis.com/gcm/send",
headers: {'Authorization' : 'key=AIzaSyDj4ISkLW7CzAQEQEhTsq3JYZK5OP8tSzY',
'Content-Type' : 'application/json'},
body: {
"data":
{
"title": request.params.title,
"msg": request.params.msg
},
"to" : deviceToken
},
success: function(httpResponse) {
response.success("Message Sent!");
console.log(httpResponse.text);
},
error: function(httpResponse) {
response.error("Error, Something went wrong.");
console.log("error 4: " + httpResponse.status);
}
});
},
error: function(error) {
//error
console.log("error 3: " + error);
}
});
},
error: function(error) {
//error
console.log("error 2: " + error);
}
});
},
error: function(error) {
//error
console.log("error 1: " + error);
}
});
});

Cannot add metadata to stripe customer subscription creation using nodejs?

I can't add metadata to the customer object when creating a new subscription/customer with stripe. Update: The problem I'm having is that the metadata does not save to the customer object. I don't see it in stripe in the logs/events.
// Stripe Response Handler
$scope.stripeCallback = function (code, result) {
result.email = $scope.email;
result.metadata = {'team': $scope.team};
if (result.error) {
window.alert('it failed! error: ' + result.error.message);
} else {
$http.post('/charge', result)
.success(function(data, status, headers, config) {
alert('success');
})
.error(function(data, status, headers, config) {
// console.log(status);
alert('error');
});
}
};
//on the server
app.post('/charge', function(req, res) {
var stripeToken = req.body.id;
var email = req.body.email;
var team = req.body.team;
subscribeUser(stripeToken, res, email, team);
});
// for subscriptions:
function subscribeUser(token, res, email, team){
stripe.customers.create({
card: token,
plan: '001',
email: email,
metadata: team
}, function(err, customer) {
var cust = customer.id;
// you'll probably want to store a reference (customer.id) to the customer
if (err) {
res.send({
ok: false, message: 'There was a problem processing your card (error: ' + JSON.stringify(err) + ')'});
} else {
res.send({
ok: true, message: 'You have been subscribed to a plan!'});
}
});
}
Any ideas would be much appreciated.
In case this helps somebody else, I made a few dumb mistakes:
You need to be sure you are added it to the metadata property
result.metadata = {'team': $scope.team};
You need to make sure you grab the metadata
var team = req.body.metadata;
You need to pass it in as metadata
metadata: team

Categories

Resources