Skip to content

Instantly share code, notes, and snippets.

@michaltakac
Created October 17, 2015 00:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaltakac/98152d84b7182eb90cb4 to your computer and use it in GitHub Desktop.
Save michaltakac/98152d84b7182eb90cb4 to your computer and use it in GitHub Desktop.
Braintree demo - billing.js (v2)
// Define gateway variable
var gateway;
Meteor.startup(function () {
var env;
// Pick Braintree environment based on environment defined in Meteor settings.
if (Meteor.settings.public.env === 'Production') {
env = Braintree.Environment.Production;
} else {
env = Braintree.Environment.Sandbox;
}
// Initialize Braintree connection:
gateway = BrainTreeConnect({
environment: env,
publicKey: Meteor.settings.public.BT_PUBLIC_KEY,
privateKey: Meteor.settings.private.BT_PRIVATE_KEY,
merchantId: Meteor.settings.public.BT_MERCHANT_ID
});
});
Meteor.methods({
getClientToken: function (clientId) {
var generateToken = Meteor.wrapAsync(gateway.clientToken.generate, gateway.clientToken);
var options = {};
if (clientId) {
options.clientId = clientId;
}
var response = generateToken(options);
return response.clientToken;
},
btCreateCustomer: function(){
var user = Meteor.user();
var customerData = {
email: user.emails[0].address
};
// Calling the Braintree API to create our customer!
gateway.customer.create(customerData, function(error, response){
if (error){
console.log(error);
} else {
// If customer is successfuly created on Braintree servers,
// we will now add customer ID to our User
Meteor.users.update(user._id, {
$set: {
customerId: response.customer.id
}
});
}
});
},
createTransaction: function(nonceFromTheClient) {
var user = Meteor.user();
// Let's create transaction.
gateway.transaction.sale({
amount: '10.00',
paymentMethodNonce: nonceFromTheClient, // Generated nonce passed from client
customer: {
id: user.customerId
},
options: {
submitForSettlement: true, // Payment is submitted for settlement immediatelly
storeInVaultOnSuccess: true // Store customer in Braintree's Vault
}
}, function (err, success) {
if (err) {
console.log(err);
} else {
// When payment's successful, add "paid" role to current user.
Roles.addUsersToRoles(user._id, 'paid', Roles.GLOBAL_GROUP)
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment