直接从 Braintree 的教程中复制,您可以使用这样的客户 ID 创建客户端 token :
gateway.clientToken.generate({
customerId: aCustomerId
}, function (err, response) {
clientToken = response.clientToken
});
我声明 var aCustomerId = "customer"
但 node.js 因错误而关闭
new TypeError('first argument must be a string or Buffer')
当我尝试在没有 customerId 的情况下生成 token 时,一切正常(尽管我从未获得新的客户端 token ,但这是另一个问题)。
编辑:这是所要求的完整测试代码:
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 工作 :)
得知您在实现过程中遇到问题,我们深感遗憾。这里可能会出现一些问题:
- 如果您在生成客户端 token 时指定了
customerId
,则它必须是有效的。在为第一次创建客户 token 时,您不需要包含客户 ID。通常你会创建 create a customer在处理结帐表单的提交时,然后将该客户 ID 存储在数据库中以供以后使用。我将与我们的文档团队讨论澄清有关此问题的文档。 -
res.write
接受一个字符串或一个缓冲区。由于您正在编写response.clientToken
,它是undefined
,因为它是使用无效的客户 ID 创建的,因此您收到的第一个参数必须是字符串或缓冲区
错误。
其他一些注意事项:
- 如果您使用无效的
customerId
创建 token ,或者在处理您的请求时出现另一个错误,response.success
将为 false,然后您可以检查响应失败的原因。 - 您应该在 http 请求处理程序中生成您的客户端 token ,这将允许您为不同的客户生成不同的 token ,并更好地处理您的请求导致的任何问题。
如果您指定了有效的 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');
关于javascript - 无法使用客户 ID 创建 Braintree 客户端 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26986158/