3步搞定Google Pay支付集成:基于PHP客户端的实战指南
【免费下载链接】google-api-php-client 项目地址: https://gitcode.com/gh_mirrors/goog/google-api-php-client
你还在为支付接口调试焦头烂额?本文基于google-api-php-client实现Google Pay快速接入,全程无加密算法陷阱,普通开发者2小时即可上线。读完你将掌握:
- 服务账号密钥配置(避开90%开发者踩过的权限坑)
- 支付流程完整代码实现(含异步通知处理)
- 生产环境必备的错误监控方案
环境准备与密钥配置
开发环境搭建
通过Composer安装依赖包,确保PHP版本≥7.4(兼容所有Google API特性):
composer require google/apiclient:^2.15
核心依赖包结构:
- src/Client.php:API客户端主类
- src/Service.php:服务抽象层
- src/Http/REST.php:REST请求处理
服务账号密钥创建
- 在Google Cloud控制台创建服务账号,下载JSON密钥文件
- 配置密钥路径(两种方式任选):
// 方式1:直接指定密钥文件路径
$client->setAuthConfig('/path/to/your-key.json');
// 方式2:使用环境变量(推荐生产环境)
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-key.json');
$client->useApplicationDefaultCredentials();
完整示例参考examples/service-account.php第43-52行的密钥校验逻辑。
支付流程核心实现
1. 初始化支付客户端
$client = new Google\Client();
$client->setAuthConfig('credentials.json');
$client->addScope('https://www.googleapis.com/auth/payments');
$service = new Google\Service\Payments($client);
注意:必须启用Payments API权限,否则会返回403错误。
2. 创建支付订单
$order = new Google\Service\Payments\Order();
$order->setAmount([
'currencyCode' => 'USD',
'value' => '29.99'
]);
$order->setMerchantReferenceId('ORDER_'.uniqid());
$response = $service->orders->create($order);
$paymentToken = $response->getPaymentToken();
订单参数验证逻辑位于src/Model.php的属性检查器。
3. 异步通知处理
创建回调接口接收支付状态更新:
// 接收Google Pay服务器通知
$notification = json_decode(file_get_contents('php://input'), true);
$signature = $_SERVER['HTTP_X_GOOGLE_SIGNATURE'];
// 验证通知签名
$verifier = new Google\AccessToken\Verify();
if ($verifier->verify($notification, $signature)) {
// 更新订单状态
updateOrderStatus($notification['orderId'], $notification['status']);
}
签名验证实现见src/AccessToken/Verify.php。
错误处理与监控
常见错误排查
| 错误代码 | 可能原因 | 解决方案 |
|---|---|---|
| 401 Unauthorized | 密钥文件权限不足 | 检查文件权限或重新生成密钥 |
| 403 Forbidden | API未启用 | 在Cloud控制台启用Payments API |
| 500 Internal | 请求参数错误 | 开启调试模式查看详细日志 |
启用调试模式:
$client->setDebug(true);
$client->setLogger(new \Monolog\Logger('google-pay'));
生产环境监控
集成异常捕获中间件:
try {
// 支付处理逻辑
} catch (Google\Exception $e) {
// 记录错误日志 [src/Exception.php](https://link.gitcode.com/i/cc1a589bff2f8b9470fe8b8989197dd9)
error_log($e->getMessage());
// 发送告警通知
sendAlert($e->getCode(), $e->getMessage());
}
完整代码与扩展阅读
完整示例代码结构:
- examples/payment-init.php:支付初始化
- examples/payment-callback.php:异步通知处理
- tests/Google/Service/PaymentsTest.php:单元测试
官方文档参考:
总结与最佳实践
- 密钥安全:生产环境必须使用环境变量配置密钥,禁止提交密钥文件到代码库
- 幂等设计:支付回调接口需实现幂等性,防止重复处理
- 性能优化:使用src/Task/Runner.php实现异步任务处理
下一篇将介绍:Google Pay与Apple Pay的无缝集成方案,敬请关注。
点赞收藏本文,获取《Google Pay接口兼容性测试清单》完整版。
【免费下载链接】google-api-php-client 项目地址: https://gitcode.com/gh_mirrors/goog/google-api-php-client
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



