implementation "com.android.billingclient:billing:4.0.0"
在Application进行初始化连接谷歌,判断是否接通谷歌,只有接通谷歌才能做后面 *** 作
//初始化
BillingClient billingClient = BillingClient.newBuilder(this)
.setListener(purchasesUpdatedListener)
.enablePendingPurchases()
.build();
if (!billingClient.isReady()) {
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingServiceDisconnected() {
}
@Override
public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
//这里代表接通谷歌成功
}
}
});
}
3.获取谷歌商品信息,获取商品信息,主要分应用内商品,订阅,传入产品id获取数据
BillingClient.SkuType.SUBS 代表订阅商品,BillingClient.SkuType.INAPP,应用内商品,具体看在谷歌后台创建什么商品
List<String> skuList = new ArrayList<>();
skuList.add("test1"); //test1 代表产品id,具体产品去后谷歌后台查看新疆
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.SUBS);
//
billingClient.querySkuDetailsAsync(params.build(),new SkuDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
}
}
});
}
调起支付 界面
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetails)
.build();
int responseCode = MyApplication.billingClient.launchBillingFlow(
GooglePayActivity.this, billingFlowParams).getResponseCode();
if (responseCode == 0){
// 调起成功
} else{
// 调起失败
}
监听用户是否支付
private PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) {
// To be implemented in a later section.);
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK
&& purchases != null) {
for (Purchase purchase : purchases) {
//完成支付
handlePurchase(purchase);
}
} else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED) {
// 用户取消
} else {
// 其他错误
}
}
};
6.用户支付完成,要进行验证,否则测试环境5分钟会自动退单退款,真实环境3天自动退单退款
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
if(!purchase.isAcknowledged()){
//Toast.makeText(MyApplication.this,"支付成功:非消耗类" ,Toast.LENGTH_SHORT).show();
AcknowledgePurchaseParams acknowledgePurchaseParams =
AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
billingClient.acknowledgePurchase(acknowledgePurchaseParams,acknowledgePurchaseResponseListener);
} else{
//Toast.makeText(MyApplication.this,"支付成功:消耗类" ,Toast.LENGTH_SHORT).show();
ConsumeParams consumeParams =
ConsumeParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
billingClient.consumeAsync(consumeParams, listener);
}
//这里可以通知自己app服务器进行相应处理
}
到这里就完成!!!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)