Unable to send Post Request on Google Apps Script

Issue

I am trying to send a post request to verify a transaction. I sent the same post request with Postman and I got a response as shown below:

enter image description here
enter image description here

Apps Script Code.gs:

function postRequest() {
    var url = "https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx/api/v2/verify";
    var options = {
        "method": "post",
        "headers": {
            "Content-Type": "application/json"
        },
        "payload": {
            "SECKEY": "FLWSECK-e6db11d1f8a6208de8cb2f94e293450e-X",
            "txref": "MC-1520443531487"
        }
    };

    const response = UrlFetchApp.fetch(url, options);

    Logger.log(JSON.stringify(response));
}

Apps Script Error Response:

Request failed for
https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx/api/v2/verify
returned code 400.

Truncated server response: SyntaxError: Unexpected token S
 
 at parse
(/app/node_modules/body-parser/lib/types/json.js:83:15)
 
 at /app/node_mod… (use muteHttpExceptions option to examine
full response) (line 299, file “Code”)

What am I doing wrong or How do I send a post request in Google Apps Script?

Solution

The UrlFetchApp.fetch() function has an unusual quirk in that you have to use the contentType property to set the content type of the payload. For some reason, setting the header directly doesn’t seem to work.

In addition you need to JSON.stringify() your payload.

So rewrite your post request as follows:

function verify() {
    var url = "https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx/api/v2/verify";

    var options = {
        "method":"POST",
        "contentType":"application/json",
        "payload":JSON.stringify({
            "SECKEY":"[YOUR-SECRET-KEY]",
            "txref":"[YOUR-TXREF-CODE]"
        })
    };

    return JSON.parse(UrlFetchApp.fetch(url, options));
}

Note that I omitted the key and code with placeholder text. You really shouldn’t share that kind of sensitive information. If possible I strongly recommend revoking those keys and have the service vendor issue new ones.

Answered By – TheAddonDepot

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.