0
votes

I am trying to call FreshChat API from google apps script. GET request of outbound-messages is working fine but POST request is failing with error

Exception: Request failed for http://api.in.freshchat.com returned code 400. Truncated server response: {"success":false,"errorCode":0,"errorMessage":"HTTP 405 Method Not Allowed","errorData":null,"errorName":null} (use muteHttpExceptions option to examine full response)

Below are the details of request

function myFunctiontest() {
  var url = "http://api.in.freshchat.com/v2/outbound-messages/whatsapp";
  var headersPOST = { 
          'Authorization': 'Bearer XXXXXX',
          'Content-Type': 'application/json',
          'Accept': 'application/json'
          };
  var bodyPayload = {"from": {"phone_number": "+XXXXXX"},"provider": "whatsapp","to": [{"phone_number": "+XXXXX"}],"data": {"message_template": {"storage": "none","template_name": "XXXXXX","namespace": "XXXXX","language": {"policy": "deterministic","code": "en"},"template_data": [{"data": "XXXXX"}]}}};
var options = {
        'method': 'post',
        'contentType': 'application/json',
        'headers': headersPOST,
        'payload': JSON.stringify(bodyPayload),
        'muteHttpExceptions':true
};

  var response = UrlFetchApp.fetch(url, options);
  console.log(response.getAllHeaders());
  Logger.log(JSON.parse(response.getContentText()));
}

Same headers are working for GET request. Also same post request is working from POSTMAN.

1

1 Answers

0
votes

Freshchat support helped for solving the issue.

There are two major changes

  1. use https instead of http
  2. Added contentType inside headers.

function myFunctiontest() {
    
    var url = "https://api.in.freshchat.com/v2/outbound-messages/whatsapp";
      var headersPOST = 'Bearer XXXXXX';
    
      var bodyPayload = {"from": {"phone_number": "+XXXXXX"},"provider": "whatsapp","to": [{"phone_number": "+ XXXXX"}],"data": {"message_template": {"storage": "none","template_name": "XXXXXX","namespace": "XXXXX","language": {"policy": "deterministic","code": "en"},"template_data": [{"data": "XXXXX"}]}}};
    var options = {
            method: 'POST',
            //content-type: 'application/json',
            headers: { Authorization: headersPOST, 'content-type': 'application/json'},
            payload: JSON.stringify(bodyPayload),
            muteHttpExceptions:true
    };
    
      var response = UrlFetchApp.fetch(url, options);
      var text = response.getResponseCode();
    }