Search code examples
google-apps-scriptpaypal-sandbox

Google App Script - PayPal API - Get Access Token


I have this function that should give me the access token in cURL

curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
    -H "Accept: application/json" \
    -H "Accept-Language: en_US" \
    -u "client_id:secret" \
    -d "grant_type=client_credentials"

source:https://developer.paypal.com/docs/api/overview/#get-an-access-token

but when i try to run the function (that is supposed to be the same) in google app script the error is always: "invalid token". What am i doing wrong?

 function lol(){
   var request = UrlFetchApp.fetch("https://api.sandbox.paypal.com/v1/oauth2/token", {
     "Accept": "application/json",
     "Accept-Language": "en_US",
     "CLIENT_ID":"SECRET",
     "grant_type":"application/x-www-form-urlencoded"
   })
   Logger.log(request.getContentText());
 }

CLIENT_ID & SECRET are personal and copied from my PayPal account.


Solution

  • How about this modification?

    Modification points :

    • At UrlFetchApp, as Sandy Good said, you are required to explicitly designate the method. In your case, it's "POST".
    • At UrlFetchApp, the default Content-Type is application/x-www-form-urlencoded.
    • The option -u for curl command is the basic authorization.
    • The option -H for curl command is the header.
    • At the curl sample of PayPal, grant_type is client_credentials.

    The script which reflected above points is as follows.

    Modified script :

    function myFunction(){
      var client_id = "client_id"; // Please input your client_id
      var secret = "secret"; // Please input your client secret
    
      var options = {
        method: "post",
        headers : {
          "Authorization" : " Basic " + Utilities.base64Encode(client_id + ":" + secret),
          "Accept": "application/json",
          "Accept-Language": "en_US"
        },
        payload: {"grant_type": "client_credentials"}
      };
      var request = UrlFetchApp.fetch("https://api.sandbox.paypal.com/v1/oauth2/token", options);
      Logger.log(request.getContentText())
    }
    

    If this was not useful for you, I'm sorry.