Why upgrade?
As the Google API continues to evolve, older versions of the google-api-php-client may face the following issues: security vulnerabilities cannot be patched in a timely manner, new API features are unusable, and compatibility problems are becoming increasingly prominent. Upgrading to the latest version not only solves these problems but also provides performance optimizations, support for new features, and more comprehensive documentation and community support. The officially maintained latest version ensures that your application maintains good compatibility with Google services, avoiding service interruptions due to API changes.
Upgrade preparation
Before you begin the upgrade, ensure your development environment meets the following requirements:
- The PHP version must be at least 5.6, and version 7.0 or above is recommended for better performance and security.
- Composer is installed to manage dependencies.
- Back up your project code and related configuration files in case of unexpected issues during the upgrade process.
The evolution of installation methods: from manual installation to Composer management
Old version installation method
In version 1.0, it was usually necessary to manually download and import the library files, or install them through a complicated process.
// Old version introduction method
require_once 'google-api-php-client/src/Google/autoload.php';
// Or introduce class files one by one
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
This approach is not only cumbersome, but also makes it difficult to manage dependencies and version updates.
New installation method
Starting with version 2.0, google-api-php-client uses Composer for dependency management, making the installation process simple and efficient. Simply execute the following command in the project root directory:
composer require google/apiclient:~2.0
After installation, you can import the client library using the following code:
require_once 'vendor/autoload.php';
This method automatically handles dependencies and easily updates library versions, making it the recommended practice for modern PHP projects. Installation instructions can be found at docs/install.md .
Major adjustments to namespaces
Old namespace
In older versions, class names Google_were prefixed with:
$client = new Google_Client();
$service = new Google_Service_Books($client);
New namespace
Version 2.0 introduces namespaces and adopts a more standardized naming convention:
$client = new Google\Client();
$service = new Google\Service\Books($client);
While the old class names can still be used for a period of time, it is recommended to migrate to the new namespace as soon as possible to ensure future compatibility. This change makes the code structure clearer and conforms to modern PHP development standards.
Improvement of authentication methods
Changes to service account authentication
In the older version, Google_Auth_AssertionCredentialsservice account authentication was performed as follows:
$client_email = '[email protected]';
$private_key = file_get_contents('MyProject.p12');
$scopes = array('https://www.googleapis.com/auth/sqlservice.admin');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client->setAssertionCredentials($credentials);
In the new version, it is recommended to use a JSON format key file and setAuthConfigconfigure it using the following method:
$client->setAuthConfig('/path/to/service-account.json');
// Or use environment variables (recommended)
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client->useApplicationDefaultCredentials();
Note: P12 format keys are deprecated. It is recommended to generate a new JSON format key in the Google Developer Console. For detailed authentication information, please refer to docs/auth.md .
User simulation implementation
In the older version, Google_Auth_AssertionCredentialsthe user’s email address was specified during creation:
$user_to_impersonate = '[email protected]';
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
$user_to_impersonate
);
The new version setSubjectimplements user simulation through the following methods:
$user_to_impersonate = '[email protected]';
$client->setSubject($user_to_impersonate);
This approach is simpler and more intuitive, and it also aligns better with the design logic of APIs.
Access token handling method
Old version token processing
In version 1.0, the access token is returned as a JSON string:
$accessToken = $client->getAccessToken();
// output: array("access_token" => "ya29...", "token_type" => "Bearer", ...)
file_put_contents($credentialsPath, json_encode($accessToken));
New Token Processing
In version 2.0, the access token is returned as an array, which needs to be JSON encoded before it can be saved.
$accessToken = $client->getAccessToken();// output: array("access_token" => "ya29...", "token_type" => "Bearer", ...)file_put_contents($credentialsPath, json_encode($accessToken));
This change makes handling token data more flexible, allowing direct access to individual fields in the array without first performing JSON decoding.
Simplified ID token verification
Old version ID token verification
In the older version, it was necessary to Google_Auth_LoginTicketobtain user data:
$ticket = $client->verifyIdToken($idToken);
$data = $ticket->getAttributes();
$userId = $data['payload']['sub'];
New version of ID token verification
The new version verifyIdTokendirectly returns a user data array:
$userData = $client->verifyIdToken($idToken);
$userId = $userData['sub'];
This simplification makes the code more concise and reduces unnecessary intermediate steps. More information about ID tokens can be found at docs/id-token.md .
Refactoring of HTTP Request Processing
Version 2.0 introduced Guzzle and PSR-7, and significantly refactored HTTP request processing:
Google_Http_RequestRelatedGoogle_IO_*classes have been removed .- Add new
Google_Client::getHttpClientmethodsGoogle_Client::setHttpClientfor getting and setting the Guzzle client. Google_Http_BatchAndGoogle_Http_MediaFileUploadit was refactored for Guzzle.
For example, creating an authorized HTTP client:
// Create an authorized HTTP client
$httpClient = $client->authorize();
// Sending requests using an HTTP client
$request = new GuzzleHttp\Psr7\Request('GET', 'https://www.googleapis.com/drive/v3/files');
$response = $httpClient->send($request);
This change makes HTTP request processing more flexible, supports the PSR-7 standard, and facilitates integration with other PSR-compliant libraries. Detailed code examples of the relevant HTTP processing can be found in src/Http/REST.php .
Changes to the service class constructor
Old version of service class constructor
In the old version, the service class constructor required Google_Clientan instance to be passed in:
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("YOUR_APP_KEY");
$service = new Google_Service_Books($client);
New version of service class construction
In the new version, the service class constructor accepts either a client instance or a configuration array:
$service = new Google\Service\Books([
'application_name' => "Client_Library_Examples",
'developer_key' => "YOUR_APP_KEY",
]);
This approach makes creating service instances more convenient and reduces the amount of code required. If a shared client instance is needed, Google\Clientan object can still be passed in.
Common problems and solutions
Question 1: An error occurred after the upgrade: the class could not be found.
Solution : Check if the namespace is correct, ensuring that the new namespace format is used Google\Clientinstead of the old one Google_Client. Also, confirm that the Composer autoload files vendor/autoload.phphave been correctly imported.
Question 2: Authentication failed, indicating invalid credentials.
Solution : Ensure you are using a service account key in JSON format, not the older P12 format. Check that the key file path is correct and that setAuthConfigthe key has been set correctly. If using environment variables GOOGLE_APPLICATION_CREDENTIALS, ensure that the variable points to the correct key file.
Question 3: HTTP request-related method calls failed.
Solution : The HTTP processing methods have changed after the upgrade, requiring the use of new Guzzle-related methods. For example, use $client->authorize()an authorized HTTP client and then send requests using Guzzle methods. Refer to the HTTP Request Handling section of this document and the official examples.