简体   繁体   中英

Meteor Braintree — Create Client Token via Meteor Method

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)

Disclaimer: I work for Braintree :)

I'm not familiar with Meteor, but as @mrak noted clientToken.generate is asynchronous and you will definitely handle that appropriately in your method.

In your current code, clientToken is undefined because console.log(clientToken) executes immediately, before you receive a clientToken from the callback for clientToken.generate . Asynchronous programming can take a while to wrap your head around if you are used to coding in a synchronous matter, but there are many resources out there to help you (here is one ).

It appears that Meteor.wrapAsync will indeed provide what you need, here is an untested example implementation.

Meteor.methods({
  createClientToken: function() {
    var createToken = Meteor.wrapAsync(gateway.clientToken.generate, gateway.clientToken);

    var response = createToken({});

    return response.clientToken;
  }
});

Update

I've created a very basic Braintree + Meteor application that may be of some use to you (if it is not, please file an issue on the GH repo to help improve it!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM