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

我是研究僧i 提交于 2019-12-23 02:46:15

问题


First off, please forgive me if this is considered vague, this is my first time posting to Stack Exchange.

Hopefully, this is not a poorly formed question, I did give it some thought, though it assumes familiarity with CURL, Stripe and Angular.

On to the problem:

I am trying to recreate the results of a CURL to the Stripe API with Angular.js's $http and having some trouble doing so.

Using CURL, I am able to create a card token as follows:

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

This gives me something like "tok_blahblahbcryptnonsense"

However, I cannot seem to translate this CURL into an Angular $http function, and I am getting back a status code 400, with the message "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
  })

As far as my understanding goes, this is totally possible. All I need is to create a token for said card. It is getting late and it might be a totally obvious solution and I'm too tired.


回答1:


Maybe the Stripe API also accepts JSON, but what you're sending in your curl command is not JSON. It's form data.

Moreover, params is used to pass data in the query string. You want this data in the POST body.

The correct code should be:

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),
});


来源:https://stackoverflow.com/questions/36953964/angular-and-stripe-cant-create-card-token-using-http-but-can-using-curl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!