-1

I am trying to connect my Google Sheet to a PHP script using a Google Apps Script. This requires sending payload with the UrlFetchApp function. And, this is where the connection betweenn Script and PHP goes wrong.

The connection works, when I replace the echo value in the PHP script to a non variable, there is a response. Also, my response code is 200. But, sending or reading my payload is the problem.

Google Apps Script:

var payload = {"A": "12345"};
var url = 'myurl/stats.php'
var response = UrlFetchApp.fetch(
        url,
        {
          "method": "GET",
          "contentType": "application/json",
          "payload": JSON.stringify(payload),
        }
      );
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();

Logger.log(responseCode);
Logger.log(responseBody); 

PHP:

<?php 
$A = $_GET["A"];
echo json_encode("Hello: ".$A);
?>

Note: Using a browser, this PHP script is working.

I expect responseBody to be "Hello: 12345" but the actual output is "Hello: "

George
  • 43
  • 1
  • 12
  • Your GA script does not make a request in the form `foo.php?A=123`, but sends the data as `application/json` - so PHP will not populate `$_GET`. You need to read the data from the input stream and decode the JSON yourself, before you can access individual values. https://stackoverflow.com/questions/18866571/receive-json-post-with-php explains how to do that for POST requests. (And you should make yours a POST as well, because GET requests are not really supposed to have a body in the first place, see https://stackoverflow.com/a/983458/10283047) – misorude Jan 14 '19 at 11:58

1 Answers1

2

Simple modify your php code for send response

var payload = {"A": "12345"};
var url = 'myurl/stats.php?A=' + payload.A;
var response = UrlFetchApp.fetch(
        url,
        {
          "method": "GET",
          "contentType": "application/json",
          "payload": JSON.stringify(payload),
        }
      );
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();

Logger.log(responseCode);
Logger.log(responseBody); 


<?php 
$A = $_GET["A"];
echo json_encode(["Hello" => $A]);
// echo json_encode("Hello: ".$A);
?>
Aman Kumar
  • 4,096
  • 2
  • 13
  • 37