Google Adwords API(PHP客户端)
我试图让用户在我的网站上进行一次授权,以便能够获取他的数据用于分析目的。但我无法找到一种方法来处理它非常复杂的文档。
我是否需要将它们添加到我的mcc才能执行此操作,或者使用https://developers.google.com/identity/protocols/OAuth2WebServer
等其他方式答案 0 :(得分:0)
您必须通过oauth令牌连接用户并激活离线访问,以便请求返回刷新令牌,您可以使用该令牌以编程方式访问连接,即使用户未登录您的应用程序:
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
如此处https://developers.google.com/adwords/api/docs/guides/authentication所述,您可以使用groogle的oauth游戏来测试api并查看您需要的内容。
此外,这里是客户端连接方法的一个示例(部分是Laravel特定代码,但应该足以解释该过程):
function googleIntegrationClient($refresh=false)
{
$client = new \Google_Client();
$client->setClientId(env('GOOGLE_OAUTH_CLIENT_ID'));
$client->setClientSecret(env('GOOGLE_OAUTH_CLIENT_SECRET'));
$client->setRedirectUri(env('GOOGLE_OAUTH_REDIRECT_URI'));
$client->setApplicationName('App Google Integration');
$client->addScope("profile");
$client->addScope("email");
$client->addScope("https://www.googleapis.com/auth/adwords");
//make sure there is a refresh token in the request for offline access.
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
if($refresh)
{
//get currently logged in user
$user = \Auth::user();
//set token from user data
$client->setAccessToken($user->settings["integration"]["google"]['token_data']);
//check if token is valid
if($client->isAccessTokenExpired())
{
//as token is invalid set refresh token
$token_data = json_decode($user->settings["integration"]["google"]['token_data']);
$client->refreshToken($token_data->refresh_token);
//save new token data
$modify_settings = $user->settings;
$modify_settings["integration"]["google"]["token_data"] = $client->getAccessToken();
$user->settings = $modify_settings;
$user->save();
}
}
return $client;
}
您可以在oauth连接例程中使用此方法:
//route for redirecting to google oauth
public function redirectToProvider()
{
$user = \Auth::User();
$client = googleIntegrationClient();
$auth_url = $client->createAuthUrl();
return \Redirect::to(filter_var($auth_url, FILTER_SANITIZE_URL));
}
//callback route to handle the provided data from google oauth
public function handleProviderCallback(Request $request)
{
$user = \Auth::User();
$client = googleIntegrationClient();
$data = $request->all();
if (isset($data['code']))
{
try {
$client->authenticate($data['code']);
$token = $client->getAccessToken();
} catch (Exception $e) {
$user->settings = array(
"integration" => array(
"google" => array(
'active' => false,
)));
$user->save();
}
if($token)
{
$google_oauth = new \Google_Service_Oauth2($client);
$user->settings = array(
"integration" => array(
"google" => array(
'active' => true,
'token_data' => $token,
'id' => $google_oauth->userinfo->get()->id,
'avatar' => $google_oauth->userinfo->get()->picture,
'email' => $google_oauth->userinfo->get()->email,
'name' => $google_oauth->userinfo->get()->name,
)));
$user->save();
}
}
}
祝你好运!