阅读 423

Android Google应用内支付(新的集成方式)

前言

之前写过一篇通过AIDL方式集成Google支付 的文章,如有需要,可以去看看。但是,不建议使用。为啥呢?,因为最近看Google文档中说已经不再支持AIDL的方式了。所以今天就来说说新的Google支付继承方式,当然,我们这里只说集成方式,配置可以看Google(应用内支付)官方文档

准备工作

要集成Google支付的准备工作有哪些呢?

  • 1、手机上安装__Google服务__(当然是针对国内的用户,国外的相信大部分都有Google服务);
  • 2、一个绑定信用卡的Google账号;
  • 3、Google play客户端;
  • 4、Google play console用于配置应用内商品信息);

首先

上面的准备工作都做好了之后需要干什么呢?当然是在Google play console上配置相关应用和商品信息了,至于如何配置具体可以参考Google支付配置

  • 1、支付流程说明 关于Google支付的流程说明: 1>前提条件

    1、检查你的包名和签名文件是否和Google Console 上面上传的apk包是否一致
    2、检查版本号是否和Google console发布的apk版本是否一致
    3、检查你是否可以购买,是否绑定了银行卡,手机支不支持Google支付,手机是否有Google服务
    复制代码

    2>支付流程

     1、第一步,初始化Google支付
     2、第二步,初始化成功后调用查询购买的商品操作,查询成功调用消耗操作,防止不能购买的情 况发生
     3、第三步,生成订单号进行购买操作
     4、第四步,购买成功后再次调用一次消耗操作(为了下次购买可以成功)
     5、第五步,拿到Google支付返回的相关信息,在服务器进行验证操作。
     6、第六步,服务器拿到你上传的相关信息和Google支付进行交互验证,验证成功后Google发货,服务器给你返回相关信息
    复制代码
  • 2、集成工作 首先在你的项目的build.gradle文件中加入Google支付的在线依赖

    implementation 'com.android.billingclient:billing:2.1.0'
    复制代码

注意:我用的时候版本是2.1.0,你可以去官网查查最新的版本

其次

上面是接入的前提条件,下面看具体代码

public class GooglePlayHelper {
private static final String TAG = GooglePlayHelper.class.getSimpleName();
private static final int GAME_ORDER_ID=0x01;

//订单号
private String mOrderID;
//商品集合
private WeakReference<Activity> mActivityRef;
//回调
private OnRechargeStateListener mListener;
//商品
private String mSku;
private String goods_number;//  商品ID,游戏提供
private BillingClient mBillingClient;
private int mPayTest;
private String mConsume = "0";

GooglePlayHelper(Activity activity, 
                String goods_number, int mPayTest,
                 String sku, OnRechargeStateListener mListener) {
    this.mActivityRef = new WeakReference<>(activity);
    this.goods_number = goods_number;
    this.mSku = sku;
    this.mPayTest = mPayTest;
    this.mListener = mListener;
}




/**
 * 初始化
 */
void init() {
    mBillingClient = BillingClient.newBuilder(mActivityRef.get())
            .setListener(mPurchasesUpdatedListener)
            .enablePendingPurchases()
            .build();
    if (!mBillingClient.isReady()) {
        mBillingClient.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(BillingResult billingResult) {
                if (billingResult != null) {
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                        if (!TextUtils.isEmpty(PreferencesUtils.getString(mActivityRef.get(),
                                Constants.USER_LT_UID_KEY))) {
                            getLTOrderID();
                        } else {
                            mListener.onState(mActivityRef.get(), RechargeResult.failOf(LTGameError.make(
                                    LTResultCode.STATE_GP_CREATE_ORDER_FAILED,
                                    "order create failed:user key is empty"
                            )));
                            mActivityRef.get().finish();
                        }
                    }
                }

            }

            @Override
            public void onBillingServiceDisconnected() {
            }
        });
    } else {
        if (!TextUtils.isEmpty(PreferencesUtils.getString(mActivityRef.get(),
                Constants.USER_LT_UID_KEY))) {
            getLTOrderID();
        } else {
            mListener.onState(mActivityRef.get(), RechargeResult.failOf(LTGameError.make(
                    LTResultCode.STATE_GP_CREATE_ORDER_FAILED,
                    "order create failed:user key is empty"
            )));
            mActivityRef.get().finish();
        }
    }
}


/**
 * 购买回调
 */
