【问题标题】:Google apps script web application and OAuth authorization (PHP)Google 应用程序脚本 Web 应用程序和 OAuth 授权 (PHP)
【发布时间】:2015-05-23 03:58:51
【问题描述】:

我需要在没有任何用户交互的情况下从我的 php 服务调用我的 GAS Web 应用程序:

  1. 脚本与项目关联
  2. 我从开发者控制台 (http://note.io/1dq51gI) 获得的所有凭据
  3. 在 php 中,我获得了访问令牌(令牌适用于其他 google 服务)
  4. 我尝试将 get 查询发送到我的脚本,总是得到 401 响应 (http://puu.sh/hX9VJ/fdce874ff5.png)
  5. 这是部署设置 - http://puu.sh/hXa5h/a4c8ad4ff2.png(作为访问应用的用户执行,访问任何人)
  6. 在 php 中我使用 google php 客户端库

这是我的 php 代码:

    $client = new Google_Client();
    $client->setApplicationName('my app');
    $client->setClientId('my-id.apps.googleusercontent.com');

    $cred = new Google_Auth_AssertionCredentials(
        'me@developer.gserviceaccount.com',
        ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive.scripts'],
        file_get_contents(__DIR__ . '/google-app-key.p12')
    );

    $client->setAssertionCredentials($cred);

    if($client->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }

    $objToken  = json_decode($client->getAccessToken());
    $accessToken = $objToken->access_token;

    $curl = curl_init();

    $header = [];
    $header[] = 'Content-type: application/json';
    $header[] = 'Authorization: Bearer '.$accessToken;

    curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
    curl_setopt($curl, CURLOPT_POST,true);
    curl_setopt($curl, CURLOPT_URL, 'https://script.google.com/macros/s/script-id/exec?query-params');

    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9");

    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);

    curl_setopt($curl, CURLOPT_SSLVERSION, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);


    $rest  = curl_exec($curl);
    $error = curl_error($curl);
    $info  = curl_getinfo($curl);

    curl_close($curl);

我总是收到 google 的 401 响应,这是个问题。

谢谢!

【问题讨论】:

  • 使用Authorization: OAuth token 标题我有相同的结果..

标签: php oauth google-apps-script


【解决方案1】:

   从服务器端调用的内容服务脚本不适用于“用户访问网络应用”。这是因为脚本需要来自用户的 google cookie SID、HSID、SSID 的其他信息才能像他们一样运行脚本。这就是为什么您可以在类似 hurl.it 的代码中测试代码的原因,看起来这是可能的,但是来自 cURL 的相同调用将失败。

   如果您从服务器调用脚本,则必须将其设置为以“我”身份执行。您在标头中传递的 Oauth 令牌将用于“谁有权访问应用程序”选项。

【讨论】:

  • 嘿!谢谢您的回答。我将部署设置更改为execute as me and access anyone。但是还有另一个错误 - 您没有执行此操作的权限。我尝试使用控制台项目中的帐户登录..
  • 这可能意味着您没有正确的范围,或者您没有为您调用它的帐户授权您的脚本。
猜你喜欢
  • 2020-02-05
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
  • 2022-09-08
  • 2015-02-15
  • 2020-11-05
相关资源
最近更新 更多