Search code examples
google-apps-scriptpaypalpaypal-sandboxrestpaypal-rest-sdk

PayPal REST API Error 400 in Google Apps Script


I'm trying to create a subscription for my OnlyFans app using PayPal API.
I'm using the exact same body as when I'm using Postman.
Somehow I can get the response using Postman but I'm getting this error trying to do it via app script.
I've triple quadruple checked for any trailing commas, etc.
Can't seem to find any error in the format.

Why am I getting error code 400?
"name":"INVALID_REQUEST","message":"Request is not well-formed, syntactically incorrect...


function restCall (){
  
  var restEndpoint = "https://api-m.sandbox.paypal.com/v1/billing/subscriptions"
  
  var head = {
    "Authorization":"Bearer "+ TokenProperties.getAccessToken(),
    "Content-Type": "application/json",
    "PayPal-Request-Id": "1111-1111-1111-1111"
  }

  var postPayload = 
  {
    "plan_id": "P-09E19660L3543673CMETTBBA",
    "subscriber": {
      "name": {
        "given_name": "John",
        "surname": "Doe"
      },
      "email_address": "[email protected]"
    },
    "application_context": {
      "brand_name": "Test",
      "user_action": "SUBSCRIBE_NOW",
      "payment_method": {
        "payer_selected": "PAYPAL",
        "payee_preferred": "IMMEDIATE_PAYMENT_REQUIRED"
      },
      "return_url": "https://example.com/returnUrl",
      "cancel_url": "https://example.com/cancelUrl"
    }
  }

  var params = {
    headers:  head,
    method: "POST",
    payload : postPayload
  }

  var response = UrlFetchApp.fetch(restEndpoint, params); 
}

Solution

  • Try

      var options = {
        "contentType": "application/json",
        "method": "post",
        "headers": head,
        "payload": JSON.stringify(postPayload)
      };