I'm trying to get Braintree Payments working in a Meteor app. I'm stuck at trying to return the result of generating a token (server side, via a Meteor Method) to be used client side.
I've tried this:
/server/braintree.js
Meteor.methods({
createClientToken: function() {
var token = gateway.clientToken.generate({
customerId: this.userId
}, function(err, response) {
clientToken = response.clientToken
return clientToken
}
)
console.log(token)
return token
}
})
which returns true
.
I've also tried this:
Meteor.methods({
createClientToken: function() {
var clientToken
gateway.clientToken.generate({
customerId: this.userId
}, function(err, response) {
clientToken = response.clientToken
}
)
console.log(clientToken)
return clientToken
}
})
Which returns undefined
.
The function(err, response)
is being called asynchronously, yes? If so, that would be the explanation of the problem. Seems that trying to return a value from an asynchronous function is a bit of a pain point in Javascript. I've read a number of SO answers on it (like this one, this one and this one) but none have seemed to lead me in the right direction.
Also, I believe I may need to be using Meteor's wrapAsync
method, correct? I've tried this (and found this and this relevant SO questions on it), but still can't seem to get things right.
Grateful for any feedback.
Update:
For a working approach to integrating Braintree with Meteor, check out the example repo (many thanks @Nick Tomlin for this)