一、前期准备工作

二、相关文档地址
1.谷歌oauth2.0接口文档地址:[文档地址](https://developers.google.com/identity/protocols/oauth2/service-account#httprest
2.谷歌支付APP文档地址:http://developer.android.com/ 》》google play >>订阅
三、上代码
<?php
class GooglePay{
/**创建服务账号时生成json密钥中的数据*/
private static $private_key="--\n";
private static $client_email="publishe.com";
private static $token_uri="https://oauth2.googleapis.com/token";
// 固定值
private static $grantType = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
// 谷歌支付对应的scope
private static $scope = "https://www.googleapis.com/auth/androidpublisher";
// token临时存储位置
private static $tokenFilePath = 'sss';
public static function getAccessToken() {
if(file_exists(self::$tokenFilePath)) { // 一定要修改这个,不然出问题别怪我
$accData = json_decode(file_get_contents(self::$tokenFilePath),true);
if($accData['expire_time'] < time() + 60) { // 提前10分钟获取新的
return $accData['access_token'];
}
}
return self::getNewAccessToken();
}
private static function getNewAccessToken(){
$nowTime = time();
$header = base64_encode('{"alg":"RS256","typ":"JWT"}'); // eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9
$claim = base64_encode(json_encode([
"iss"=>self::$client_email,
"scope"=>self::$scope,
"aud"=>self::$token_uri,
"exp"=>$nowTime + 3600,
"iat"=>$nowTime,
],JSON_UNESCAPED_UNICODE));
$preSign = $header.'.'.$claim;
$sign = "";
openssl_sign($preSign,$sign,self::$private_key,'SHA256');
$sign = base64_encode($sign);
$postData = [
"grant_type"=>self::$grantType,
"assertion" => $preSign.'.'.$sign
];;
$tokenRes = self::httpRequest(self::$token_uri,"POST",$postData);
$resp = json_decode($tokenRes,true);
$resp['expire_time'] = time() + $resp['expires_in'];
file_put_contents(self::$tokenFilePath,json_encode($resp));
return $resp['access_token'];
}
public static function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
// XXXXXXXXXXX
return [];
}
// 获取套餐信息
public static function getOrderInfo($packageName,$productId,$purchaseToken,$accessToken) {
$url = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{$packageName}/purchases/subscriptions/{$productId}/tokens/{$purchaseToken}?access_token={$accessToken}";
$resp = self::httpRequest($url,"GET");
$data = json_decode($resp,true);
if($data && !isset($data['error'])) {
return $data;
}
return [];
}
// 确认订阅(可以放在客户端完成)
public static function subVerify($packageName,$productId,$purchaseToken,$accessToken) {
$url = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{$packageName}/purchases/products/{$productId}/tokens/{$purchaseToken}?access_token={$accessToken}";
$resp = self::httpRequest($url,"POST");
$data = json_decode($resp,true);
var_dump($resp);
if($data && !isset($data['error'])) {
return $data;
}
return [];
}
}
不要相信屏幕授权,亲自尝试,你认真就完蛋了
网友评论