Search code examples
phprestcurlgoogle-apirefresh-token

Google API curl to get refresh token in php


I am using php and curl to retrieve review data and want to automate the process of getting access tokens using a refresh token. I understand how to do this using http/rest as documented here:

https://developers.google.com/identity/protocols/oauth2/web-server

I am trying to follow the "Refreshing an access token (offline access)" section and I know I need to do a POST request but am not sure how to do this with curl in php.

Here is what I have now:

function getToken($token_url){
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $token_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);

    $result = curl_exec($ch);
}

$token_url = "https://oauth2.googleapis.com/token" . "&client_id=" . $client_id . "&client_secret=" . $client_secret . "&refresh_token=" . $refresh_token . "&grant_type=" . $grant_type;
getToken($token_url);

Solution

  • So looking at the documentation provided, to perform the HTTP/REST request in PHP with the CURL module the code would look something like this:

    function getToken($token_url, $request_data) {
    
        $ch = curl_init($token_url);
    
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request_data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/x-www-form-urlencoded"
        )); 
    
        $result = curl_exec($ch);
    }
    
    $token_url = "https://oauth2.googleapis.com/token";
    
    $request_data = array(
        "client_id" => $client_id,
        "client_secret" => $client_secret,
        "refresh_token" => $refresh_token,
        "grant_type" => "refresh_token" // Constant for this request
    );
    getToken($token_url, $request_data);