如何在 Android 应用程序中实现应用内结算?

新手上路,请多包涵

在 Android 应用中实现 In-App Billing 似乎是相当复杂的。我怎么能这样做? SDK 中的示例应用程序只有一个活动,这对于像我这样具有多个活动的应用程序来说过于简化了。

原文由 SZH 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 397
2 个回答

好吧,我将尝试解释我的经历。我不认为自己是这方面的专家,但几天我就崩溃了。

对于初学者来说,我很难理解示例和应用程序的工作流程。我认为最好从一个简单的示例开始,但是很难将代码分成小块并且不知道您是否破坏了任何东西。我将告诉您我拥有什么以及我从示例中更改了什么以使其起作用。

我有一个活动,我所有的购买都来自于此。它被称为临。

首先,您应该使用您的公共市场开发人员密钥更新您的安全类中的变量 base64EncodedPublicKey,否则您将看到一个不错的异常。

好吧,我将 Activity 绑定到 BillingService,如下所示:

       public class Pro extends TrackedActivity implements OnItemClickListener {

            private BillingService mBillingService;
            private BillingPurchaseObserver mBillingPurchaseObserver;
            private Handler mHandler;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.pro);

                //Do my stuff

                mBillingService = new BillingService();
                mBillingService.setContext(getApplicationContext());

                mHandler = new Handler();
                mBillingPurchaseObserver = new BillingPurchaseObserver(mHandler);

            }

        }

    @Override
    protected void onStart() {
       //Register the observer to the service
        super.onStart();
        ResponseHandler.register(mBillingPurchaseObserver);
    }

    @Override
    protected void onStop() {
        //Unregister the observer since you dont need anymore
        super.onStop();
        ResponseHandler.unregister(mBillingPurchaseObserver);
    }

    @Override
    protected void onDestroy() {
       //Unbind the service
        super.onDestroy();
        mBillingService.unbind();
    }

这样,所有购买都与该服务对话,然后将 JSON 请求发送到市场。您可能认为购买是在同一瞬间进行的,但事实并非如此。您发送请求,购买可能会在几分钟或几小时后到来。我认为这主要是服务器过载和信用卡审批。

然后我有一个包含我的项目的 ListView,我在每个项目上打开一个 AlertDialog,邀请他们购买该项目。当他们点击一个项目时,我这样做:

   private class BuyButton implements DialogInterface.OnClickListener {

       private BillingItem item = null;
       private String developerPayload;

       public BuyButton(BillingItem item, String developerPayload) {
        this.item = item;
        this.developerPayload = developerPayload;
        }

            @Override
            public void onClick(DialogInterface dialog, int which) {

                if (GeneralHelper.isOnline(getApplicationContext())){
                    //I track the buy here with GA SDK.

        mBillingService.requestPurchase(this.item.getSku(), this.developerPayload);
                } else {
                    Toast.makeText(getApplicationContext(), R.string.msg_not_online, Toast.LENGTH_SHORT).show();
                }

            }

        }

好的,您应该看到市场打开并且用户完成或取消购买。

然后重要的是我的 PurChaseObserver,它处理市场发送的所有事件。这是它的精简版,但你应该明白这一点(请参阅我对代码的评论):

 private class BillingPurchaseObserver extends PurchaseObserver {
        public BillingPurchaseObserver(Handler handler) {
            super(Pro.this, handler);
        }

        @Override
        public void onBillingSupported(boolean supported) {

            if (supported) {
                //Enable buy functions. Not required, but you can do stuff here. The market first checks if billing is supported. Maybe your country is not supported, for example.
            } else {
                Toast.makeText(getApplicationContext(), R.string.billing_not_supported, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onPurchaseStateChange(PurchaseState purchaseState, String itemId,
                int quantity, long purchaseTime, String developerPayload) {

//This is the method that is called when the buy is completed or refunded I believe.
// Here you can do something with the developerPayload. Its basically a Tag you can use to follow your transactions. i dont use it.

        BillingItem item = BillingItem.getBySku(getApplicationContext(), itemId);

        if (purchaseState == PurchaseState.PURCHASED) {
            if (item != null){
//This is my own implementation that sets the item purchased in my database. BillingHelper is a class with methods I use to check if the user bought an option and update the UI. You should also check for refunded. You can see the Consts class to find what you need to check for.

                    boolean resu = item.makePurchased(getApplicationContext());
                    if (resu){
                        Toast.makeText(getApplicationContext(), R.string.billing_item_purchased, Toast.LENGTH_LONG).show();
                    }
                }
            }
        }

        private void trackPurchase(BillingItem item, long purchaseTime) {
            //My code to track the purchase in GA
        }

        @Override
        public void onRequestPurchaseResponse(RequestPurchase request,
                ResponseCode responseCode) {

               //This is the callback that happens when you sent the request. It doesnt mean you bought something. Just that the Market received it.

            if (responseCode == ResponseCode.RESULT_OK) {

                Toast.makeText(getApplicationContext(), R.string.billing_item_request_sent, Toast.LENGTH_SHORT).show();

            } else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {
                //The user canceled the item.
            } else {
            //If it got here, the Market had an unexpected problem.
            }
        }

        @Override
        public void onRestoreTransactionsResponse(RestoreTransactions request,
                ResponseCode responseCode) {
            if (responseCode == ResponseCode.RESULT_OK) {
//Restore transactions should only be run once in the lifecycle of your application unless you reinstalled the app or wipe the data.

                SharedPreferences.Editor edit = PreferencesHelper.getInstance().getDefaultSettings(getApplicationContext()).edit();
                edit.putBoolean(Consts.DB_INITIALIZED, true);
                edit.commit();

            } else {
    //Something went wrong
            }
        }
    }

而且我相信您不需要编辑任何其他内容。其余代码“有效”。您可以先在您自己的商品“android.test.purchased”中尝试使用示例 SKU。到目前为止,我已经对此进行了测试并且可以正常工作,但是我仍然需要涵盖所有内容,例如退款状态。在这种情况下,我让用户保留这些功能,但我想在修改它之前确保它能完美运行。

我希望它能帮助你和其他人。

原文由 sebastianf182 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题