- 先集成google支付插件
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");
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) {
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()){
AcknowledgePurchaseParams acknowledgePurchaseParams =
AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
billingClient.acknowledgePurchase(acknowledgePurchaseParams,acknowledgePurchaseResponseListener);
} else{
ConsumeParams consumeParams =
ConsumeParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
billingClient.consumeAsync(consumeParams, listener);
}
}
到这里就完成!!!
|