需要先提交google商店,才能在google创建商品,查询支付。
1导入googlepay
//GooglePay
implementation("com.android.billingclient:billing:4.1.0")
//支付工具类
class GooglePayHelper {
private val TAG = "GooglePayHelper"
private var mActivity: Activity;
constructor(mActivity: Activity) {
this.mActivity = mActivity
}
/**
* 购买监听
*/
private val purchasesUpdatedListener =
PurchasesUpdatedListener {
billingResult, purchases ->
// To be implemented in a later section.
if (billingResult.responseCode == BillingResponseCode.OK) {
//支付成功
if (!purchases.isNullOrEmpty()) {
for (i in 0 until purchases.size) {
var purchase = purchases[i];
//购买成功 消耗掉 同步后台
consume(purchase)
}
}
} else if (billingResult.responseCode == BillingResponseCode.ITEM_ALREADY_OWNED) {
//未消耗掉 查询补单
queryPurchases()
} else if (billingResult.responseCode == BillingResponseCode.USER_CANCELED) {
//取消支付
} else {
// when (billingResult.responseCode) {
// BillingResponseCode.SERVICE_TIMEOUT -> {
// //服务连接超时
// }
// BillingResponseCode.FEATURE_NOT_SUPPORTED -> {
// }
// BillingResponseCode.SERVICE_DISCONNECTED -> {
// //服务未连接
// }
// BillingResponseCode.USER_CANCELED -> {
// //取消
// }
// BillingResponseCode.SERVICE_UNAVAILABLE -> {
// //服务不可用
// }
// BillingResponseCode.BILLING_UNAVAILABLE -> {
// //购买不可用
// }
// BillingResponseCode.ITEM_UNAVAILABLE -> {
// //商品不存在
//
// }
// BillingResponseCode.DEVELOPER_ERROR -> {
// //提供给 API 的无效参数
// }
// BillingResponseCode.ERROR -> {
// //错误
// }
// BillingResponseCode.ITEM_NOT_OWNED -> {
// //不可购买
// }
// }
}
}
private var billingClient = BillingClient.newBuilder(Application)
.setListener(purchasesUpdatedListener)
.enablePendingPurchases()
.build()
//检查之前的商品是否被消费
fun init() {
//已经连接查询订单
if (billingClient.isReady) {
queryPurchases()
} else {
//开始连接
billingClient.startConnection(object : BillingClient