Contents

google api 授权及使用 总结

控制台中的操作

创建项目

https://static.duan1v.top/images/20230216223857.png

在库中选择需要的api,并启用

https://static.duan1v.top/images/20230216224808.png

Oauth 同意屏幕配置授权应用基础信息及可调用接口范围

  • 个人账号只能配置为外部用户,需要配置测试用户及发布为正式应用;google suit的用户可以配置为内部用户
  • 第一页配置些应用的基本信息
  • 第二页配置的是授权后,应用内可以调用的接口
  • 个人账号只能配置为外部用户,需要配置测试用户,可以是自己的账号
https://static.duan1v.top/images/20230216225207.png

配置凭据

OAuth客户端授权

  • 需要通过下载的凭据生成授权跳转链接,获取code,生成token.json

  • 新建web应用类型的凭据,并配置授权完成后的跳转地址,可以写需要的授权那个页面地址,本地可以配置为localhost

  • 下载凭证

https://static.duan1v.top/images/20230216230330.png https://static.duan1v.top/images/20230217000810.png

服务端授权

  • 本意是通过公私钥匹配,使应用中可以在服务端直接调用接口,无需进行授权交互

  • 创建完成后要继续编辑,添加密钥,及配置全网域(个人账号无法配置)

https://static.duan1v.top/images/20230216231734.png https://static.duan1v.top/images/20230216233017.png

测试用例

引入google api包

1
composer require google/apiclient:^2.12.1

使用凭据

客户端授权

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php

require __DIR__ . '/vendor/autoload.php';

use Google\Client;
use Google\Service\Gmail;

function getLabels()
{
    $client = new Client();
    $client->setApplicationName('Gmail API PHP Quickstart');
    $client->setScopes('https://www.googleapis.com/auth/gmail.readonly');
    $client->setAuthConfig("client_secret.json");
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');
    $tokenPath = "token.json";
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    } else if ($authCode = $_GET["code"]) {
        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        $client->setAccessToken($accessToken);

        // Check to see if there was an error.
        if (array_key_exists('error', $accessToken)) {
            throw new \Exception(join(', ', $accessToken));
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            header("Location: " . $authUrl);
        }
    }
    try {
        $service = new Gmail($client);
        // Print the labels in the user's account.
        $user = 'me';
        $results = $service->users_labels->listUsersLabels($user);

        if (count($results->getLabels()) == 0) {
            print "No labels found.\n";
        } else {
            print "Labels:\n";
            foreach ($results->getLabels() as $label) {
                printf("- %s\n", $label->getName());
            }
        }
    } catch (\Exception $e) {
        echo "Message: " . $e->getMessage();
    }
}

getLabels();
  • 页面授权
https://static.duan1v.top/images/20230217001106.png https://static.duan1v.top/images/20230217001518.png

服务端授权

1
2
3
$gmailService = new Google_Service_Gmail($client);

$labels = $gmailService->users_labels->listUsersLabels("me");
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
PHP Fatal error:  Uncaught Google\Service\Exception: {
  "error": {
    "code": 400,
    "message": "Precondition check failed.",
    "errors": [
      {
        "message": "Precondition check failed.",
        "domain": "global",
        "reason": "failedPrecondition"
      }
    ],
    "status": "FAILED_PRECONDITION"
  }
}

调试接口

https://static.duan1v.top/images/20230217005004.png
coffee