private PurchasesUpdatedListener mPurchasesUpdatedListener = new PurchasesUpdatedListener() {
    @Override
    public void onPurchasesUpdated(BillingResult billingResult, List<Purchase> list) {
        String debugMessage = billingResult.getDebugMessage();
        Log.e(TAG, debugMessage);
        if (list != null && list.size() > 0) {
            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                for (Purchase purchase : list) {
                    mConsume = "2";
                    consume(purchase.getPurchaseToken());
                }

            }
        } else {
            switch (billingResult.getResponseCode()) {
                case BillingClient.BillingResponseCode.SERVICE_TIMEOUT: {//服务连接超时
                    mListener.onState(mActivityRef.get(), RechargeResult.failOf("-3"));
                    mActivityRef.get().finish();
                    break;
                }
                case BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED: {
                    mListener.onState(mActivityRef.get(), RechargeResult.failOf("-2"));
                    mActivityRef.get().finish();
                    break;
                }
                case BillingClient.BillingResponseCode.SERVICE_DISCONNECTED: {//服务未连接
                    mListener.onState(mActivityRef.get(), RechargeResult.failOf("-1"));
                    mActivityRef.get().finish();
                    break;
                }
                case BillingClient.BillingResponseCode.USER_CANCELED: {//取消
                    mListener.onState(mActivityRef.get(), RechargeResult.failOf("1"));
                    mActivityRef.get().finish();
                    break;
                }
                case BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE: {//服务不可用
                    mListener.onState(mActivityRef.get(), RechargeResult.failOf("2"));
                    mActivityRef.get().finish();
                    break;
                }
                case BillingClient.BillingResponseCode.BILLING_UNAVAILABLE: {//购买不可用
                    mListener.onState(mActivityRef.get(), RechargeResult.failOf("3"));
                    mActivityRef.get().finish();
                    break;
                }
                case BillingClient.BillingResponseCode.ITEM_UNAVAILABLE: {//商品不存在
                    mListener.onState(mActivityRef.get(), RechargeResult.failOf("4"));
                    mActivityRef.get().finish();
                    break;
                }
                case BillingClient.BillingResponseCode.DEVELOPER_ERROR: {//提供给 API 的无效参数
                    mListener.onState(mActivityRef.get(), RechargeResult.failOf("5"));
                    mActivityRef.get().finish();
                    break;
                }
                case BillingClient.BillingResponseCode.ERROR: {//错误
                    mListener.onState(mActivityRef.get(), RechargeResult.failOf("6"));
                    mActivityRef.get().finish();
                    break;
                }
                case BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED: {//未消耗掉
                    mConsume = "1";
                    queryHistory();
                    break;
                }
                case BillingClient.BillingResponseCode.ITEM_NOT_OWNED: {//不可购买
                    mListener.onState(mActivityRef.get(), RechargeResult.failOf("8"));
                    mActivityRef.get().finish();
                    break;
                }
            }
        }
    }
};

/**
 * 购买
 */
private void recharge() {
    if (mBillingClient.isReady()) {
        List<String> skuList = new ArrayList<>();
        skuList.add(mSku);
        SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
        params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
        mBillingClient.querySkuDetailsAsync(params.build(),
                new SkuDetailsResponseListener() {
                    @Override
                    public void onSkuDetailsResponse(BillingResult billingResult,
                                                     List<SkuDetails> skuDetailsList) {
                        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK
                                && skuDetailsList != null) {
                            for (SkuDetails skuDetails : skuDetailsList) {
                                String sku = skuDetails.getSku();
                                if (mSku.equals(sku)) {
                                    BillingFlowParams purchaseParams =
                                            BillingFlowParams.newBuilder()
                                                    .setSkuDetails(skuDetails)
                                                    .build();
                                    mBillingClient.launchBillingFlow(mActivityRef.get(), purchaseParams);
                                }
                            }
                        }

                    }
                });

    }


}


/**
 * 消耗
 */
private void consume(String purchaseToken) {
    ConsumeParams consumeParams =
            ConsumeParams.newBuilder()
                    .setDeveloperPayload(mOrderID)
                    .setPurchaseToken(purchaseToken)
                    .build();
    mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {

        @Override
        public void onConsumeResponse(BillingResult billingResult, String s) {

        }
    });
    //上传服务器验证
    uploadToServer(purchaseToken, mOrderID, mPayTest);

}

/**
 * 消耗
 */
