前段时间公司项目接入了第三方支付谷歌支付,一句话就是前端下单后再调用后端接口检验订单,(其他业务),校验完就可以去消耗了
网上的教程好多都是先获取code,拿到code后再去获取refresh_token和access_token,使用access_token做为凭证调用google api,获取code时需要登录,登录在后端都不好做了
推荐使用下面的方式
// packageName为应用程序报名、productId商品id、purchaseToken谷歌返回的收据
public String checkOrder(String packageName, String productId, String purchaseToken) throws IOException, GeneralSecurityException {
//使用服务帐户Json文件获取Google凭据
List<String> scopes = new ArrayList<>();
scopes.add(AndroidPublisherScopes.ANDROIDPUBLISHER);
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("服务账号json文件路径"))
.createScoped(scopes);
// 使用谷歌凭据和收据从谷歌获取购买信息
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = new JacksonFactory();
AndroidPublisher publisher = new AndroidPublisher.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("应用程序名称").build();
AndroidPublisher.Purchases purchases = publisher.purchases();
final AndroidPublisher.Purchases.Products.Get request = purchases.products().get(packageName, productId,purchaseToken);
final ProductPurchase purchase = request.execute();
//处理业务
}
purchase 里面包含以下信息
只说几个关键的字段
orderId -------------------------------谷歌的平台订单号
consumptionState-----------------Inapp产品的消费状态。可能的值为:0。尚未消耗1.已消耗
purchaseState---------------------订单的购买状态。可能的值为:0。已购买1.已取消2.待定
obfuscatedExternalProfileId—透传字段,一般传服务端生成的订单id
后面就是处理自己的业务了,大概说下我这次业务,从谷歌得到交易对象purchase后
1.判断订单是否已购买
2.判断订单是否已消耗
3.如果是已购买未消耗的情况下才继续往下走
4.更新数据库订单记录,通过obfuscatedExternalProfileId透传的订单号查询数据库找到该笔订单
5.通知服务发放道具
下面记录下遇到的问题
出现下面这种情况一般是服务账号没有权限,需要在google play console赋予权限
"errors": [
{
"domain": "androidpublisher",
"reason": "permissionDenied",
"message": "The current user has insufficient permissions to perform the requested operation."
}
],
"code": 401,
"message": "The current user has insufficient permissions to perform the requested operation."
}
}
出现下面这种情况 项目没有关联或者关联错了,如果关联了还报这个错误,随便新增一个内购商品,你可以新增完删除掉
{
"error": {
"errors": [
{
"domain": "androidpublisher",
"reason": "projectNotLinked",
"message": "The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console."
}
],
"code": 403,
"message": "The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console."
}
}