繁体   English   中英

Google Ads API - 如何使用 PHP 获取访问和引用令牌

[英]Google Ads API - How to get the access and referesh token using PHP

我正在关注这个 package: https://github.com/googleads/google-ads-php 他们在这里说我需要运行这个页面:

https://github.com/googleads/google-ads-php/blob/main/examples/Authentication/GenerateUserCredentials.php

到终端。

我这样做是这样的:

php /locaation of the fie/GenerateUserCredentials.php

之后我可以获得一个类似这样的链接:

https://accounts.google.com/o/oauth2/v2/auth?response_type=code&access_type=offline&client_id=535777736006-d1rp8msevnls2pmihk7b8l23j3vra7duh.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fcallback&state=4e23ce963534701029c1a22d2de7848d034d8b0b0&scope= https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fadwords

(以上链接是演示目的)

因此,当我单击此链接时,我会重定向到我的谷歌帐户并授予对它们的访问权限,然后我会重定向回以下 URL:

http://localhost:3000/auth/callback?state=fddbaae6583b15aba552f682fe9f018233388533555f&code=4%2F0AfgeXvs4NV49mrqEBrl81ATRnXhqcu9x9ja8SAbaENSWhmNejGRGkZJE_AcD1aAFWdrlGg&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fadwords

在这里你可以看到我有 2 个参数,分别是statecode

现在我的问题是如何使用这个 URL 获取访问令牌和刷新令牌?

在这里你可以看到我有 2 个参数,分别是statecode

现在您可以使用它们来获取令牌。 这是来自 google-ads-php 源代码的示例(打开完整示例/代码的链接):

// Exit if the state is invalid to prevent request forgery.
$state = $request->getQueryParams()['state'];
if (empty($state) || ($state !== $oauth2->getState())) {
    throw new UnexpectedValueException(
        "The state is empty or doesn't match expected one." . PHP_EOL
    );
};

// Set the authorization code and fetch refresh and access tokens.
$code = $request->getQueryParams()['code'];
$oauth2->setCode($code);
$authToken = $oauth2->fetchAuthToken();

$refreshToken = $authToken['refresh_token'];
print 'Your refresh token is: ' . $refreshToken . PHP_EOL;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM