Google Android应用内支付订单服务端验证

时间:2024-03-19 15:45:36

       最近公司的APP新增了收费版本,针对一些高级功能需要用户付费才能使用,付费的方式是用户通过应用内支付去订阅一个月或一年的账户高级权限,相当于QQ里面的VIP功能。

       大概的流程是用户下载APP后注册之后默认为普通用户,用户通过应用内支付去订阅高级账户权限包之后,客户端应用把订单的收据数据提交到服务器,服务器保存用户的支付订单收据数据,并且去验证收据的合法性,确保不是伪造的收据,并且在后续管理用户的取消订阅和订阅过期的行为。

以Google Play为例

一、为访问Google API做准备

1、进入https://play.google.com/apps/publish,Google Play Console;

2、进入菜单Developer account -> API access -> Service Accounts;

Google Android应用内支付订单服务端验证

3、创建好账户之后需要更新账户权限,然后点击View in Google Developers Console;

4、创建Credentials,选择Service account key;

Google Android应用内支付订单服务端验证

5、在新的页面中选择刚刚创建的Service Accounts;

Google Android应用内支付订单服务端验证

 6、点击创建之后将下载的JSON文件放到服务器的指定目录下;

二、添加依赖库到项目

composer require google/apiclient:"^2.0"

三、验证收据信息

$path_parts = pathinfo(__FILE__);
$dir_name = $path_parts['dirname'];
$oauth_file = $dir_name."/GooglePlayAndroidDeveloper-xxxxxx.json";

$google_client = new \Google_Client();
$google_client->setApplicationName($package_name);
$google_client->setClientId(GOOGLE_CLIENT_ID);
$google_client->setScopes(array('https://www.googleapis.com/auth/androidpublisher'));
$google_client->setAuthConfig($oauth_file);
$androidPublishService = new \Google_Service_AndroidPublisher($google_client);
$result = $androidPublishService->purchases_subscriptions->get(
    $package_name,
    $product_id,
    $purchase_token
);
Log::info($result);

根据expiryTimeMillis字段来验证订单是否有效:

$current_time = time();

$valid_time = $result['expiryTimeMillis'] / 1000;

if ($current_time < $valid_time) {

            $status = 1;

}

相关文档传送门:

1、订阅验证 Purchases.subscriptions

https://developers.google.com/android-publisher/api-ref/purchases/subscriptions
2、Google APIs Client Library for PHP

https://github.com/googleapis/google-api-php-client