如何在cURL中的变量中存储返回的Google应用脚本“doPost(e)”函数?

I have written a doPost(e) function on google app script that will return a number depending on the data that is sent through. The script returns a number, somewhat like this:

Google App Script Code:

doPost(e)
{
/* Code that does stuff with the parameters */
var results = 3;
var result_output = JSON.stringify(results);
var output = ContentService.createTextOutput(result_output).setMimeType(ContentService.MimeType.JSON);
return output;
}

This is my cURL code which sends appropriate values and aims to store the returned output from the Google App Script code in a variable to be used later in the program:

function connect_to_GAS() 
{
// Get cURL resource
$curl = curl_init();
// Set some options
curl_setopt_array($curl, array(
CURLOPT_URL => 'puturlhere',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
// add params here
)
));

curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // there is a redirect

// Send the request, save response to $resp

$resp = curl_exec($curl);

echo $resp;
}

When I return the $resp value it only ever returns "1" because the function was executed succesfully, but I can't get it to store the retuned value for some reason!!!

I have deployed it as a web app, and the Post function of the script does work, but my cURL side is not receiving the value as i'd like it to. Frustratingly, when I run my cURL script the value I need is displayed in the resultant web page but I have no way to access it.

Does anyone know how I can store the response???? Any help is MUCH appreciated!!

  1. First thing is that when ever you make a changes in your script, then it need to be saved as a new version and published again to get it effective.
  2. You are returning a number, but not a json. Try returning a proper json.
  3. For such cases I use guzzle.
  4. The 1 that you are getting as result has nothing to do with variable being returned from gs file. That 1 indicates curl has gone success.

Sample Code

In gs file

function doPost(e){
  //WHILE PRODUCTION
  //var postData = JSON.parse(e.postData.contents);
  //WHILE TESTING
  //var postData = e.postData.contents;
  return ContentService.createTextOutput(JSON.stringify({'status': 'success'})).
  setMimeType(ContentService.MimeType.JSON);
}

function test(){
  var payload = {
  "key1": "value1",
  "key2": "value2",
  }

  var e = {
    postData: {
    contents: payload
  }
 };
  var returned = doPost(e);
}

In php file

<?php
    session_start();
    require_once '../vendor/autoload.php';
    $client = new GuzzleHttp\Client(['verify'=>false]);
//  Webapp link
    $url = 'https://script.google.com/macros/s/yourwebapplink/exec';
    $payload = json_encode(array("key1" => "value1", "key2" => "value2"))
    $response = $client->request('POST', $url, ['json' => $payload]);
    $body = json_decode($response->getBody());
    print_r($body);
    return;
?>

It is easy to install guzzle if you are using composer