private void consume2(String purchaseToken) {
    ConsumeParams consumeParams =
            ConsumeParams.newBuilder()
                    .setDeveloperPayload(PreferencesUtils.getString(mActivityRef.get(), Constants.LT_ORDER_ID))
                    .setPurchaseToken(purchaseToken)
                    .build();
    mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {

        @Override
        public void onConsumeResponse(BillingResult billingResult, String s) {
            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                uploadToServer2(purchaseToken, PreferencesUtils.getString(mActivityRef.get(), GAME_ORDER_ID),
                        mPayTest);
            }
        }
    });

}

/**
 * 补单操作
 */
private void queryHistory() {
    mBillingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP,
            new PurchaseHistoryResponseListener() {
                @Override
                public void onPurchaseHistoryResponse(BillingResult billingResult, List<PurchaseHistoryRecord> list) {
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK
                            && list != null) {
                        for (final PurchaseHistoryRecord purchase : list) {
                            consume2(purchase.getPurchaseToken());
                        }
                    } else {
                        mActivityRef.get().finish();
                    }
                }

            });


}

/**
 * 获取订单ID
 */
private void getLTOrderID() {
   //自己获取订单ID的接口(和你们自己的服务器进行商量)
    LoginRealizeManager.createOrder(mActivityRef.get(), xx, xx, xx,
            new OnRechargeStateListener() {

                @Override
                public void onState(Activity activity, RechargeResult result) {
                    if (result != null) {
                        if (result.getResultModel() != null) {
                            if (result.getResultModel().getData() != null) {
                                if (result.getResultModel().getCode() == 0) {
                                    if (result.getResultModel().getData().getOrder_number() != null) {
                                        mOrderID = result.getResultModel().getData().getOrder_number();
                                        PreferencesUtils.init(mActivityRef.get());
                                        PreferencesUtils.putString(mActivityRef.get(), GAME_ORDER_ID, mOrderID);
                                        recharge();
                                    }
                                } else {
                                    mListener.onState(mActivityRef.get(),
                                            RechargeResult.failOf(result.getResultModel().getMsg()));
                                    mActivityRef.get().finish();
                                    activity.finish();
                                }

                            }

                        }
                    }
                }

            });

}

/**
 * 上传到服务器验证接口(具体传值和你们的服务器进行沟通确认)
 */
private void uploadToServer(final String purchaseToken, String mOrderID, int mPayTest) {
    LoginRealizeManager.googlePlay(mActivityRef.get(),
            purchaseToken, mOrderID, mPayTest, new OnRechargeStateListener() {
                @Override
                public void onState(Activity activity, RechargeResult result) {
                    if (result != null) {
                        if (result.getResultModel() != null) {
                            if (result.getResultModel().getCode() == 0) {
                               
                                mListener.onState(mActivityRef.get(), RechargeResult
                                        .successOf(result.getResultModel()));
                            }else {
                                queryHistory();
                            }
                        }

                    }

                }

            });

}

/**
 * 上传到服务器验证接口(具体传值和你们的服务器进行沟通确认)
 */
private void uploadToServer2(final String purchaseToken, String mOrderID, int mPayTest) {
    LoginRealizeManager.googlePlay(mActivityRef.get(),
            purchaseToken, mOrderID, mPayTest, new OnRechargeStateListener() {
                @Override
                public void onState(Activity activity, RechargeResult result) {
                    if (result != null) {
                        if (result.getResultModel() != null) {
                            if (result.getResultModel().getCode() == 0) {
                               
                                if (mConsume.equals("1")) {
                                    recharge();
                                }
                            }
                        }

                    }

                }

            });

}

/**
 * 释放
 */
void release() {
    if (mBillingClient.isReady()) {
        mBillingClient.endConnection();
    }
}

/**
 * 补单操作
 */
public void addOrder() {
    PreferencesUtils.init(mActivityRef.get());
    mBillingClient = BillingClient.newBuilder(mActivityRef.get())
            .setListener(mPurchasesUpdatedListener)
            .enablePendingPurchases()
            .build();
    mBillingClient.startConnection(new BillingClientStateListener() {
        @Override
        public void onBillingSetupFinished(BillingResult billingResult) {
            if (billingResult != null) {
                if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                    queryHistory();
                }
            }

        }

        @Override
        public void onBillingServiceDisconnected() {
        }
    });
}


}
复制代码

最后

好了,这就是今天的Google支付说明了,如果还有疑问可以加群探讨(493180098)

关注下面的标签,发现更多相似文章
评论