Angular 和 Stripe,无法使用 $http 创建卡片令牌,但可以使用 CURL

Angular and Stripe, Can't create Card token using $http, but can using CURL

首先,如果这被认为含糊不清,请原谅我,这是我第一次在 Stack Exchange 上发帖。

希望这不是一个结构不佳的问题,我确实考虑过它,尽管它假定熟悉 CURL、Stripe 和 Angular。

关于问题:

我正在尝试使用 Angular.js 的 $http 重新创建 Stripe API 的 CURL 结果,但遇到了一些问题。

使用 CURL,我可以创建一个卡片令牌,如下所示:

curl -X POST https://api.stripe.com/v1/tokens \
   -u MY_TEST_KEY: \
   -d "card[number]"=4242424242424242 \
   -d "card[exp_month]"=12 \
   -d "card[exp_year]"=2017 \
   -d "card[cvc]"=123

这给了我类似 "tok_blahblahbcryptnonsense"

但是,我似乎无法将此 CURL 转换为 Angular $http 函数,我收到了状态代码 400,消息为 "You must pass full card details to create a token."

$http({
    method: 'POST',
    url: 'https://api.stripe.com/v1/tokens',
    headers: {
      'content-type': 'application/json',
      'Authorization': 'Bearer MY_TEST_KEY'
    },
    params: {
       card: {
          "number": '4242424242424242', // I have tried this as
                                       // an integer and string
                                      // Stripe docs say string
          "exp_month": 12,
          "exp_year": 2017,

          "cvc": '123'    // I have tried this as
                         // an integer and string
                        // Stripe docs don't specify but I think string
       }
    }
  }).then(function(success){
      console.log('success ', success)
  }, function(error){
      console.log('error ', error) // gets here, this is where the message is
  })

据我了解,这是完全有可能的。我只需要为所述卡创建一个令牌。时间不早了,这可能是一个完全显而易见的解决方案,我太累了。

也许 Stripe API 也接受 JSON,但您在 curl 命令中发送的不是 JSON。是表单数据。

此外,params用于在查询字符串中传递数据。您希望此数据位于 POST 正文中。

正确的代码应该是:

var myData = {
  card: {
    "number": '4242424242424242', 
    "exp_month": 12,
    "exp_year": 2017,
    "cvc": '123'
  }
};
$http({
  method: 'POST',
  url: 'https://api.stripe.com/v1/tokens',
  headers: {
    'Authorization': 'Bearer MY_TEST_KEY',
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: $httpParamSerializerJQLike(myData),
});