我正在尝试使用stripe.js并在将其保存在服务器上后返回创建的费用。条带费用成功保存并保存在我的条带测试帐户中,但似乎回调无法正常工作。从我下面的代码中,调用console.log('success'),但是没有调用“then”回调,并且也没有调用console.log('savedChanges')。难道我做错了什么?我正在关注https://stripe.com/docs/tutorials/charges以供参考。
/app/scripts/controllers/stripe.js
'use strict';
app.controller('StripeCtrl', function ($scope, $location, $http) {
$scope.charge = {};
$scope.successfulCharge = null;
$scope.submitCharge = function(status, response){
var $form = $('#payment-form');
if (response.error) {
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
var token = response.id;
var data = {
amount: ($scope.charge.amount * 100),
card: token,
description: "2014 missions donation for " + $scope.charge.missionary,
metadata: {
'email': $scope.charge.email,
'missionary': $scope.charge.missionary
}
};
$http.post('/api/stripe/submitCharge', data).success(function(data, status, headers) {
console.log('submitCharge success!!!');
console.log(data);
$scope.successfulCharge = data;
});
}
}
$scope.getCharges = function(){
$http.get('/api/charges').success(function(charges) {
return charges;
});
}
});
/lib/controllers/api.js
'use strict';
var mongoose = require('mongoose'),
config = require('../config/config'),
stripe = require('stripe')(config.stripe.secret_key),
Charge = mongoose.model('Charge');
exports.charges = function(req, res) {
return Charge.find(function (err, charges) {
if (!err) {
return res.json(charges);
} else {
return res.send(err);
}
});
};
exports.publishable_key = function(req, res){
return res.send(config.stripe.publishable_key);
};
exports.submitCharge = function(req, res){
var savedCharge;
var result = stripe.charges.create({
amount: req.body.amount,
currency: "usd",
card: req.body.card,
description: req.body.description
}, function(err, charge) {
if (err) {
console.log('errors');
console.log(err);
} else {
console.log('success');
}
}).then(function(charge){
savedCharge = Charge.create({
name: charge.card.name,
amount: charge.amount,
email: charge.metadata.email,
address: charge.card.address_line1 + charge.card.address_line1,
city: charge.card.address_city,
state: charge.card.address_city,
zip: charge.card.address_zip,
tax_receipt: charge.metadata.tax_receipt,
missionary: charge.metadata.missionary,
});
});
console.log('savedCharge');
console.log(savedCharge);
return res.send(savedCharge);
};
答案 0 :(得分:4)
看起来Stripe API可让您使用回调或承诺,但您在charges.create
的通话中同时使用这两项:
var result = stripe.charges.create({
...data...
}, function (err, charge) { // <-- callback
...
}).then(function(charge) { // <-- promise
...
})
您需要选择其中一个。也就是说,要么将Charge.create
的调用放在stripe.charges.create
(您的console.log('success')
所在的回调)内,要么通过向{{1}提供第二个参数来将错误处理移到promise中。声明:具有then()
参数的函数。