Search code examples
google-apigoogle-api-php-clientgoogle-ads-api

How to enable offline access to customer data in google adwords api php


Google Adwords API (PHP Client)

I am trying to get a user to authorize once on my website to be able to get his data for analytical purposes. But I can not figure out a way to do it with the documentation it is quite complex.

Do I need to add them to my mcc to be able to do this or is there another way using something like https://developers.google.com/identity/protocols/OAuth2WebServer


Solution

  • You will have to connect the user via oauth token with offline access activated, so that the request returns a refresh token, that you can use to programmatically access the connection, even if the user is not logged into you application:

    $client->setApprovalPrompt('force');
    $client->setAccessType('offline'); 
    

    As explained here https://developers.google.com/adwords/api/docs/guides/authentication you can use the oauth playground from groogle to test the api and see what you need.

    Additionally here is an example for the client connection method (partially Laravel specific code, but should be good enough to explain the procedure):

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

    You can use this method then in your oauth connecting routine:

    //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();
         }
     }
    }
    

    Good luck!