尝试将PHP cURL帖子功能用于Google Apps脚本时出现401未经授权的错误

时间:2018-04-26 21:36:44

标签: php curl google-apps-script php-curl

我收到错误,"请求的网址返回错误:401 Unauthorized",在尝试将PHP cURL与Google Apps脚本一起使用时。

我一直在遵循以下指南,但似乎没有任何作用:
How do I post to a Google script with cURL in PHP and return text?
Posting data to google apps script using php/curl

我昨天发布了这个额外的问题,这帮助我弄清楚我需要设置所有SSL证书:
How to use Google Scripts with cURL PHP? [duplicate]

我的test.php页面:

<div id="body">
    <form name="testing" method="post">
        Email: <input type="text" name="email"><br>
        <input type="submit" value="Submit" onClick="return OnTest1();">
    </form>
</div>

<script>
    function OnTest1()
    {
        document.testing.action = "testsubmit.php";
        document.testing.submit();
        return true;
    }
</script>

我的testsubmit.php页面:

<?php   
    $url = 'https://script.google.com/a/meditech.com/macros/s/[SCRIPT ID]/exec';
    $data['email'] = $_POST['email'];
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_FAILONERROR,true);

    $result = curl_exec($ch);

    if(curl_error($ch))
    {
        echo curl_error($ch);
    }
    else
    {
        echo $result;
    }

    curl_close($ch);
?>

我的Google Apps脚本:

function doPost(e)
{
  return ContentService.createTextOutput(e.parameter.email);
}

我希望能够在某个时候将大量信息传递到我的php页面,以便处理成我已经设置的数据库,一旦它被转储到数据库中,我需要发送所有数据库将信息发送到Google Apps脚本然后发送电子邮件。

感谢任何可以提供帮助的人。

1 个答案:

答案 0 :(得分:1)

是的,使用Execute the app as: MyselfWho has access to the app: CompanyDomain.com非常好,但与此同时,您必须确保Google确定您仅来自CompanyDomain.com。你现在怎么样?

我认为您需要通过requset传递身份验证详细信息,可能类似于OAuth / 2令牌。首先获取正在发出请求的用户的令牌,然后在身份验证标头中传递该令牌,以便谷歌识别用户。

或者,如果您不想这样,那么您可以切换到Who has access to the app: Anyone, even anonymous,那么您无需证明自己的身份。

选择最适合您需求的产品。

您也可以在How to create a doPost(e) to receive data from an external service?

查看我的答案