无法使用客户 ID 创建 Braintree 客户端令牌

Can't create Braintree client token with customer ID

本文关键字:创建 Braintree 客户端 令牌 ID 客户      更新时间:2023-09-26

直接从 Braintree 的教程中复制,您可以使用客户 ID 创建客户端令牌,如下所示:

gateway.clientToken.generate({
    customerId: aCustomerId
}, function (err, response) {
    clientToken = response.clientToken
});

我声明var aCustomerId = "customer"但节点.js关闭并出现错误

new TypeError('first argument must be a string or Buffer')

当我尝试在没有 customerId 的情况下生成令牌时,一切正常(尽管我从未获得新的客户端令牌,但这是另一个问题)。

编辑:这是要求的完整测试代码:

var http = require('http'),
    url=require('url'),
    fs=require('fs'),
    braintree=require('braintree');
var clientToken;
var gateway = braintree.connect({
    environment: braintree.Environment.Sandbox,
    merchantId: "xxx", //Real ID and Keys removed
    publicKey: "xxx",
    privateKey: "xxx"
});
gateway.clientToken.generate({
    customerId: "aCustomerId" //I've tried declaring this outside this block
}, function (err, response) {
    clientToken = response.clientToken
});
http.createServer(function(req,res){
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.write(clientToken);
   res.end("<p>This is the end</p>");
}).listen(8000, '127.0.0.1');

免责声明:我在Braintree :)工作

很抱歉听到您在实施时遇到问题。这里有一些事情可能会出错:

  1. 如果在生成客户端令牌时指定customerId,则该令牌必须是有效的令牌。为首次使用的客户创建客户端令牌时,无需包含客户 ID。通常,您会在处理结帐表单的提交时创建一个客户,然后将该客户 ID 存储在数据库中以供以后使用。我将与我们的文档团队讨论如何澄清有关此的文档。
  2. res.write采用字符串或缓冲区。由于您正在编写 response.clientToken ,这是undefined的,因为它是使用无效的客户 ID 创建的,因此您收到first argument must be a string or Buffer错误。

其他一些注意事项:

  • 如果创建的令牌具有无效的customerId,或者处理请求时存在另一个错误,response.success将为 false,则可以检查响应以了解其失败的原因。
  • 您应该在 http 请求处理程序中生成客户端令牌,这将允许您为不同的客户生成不同的令牌,并更好地处理由请求引起的任何问题。

以下代码应该有效,前提是您指定了有效的customerId

http.createServer(function(req,res){
  // a token needs to be generated on each request
  // so we nest this inside the request handler
  gateway.clientToken.generate({
    // this needs to be a valid customer id
    // customerId: "aCustomerId"
  }, function (err, response) {
    // error handling for connection issues
    if (err) {
      throw new Error(err);
    }
    if (response.success) {
      clientToken = response.clientToken
      res.writeHead(200, {'Content-Type': 'text/html'});
      // you cannot pass an integer to res.write
      // so we cooerce it to a string
      res.write(clientToken);
      res.end("<p>This is the end</p>");
    } else {
      // handle any issues in response from the Braintree gateway
      res.writeHead(500, {'Content-Type': 'text/html'});
      res.end('Something went wrong.');
    }
  });
}).listen(8000, '127.0.0.1');