简体   繁体   中英

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

I am following this package: https://github.com/googleads/google-ads-php . Here they said that I need to run this page:

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

to terminal.

and I did it like:

php /locaation of the fie/GenerateUserCredentials.php

After that I can get a link which is something like that:

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

(Above link is demo purpose)

So, When I click on this link I redirect to my google account and give access to them and after that I redirect back to this following URL:

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

Here you can see I have 2 params which is state and code .

Now my question is how can I get the access token and refresh token using this URL?

Here you can see I have 2 params which is state and code .

Now you can use them to get tokens. Here is an example from the google-ads-php source code (open the link for the full example/code):

// 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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