直接从Braintree的教程中复制,您可以使用以下客户ID创建客户端令牌:
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的令牌时,一切正常(虽然我从来没有得到新的客户端令牌,但这是另一个问题)。
编辑:以下是所要求的完整测试代码:
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');
答案 0 :(得分:21)
免责声明:我为Braintree工作:)
我很遗憾听到您的实施遇到问题。这里可能会出现一些问题:
customerId
,则它必须是有效的。在为初次使用客户创建客户端令牌时,您不需要包含客户ID。通常,您在处理提交结帐表单时会创建create a customer,然后将该客户ID存储在数据库中以供日后使用。我将与我们的文档团队讨论如何澄清相关文档。res.write
接受字符串或缓冲区。由于您撰写response.clientToken
undefined
,因为它是使用无效的客户ID创建的,因此您收到了first argument must be a string or Buffer
错误。其他一些说明:
customerId
创建令牌,或者处理您的请求时出现另一个错误,response.success
将为false,您可以检查响应是否失败。如果您指定有效的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');