user1856596
user1856596

Reputation: 7233

Calling Google App Script from PHP using curl?

I am trying to call my Google App from a PHP Script, this is the code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_URL, "https://script.google.com/macros/s/.../exec");
$res = curl_exec($ch); // $res = true

This calls the URL and the "Loading" screen from Google App Script is shown and thats it, nothing else happens. Calling the URL from the browser works, so it must be related to curl. Maybe I have to set another curl option?

Thanks!

Upvotes: 1

Views: 2350

Answers (2)

AHeraldOfTheNewAge
AHeraldOfTheNewAge

Reputation: 59

Here is an example for calling google apps script with a POST request

// set some post fields
$post = [
    'username' => 'user1',
    'password' => 'passuser1',
    'gender'   => 1,
];

$url = curl_init('https://script.google.com/macros/s/... your apps script url basically .../exec');
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_POSTFIELDS, $post);
curl_setopt($url, CURLOPT_FOLLOWLOCATION, true); //we must follow location -> google apps script makes a small redirect "for security reasons"

// execute!
$response = curl_exec($url);

// close the connection, release resources used
curl_close($url);

// do anything you want with your response
var_dump($response);

Upvotes: 1

jj-lucas
jj-lucas

Reputation: 143

This snippet below has worked wonders for me in the past:

$APPS_SCRIPT_URL = 'https://script.google.com/macros/s/.../exec';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $APPS_SCRIPT_URL); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$content = trim(curl_exec($ch));
curl_close($ch);          

Also, remember to properly authorize and publish your script for it to be executed by an anonymous user (your PHP script)

Upvotes: 0

Related Questions