Samuel Policar
Samuel Policar

Reputation: 13

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

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.

Upvotes: 1

Views: 1077

Answers (1)

JB Nizet
JB Nizet

Reputation: 691785

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

Upvotes: 1

Related Questions