Google API + PHP + Ajax Call - Access-Control-Allow-Origin'标头出现在请求的资源

时间:2018-06-07 18:06:56

标签: php ajax api cross-domain

我使用Google API通过OAuth访问我的日历条目。 不幸的是,我收到以下错误(服务器是本地raspi):

  

无法加载https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id= **** - ****。apps.googleusercontent.com& redirect_uri = http%3A%2F%2Fopenhabianpi。 %2Fsmarthome%2Fphp%2Fscripts%2Fscript.oauth2callback.php&安培;状态&安培;范围= HTTPS%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly&安培; approval_prompt =经销商:响应预检请求没有按'吨通过访问控制检查:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。来源' http://openhabianpi '因此不允许访问。响应的HTTP状态代码为405。

我的脚本:

Ajax请求

var termine = function (){
     $.ajax({
        type: "POST",
        url: "php/ajax/ajax.termine.php",
        data: {
            action: 'get_termine'
        },n
        success: function(response) {
            console.log(response);
        }
    });
}

ajax.termine.php

require dirname(dirname(__FILE__)).'/vendor/autoload.php';

$client = new Google_Client();
$client->setAuthConfig(dirname(dirname(__FILE__)).'/config/client_secret.json');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $calendarId = 'primary';
  $optParams = array(
    'maxResults' => 10,
    'orderBy' => 'startTime',
    'singleEvents' => TRUE,
    'timeMin' => date('c'),
  );

  $service = new Google_Service_Calendar($client);
  $results = $service->events->listEvents($calendarId, $optParams);
  if (count($results->getItems()) == 0) {
    print "No upcoming events found.\n";
  } else {
    print "Upcoming events:\n";
    foreach ($results->getItems() as $event) {
      $start = $event->start->dateTime;
      if (empty($start)) {
        $start = $event->start->date;
      }
      printf("%s (%s)\n", $event->getSummary(), $start);
        echo date('c');
    }
  }
} else {
  $redirect_uri = 'http://openhabianpi.***.***/smarthome/php/scripts/script.oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

script.oauth2callback

<?php
require_once dirname(dirname(__FILE__)).'/vendor/autoload.php';
session_start();

$client = new Google_Client();
$client->setAuthConfigFile(dirname(dirname(__FILE__)).'/config/client_secret.json');
$client->setRedirectUri('http://openhabianpi.***.***/smarthome/php/scripts/script.oauth2callback.php');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://openhabianpi.***.***/smarthome/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

我尝试了以下内容,但遗憾的是没有成功:

  1.   

    dataType:&#39; jsonp&#39;,

  2.   

    标题(&#34; Access-Control-Allow-Origin:*&#34;);

  3. 在.htaccess或apache.conf中设置

  4.   

    Access-Control-Allow-Origin&#34; *&#34;

    提前感谢您的帮助!

4 个答案:

答案 0 :(得分:4)

(end_x, end_y)

答案 1 :(得分:0)

您无法使用AJAX执行OAuth身份验证,因为$client->createAuthUrl()返回的网址会显示登录页面。

您仍然可以按照以下步骤停留在同一页面上:

  • 在新标签页中打开ajax.termine.php

window.open('php/ajax/ajax.termine.php', '_blank');

  • 将重定向uri设置为仅包含Javascript的空白页。
  • 使用此javascript更改父网页网址。

window.top.location.href = 'http://openhabianpi.***.***/smarthome/';

答案 2 :(得分:0)

您只需访问您的Google开发者帐户,然后根据API凭据添加您的网络服务器地址或IP地址。

访问console.developers.google.com

然后选择您的项目。 然后选择凭据。然后选择您的API密钥。然后选择应用程序限制,然后选择HTTP引用程序地址并添加您的地址。

enter image description here

希望它能解决你的问题。

答案 3 :(得分:0)

以下脚本通过ajax工作(您必须使用服务帐户):

    <?php
    /**
    * Session aufbauen und user check
    */
    session_start();

    require dirname(dirname(__FILE__)).'/vendor/autoload.php'; //Google API via Composer

    $json_path = '***PATH to service account credential JSON***';

    $client = new Google_Client();

    $client->setAuthConfig($json_path);
    $client->useApplicationDefaultCredentials();
    $client->addScope(Google_Service_Calendar::CALENDAR_READONLY);

    $client->setApplicationName("***Your Appname***");

    $service = new Google_Service_Calendar($client);

    $calendarId = '***Your CAL ID***';
    $optParams = array(
       'maxResults' => 10,
        'orderBy' => 'startTime',
        'singleEvents' => TRUE,
        'timeMin' => date('c'),
    );

  $results = $service->events->listEvents($calendarId, $optParams);
  if (count($results->getItems()) == 0) {
    print "";
  } else {
    foreach ($results->getItems() as $event) {
      $start = $event->start->dateTime;
      if (empty($start)) {
        $start = $event->start->date;
      }

      $date = date("d.m.Y", strtotime($start));
      $time = date("G:i", strtotime($start));

      $today = date("d.m.Y");

      if ($date == $today){
        $array[] = array(
          "datum" => $date,
          "time" => $time,
          "termin" => $event->summary
        );
      }
    }
  }

  echo json_encode($array);