2

FOR ANYONE FINDING THIs - this error was due to the .p12 being corrupt after downloading on a win7 box. After downloading to a unix machine the cert worked.

I have followed about a million different guides trying to get this to work.

I am trying to connect to the Google Analytics API with a service account.

I have the relevant "project" created in the console, given said project access to the relavent API's required.

In the credentials I have added the service account in the OAuth section, downloaded the p12 key and stored on server.

When I run the code:

//start the google v3 api server authorization with the .p12 key
    $client = new \Google_Client();
    $client->setApplicationName("AnalyticsAPI");

    $key = __DIR__ . '/google-keys/AnalyticsAPI-XXXXXX.p12';

    $credentials = new \Google_Auth_AssertionCredentials(
        '101XXXXXXXXXXXXXXXXXXXXXnq4omne@developer.gserviceaccount.com',
        array('https://www.googleapis.com/auth/analytics.readonly'),
        $key
    );
    $client->setAssertionCredentials($credentials);
    //auto refresh if old
    if($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($credentials);
    }

    //start the analytics shtuff
    $service = new \Google_Service_Analytics($client);  
    $accounts = $service->management_accountSummaries->listManagementAccountSummaries();

    //Adding Dimensions
    $params = array('dimensions' => 'ga:pagePath');
    // requesting the data
    $data = $service->data_ga->get("ga:$profile_id", $start_date,  $end_date, "ga:users,ga:sessions", $params );

    print_r($data);

The error is thrown from the "Google/Signer/P12.php on line 52"

Unable to parse the p12 file. Is this a .p12 file? Is the password correct? OpenSSL error: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag in /XXXXX/classes/google-api-php-client-master/src/Google/Signer/P12.php on line 52

The error is thrown from ...Signer/P12.php @ 49:

// This throws on error
      $certs = array();
      if (!openssl_pkcs12_read($p12, $certs, $password)) {
        throw new Google_Auth_Exception(
            "Unable to parse the p12 file.  " .
            "Is this a .p12 file?  Is the password correct?  OpenSSL error: " .
            openssl_error_string()
        );
      }

When i extract the relavent code attempting to read the .p12 file and run on its own i get the same error:

$certs = array();
    openssl_pkcs12_read($key, $certs, 'notasecret');
    print_r($certs);
    echo openssl_error_string();
    die(x);


Array ( ) error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag

I'm completely stumped. Reading some other posts on the issue like this one: Getting "Unable to parse the p12 file..." Error With google-api-php-client

I have tried

  1. Ensuring permissions are correct.
  2. file_get_contents($key) and then passing to the openssl_pkcs12_read which yields the same results!

Does anyone have any clues?

Community
  • 1
  • 1

1 Answers1

1
  1. Make sure you have the latest clint lib from github
  2. give The service account email address access to read Google Analytics at the ACCOUNT level
  3. Try this tutorial Google Service Account with PHP

    session_start();        
    require_once 'Google/Client.php';
    
    require_once 'Google/Service/Analytics.php';    
    
    /************************************************   
    The following 3 values an befound in the setting    
    for the application you created on Google       
    Developers console.      Developers console.
    The Key file should be placed in a location  
    that is not accessable from the web. outside of 
    web root.        web root.
    
    In order to access your GA account you must 
    Add the Email address as a user at the  
    ACCOUNT Level in the GA admin.      
    ************************************************/
    
    $client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
    $Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com';     
    $key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';     
    $client = new Google_Client();      
    $client->setApplicationName("Client_Library_Examples");
    
    $key = file_get_contents($key_file_location);   
    
    // seproate additional scopes with a comma   
    $scopes ="https://www.googleapis.com/auth/analytics.readonly";  
    
    $cred = new Google_Auth_AssertionCredentials(
    
        $Email_address,      
    array($scopes),     
    $key         
    );      
    $client->setAssertionCredentials($cred);
    if($client->getAuth()->isAccessTokenExpired()) {        
            $client->getAuth()->refreshTokenWithAssertion($cred);       
    }       
    $service = new Google_Service_Analytics($client);
    $accounts = $service->management_accountSummaries->listManagementAccountSummaries();
    
    //calulating start date  
    $date = new DateTime(date("Y-m-d"));     
    $date->sub(new DateInterval('P10D'));    
    //Adding Dimensions
    $params = array('dimensions' => 'ga:userType'); 
    // requesting the data  
    $data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params );  
    ?><html>     
    <?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>    
    <table>  
    <tr>     
    <?php    
    //Printing column headers
    foreach($data->getColumnHeaders() as $header){
            print "<td>".$header['name']."</td>";       
    }       
    ?>      
    </tr>       
    <?php       
    //printing each row.
    foreach ($data->getRows() as $row) {        
            print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";   
    }    
    //printing the total number of rows
    ?>      
    <tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>     
    </table>     
    </html>     
    

code ripped from the previously mentioned tutorial.

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • 1
    Hi DalmTo, thanks but it turns out the error was fixed by downloading the .p12 from a unix machine instead of a windows. God knows why.. I am getting the std google error message in return now instead of the cannot read cert. Will ensure all the analytics settings are now correct :-) –  Dec 15 '14 at 14:44
  • weird I do everything on a windows machine. I have never had problems with uploading the .p12 keys to the server after. – Linda Lawton - DaImTo Dec 15 '14 at 14:48
  • 1
    I was rsyncing the cert via cwrsync from windows to unix.. was thinking it could be to do with that, but then i got a colleague to email me the cert downloaded from a mac, rsynced that to the server and it worked... i have no idea. Very confusing :O –  Dec 15 '14 at 14:54
  • I am going to have to try and recreate this still seams weird. – Linda Lawton - DaImTo Dec 15 '14 at 14:58
  • The updating to the newest version of the client library did it for me. Thank you :) – func0der Aug 06 '15 at 10:41