美文网首页第三方框架Android
Android Google应用内支付(新的集成方式)

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

作者: Silence潇湘夜雨 | 来源:发表于2020-05-27 19:31 被阅读0次

    前言

    之前写过一篇通过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发货,服务器给你返回相关信息
      
    支付流程.jpg 补单流程.jpg 后台验证流程.png
    • 2、集成工作
      首先在你的项目的build.gradle文件中加入Google支付的在线依赖
      implementation 'com.android.billingclient:billing:3.0.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;
    //用户信息
    privata String mUserID;
    //商品集合
    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;
    }
    
      public GooglePlayHelper(Activity activity, int mPayTest) {
        this.mActivityRef = new WeakReference<>(activity);
        this.mPayTest = mPayTest;
    }
    
    
    
    
    /**
     * 初始化
     */
    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";
                        uploadToServer(purchase.getPurchaseToken(), purchase.getOrderId(),mOrderID, mPayTest);
                    }
    
                }
            } 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)
                                                        .setObfuscatedAccountId(mUserID)
                                                        .setObfuscatedProfileId(mOrderID)
                                                        .build();
                                        mBillingClient.launchBillingFlow(mActivityRef.get(), purchaseParams);
                                    }
                                }
                            }
    
                        }
                    });
    
        }
    
    
    }
    
    
    /**
     * 消耗
     */
    private void consume(String purchaseToken) {
        if (mBillingClient.isReady()) {
            ConsumeParams consumeParams = ConsumeParams.newBuilder()
                    .setPurchaseToken(purchaseToken)
                    .build();
            mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
                @Override
                public void onConsumeResponse(BillingResult billingResult, String s) {
    
                }
            });
        } else {
            mBillingClient.startConnection(new BillingClientStateListener() {
                @Override
                public void onBillingSetupFinished(BillingResult billingResult) {
                    if (billingResult != null) {
                        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                            ConsumeParams consumeParams = ConsumeParams.newBuilder()
                                    .setPurchaseToken(purchaseToken)
                                    .build();
                            mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
                                @Override
                                public void onConsumeResponse(BillingResult billingResult, String s) {
    
                                }
                            });
                        }
                    }
    
                }
    
                @Override
                public void onBillingServiceDisconnected() {
                }
            });
        }
    
    }
    
    /**
     * 消耗
     */
    private void consume2(String purchaseToken) {
        if (mBillingClient.isReady()) {
            ConsumeParams consumeParams = ConsumeParams.newBuilder()
                    .setPurchaseToken(purchaseToken)
                    .build();
            mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
                @Override
                public void onConsumeResponse(BillingResult billingResult, String s) {
    
                }
            });
            recharge();
        } else {
            mBillingClient.startConnection(new BillingClientStateListener() {
                @Override
                public void onBillingSetupFinished(BillingResult billingResult) {
                    if (billingResult != null) {
                        if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                            ConsumeParams consumeParams = ConsumeParams.newBuilder()
                                    .setPurchaseToken(purchaseToken)
                                    .build();
                            mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
                                @Override
                                public void onConsumeResponse(BillingResult billingResult, String s) {
    
                                }
                            });
                        }
                    }
    
                }
    
                @Override
                public void onBillingServiceDisconnected() {
                }
            });
            recharge();
        }
    
    }
    
    /**
     * 补单操作
     */
    private void queryHistory() {
       Purchase.PurchasesResult mResult = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
        for (int i = 0; i < mResult.getPurchasesList().size(); i++) {
            if (mResult.getPurchasesList().get(i).isAcknowledged()) {
                consume2(mResult.getPurchasesList().get(i).getPurchaseToken());
            } else {
                uploadToServer2(mResult.getPurchasesList().get(i).getPurchaseToken(),
                        mResult.getPurchasesList().get(i).getOrderId(),
                        mResult.getPurchasesList().get(i).getAccountIdentifiers().getObfuscatedProfileId(),
                        mPayTest);
            }
        }
    
    }
    
    /**
     * 获取订单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 mGoogleOrder, 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()));
                                    consume(purchaseToken);
                                } else if (result.getResultModel().getCode() == 10500) {//网络中断再次重新上传验证上传
                                    uploadToServer(purchaseToken,mGoogleOrder, mOrderID, mPayTest);
                                } else {//上传订单验证错误日志信息到服务器
                                    LoginRealizeManager.sendGooglePlayFailed(mActivityRef.get(), mOrderID, purchaseToken,
                                            mGoogleOrder,
                                            mPayTest, result.getResultModel().getMsg(), mListener);
                                }
                            }
    
                        }
    
                    }
    
                });
    
    }
    
    /**
     * 上传到服务器验证接口(具体传值和你们的服务器进行沟通确认)
     */
    private void uploadToServer2(final String purchaseToken,String mGoogleOrder, 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) {
                                    consume2(purchaseToken);
                                    if (mConsume.equals("1")) {
                                        recharge();
                                    }
                                } else if (result.getResultModel().getCode() == 10500) {
                                    uploadToServer2(purchaseToken,mGoogleOrder, mOrderID, mPayTest);
                                } else {
                                    LoginRealizeManager.sendGooglePlayFailed(mActivityRef.get(), mOrderID, purchaseToken,
                                            mGoogleOrder,
                                            mPayTest, result.getResultModel().getMsg(), mListener);
                                }
                            }
    
                        }
    
                    }
    
                });
    
    }
    
       /**
        * 上传到服务器验证
        */
    private void uploadToServer3(final String purchaseToken, String mGoogleOrder,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) {
                                    consume2(purchaseToken);
                                } else if (result.getResultModel().getCode() == 10500) {
                                    uploadToServer3(purchaseToken,mGoogleOrder, mOrderID, mPayTest);
                                } else {
                                    LoginRealizeManager.sendGooglePlayFailed(mActivityRef.get(), mOrderID, purchaseToken,
                                            mGoogleOrder,
                                            mPayTest, result.getResultModel().getMsg(), mListener);
                                }
                            }
    
                        }
    
                    }
    
                });
    
    }
    
    
    /**
     * 释放
     */
    void release() {
        if (mBillingClient.isReady()) {
            mBillingClient.endConnection();
        }
    }
    
    /**
     * 补单操作
     */
    public void addOrder() {
        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) {
                        Purchase.PurchasesResult mResult = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
                        for (int i = 0; i < mResult.getPurchasesList().size(); i++) {
                            if (mResult.getPurchasesList().get(i).isAcknowledged()) {//服务器验证
                                consume2(mResult.getPurchasesList().get(i).getPurchaseToken());
                            } else {//服务器未验证走验证流程
                                uploadToServer3(mResult.getPurchasesList().get(i).getPurchaseToken(),
                                        mResult.getPurchasesList().get(i).getOrderId(),
                                        mResult.getPurchasesList().get(i).getAccountIdentifiers().getObfuscatedProfileId(),
                                        mPayTest);
                            }
                        }
                    }
                }
    
            }
    
            @Override
            public void onBillingServiceDisconnected() {
            }
        });
    }
    
    
    }
    

    最后

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

    相关文章

      网友评论

        本文标题:Android Google应用内支付(新的集成方式)

        本文链接:https://www.haomeiwen.com/subject/zusgahtx.html