我通过 Braintree 进行了定期付款,一切正常。我的代码如下所示:
app.post("/create_customer", function (req, res) {
var customerRequest = {
firstName: req.body.first_name,
lastName: req.body.last_name,
creditCard: {
number: req.body.number,
cvv: req.body.cvv,
expirationMonth: req.body.month,
expirationYear: req.body.year,
billingAddress: {
postalCode: req.body.postal_code
}
}
};
gateway.customer.create(customerRequest, function (err, result) {
console.log(result);
if (result.success) {
res.send(
"<h1>Customer created with name: " + result.customer.firstName + " " + result.customer.lastName + "</h1>" +
"<a href=\"/subscriptions?id=" + result.customer.id + "\">Click here to sign this Customer up for a recurring payment</a>"
);
} else {
res.send("<h1>Error: " + result.message + "</h1>");
}
});
});
app.get("/subscriptions", function (req, res) {
var customerId = req.query.id;
gateway.customer.find(customerId, function (err, customer) {
if (err) {
res.send("<h1>No customer found for id: " + req.query.id + "</h1>");
} else {
var subscriptionRequest = {
paymentMethodToken: customer.creditCards[0].token,
planId: "reccuringtest"
};
gateway.subscription.create(subscriptionRequest, function (err, result) {
res.send("<h1>Subscription Status " + result.subscription.status + "</h1>");
});
}
});
});
app.post("/create_transaction", function (req, res) {
var saleRequest = {
amount: "1000.00",
creditCard: {
number: req.body.number,
cvv: req.body.cvv,
expirationMonth: req.body.month,
expirationYear: req.body.year
},
options: {
submitForSettlement: true
}
};
gateway.transaction.sale(saleRequest, function (err, result) {
console.log(err, result);
if (result.success) {
res.send("<h1>Success! Transaction ID: " + result.transaction.id + "</h1>");
} else {
res.send("<h1>Error: " + result.message + "</h1>");
}
});
});
我可以进行客户和付款,然后添加 webhook:
app.get("/webhooks", function (req, res) {
res.send(gateway.webhookNotification.verify(req.query.bt_challenge));
});
app.post("/webhooks", function (req, res) {
gateway.webhookNotification.parse(
req.body.bt_signature,
req.body.bt_payload,
function (err, webhookNotification) {
console.log("[Webhook Received " + webhookNotification.timestamp + "] | Kind: " + webhookNotification.kind + " | Subscription: " + webhookNotification.subscription.id);
}
);
res.send(200);
});
现在,当我付款时,会调用 post 函数,但出现 csrf 错误:
POST/webhooks 403 194.783 毫秒 - -
错误:CSRF token 不匹配
在 csrf (/root/waitero/node_modules/lusca/lib/csrf.js:48:18)
感谢您的帮助!
最佳答案
您需要为从 Braintree 接收帖子的路由禁用 CSRF 保护。最好的方法可能是 writing a custom middleware :
var expressCsrf = express.csrf();
var customCsrf = function (req, res, next) {
if (req.path == "/webhooks") {
expressCsrf(req, res, next);
} else {
next();
}
}
app.use(customCsrf);
关于javascript - 带有 csrf 的 Braintree webhooks 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29067255/