2

How can I convert this curl code to a javascript post request that works for all browser

curl https://connect.stripe.com/oauth/token \
-d client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB \
-d code="{AUTHORIZATION_CODE}" \
-d grant_type=authorization_code

after some research and review of this answer Convert command curl to javascript , i see that i can implement the request as so

$.ajax({
 url: "https://connect.stripe.com/oauth/token",
beforeSend: function(xhr) { 
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); 
},
type: 'POST',
dataType: 'json',
contentType: 'application/json',
processData: false,

success: function (data) {
console.log(JSON.stringify(data));
},
  error: function(){
 console.log(error)
} 
});

how do I add the client_secret, code and grant_type?

jone2
  • 191
  • 1
  • 4
  • 18
  • how are they browser specific? They all run JavaScript.... – epascarello Mar 20 '18 at 12:17
  • Do you need this specific snippet to be converted to a JavaScript AJAX? It's not entirely clear. – Minzkraut Mar 20 '18 at 12:18
  • "most are browser specific"...how so? I would be interested to see these questions.. Anyway there are _lots_ of examples of creating ajax requests available online. The only real difference between browsers is how you declare the XHR object in IE vs. every other browser. That's trivial to search for. 99% of examples will show this. Or of course lots of JS libraries exist which provide friendlier wrappers round the native XHR object, so if you use those you don't even have to think about that (and other issues). How much research have you done, exactly? – ADyson Mar 20 '18 at 12:18
  • 1
    Stripe has a JavaScript SDK anyway. – TheValyreanGroup Mar 20 '18 at 12:28

1 Answers1

2

Its not entirely clear what you're asking for. But here are snippets to make this post request with
JQuery

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://connect.stripe.com/oauth/token",
  "method": "POST",
  "headers": {
    "content-type": "application/x-www-form-urlencoded",
    "cache-control": "no-cache",
  },
  "data": {
    "client_secret": "sk_test_f7PKXx5NRBFG5r41nTrPT7qB",
    "code": "\"{AUTHORIZATION_CODE}\"",
    "grant_type": "authorization_code"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

or vanialla JavaScript:

var data = "client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB&code=%22%7BAUTHORIZATION_CODE%7D%22&grant_type=authorization_code";

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "https://connect.stripe.com/oauth/token");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("cache-control", "no-cache");

xhr.send(data);
Minzkraut
  • 2,149
  • 25
  • 31