google play 此应用使用的结算功能版本已不能受支持。

来源:互联网 发布:bluehost域名绑定主机 编辑:程序博客网 时间:2024/06/06 04:39

谷歌提供的支付版本需要强制更新,需要开发者更新sdk支付版本。


google paly v3代码解析


今天跟大家一起看下Google的in-app Billing V3支付。

   如果没有GooglePlay此处附上安装Google Play的一键安装器的链接(需要Root权限):http://www.muzhiwan.com/com.muzhiwan.gsfinstaller-86095.html
   之前用过Google BillingV2,感觉不太爽。V2版支付走的是异步通知,不能即时得到支付结果,支付、查询接口太过复杂,还有就是没找到RestoreOrder接口,因此选择使用V3版,网上大部分都是介绍GoogleBilling的付费机制原理,具体针对某个功能点的很模糊,所以如果大家想了解GoogleBilling付费机制的这篇博文大可不看,网上转载多的是,我写这篇博文的目的是想让大家快速的将Google支付集成到自己项目中。
   集成Google in-appBilling的前提是你已经正确连接上VPN(大陆用户),基本上每个公司都会有VPN的,这个找项目组长去要。
  也正式由于天朝的封锁使得在大陆接Google的支付加大了难度。所以要想接in-appBilling首先要有一个稳定的vpn,PS:非大陆的就行,最好是美、日的。
VPN设置:Android支付接入(七):Google <wbr>In-app-BillingAndroid支付接入(七):Google <wbr>In-app-BillingAndroid支付接入(七):Google <wbr>In-app-BillingAndroid支付接入(七):Google <wbr>In-app-BillingAndroid支付接入(七):Google <wbr>In-app-BillingAndroid支付接入(七):Google <wbr>In-app-Billing

注意:类型根据VPN而定,我用的是L2TP/IPSecPSK,选择此类型时,编辑只需填写名称,服务器地址和IPSec预共享密钥即可,然后连接的时候填写帐号和密码。当打开Google商店能看到付费软件表名VPN已成功连接,如果显示VPN已连接但还看不到付费软件时,进入应用程序管理器分别清除GooglePlay服务和Google Play商店数据之后再打开Google商店即可。

文档下载链接为:  http://pan.baidu.com/share/link?shareid=1387554851&uk=473193131
源码下载链接为:http://pan.baidu.com/share/link?shareid=1579953623&uk=473193131
   注:源码导入工程是不可用的,需将包名、版本号、版本code、签名改为你上传至Google控制台测试应用的包名、版本号、版本code、签名,且将MainActivity.java中的Stringbase64EncodedPublicKey ="";填写上你应用程序的签名。PS:签名即Eclipse->AndroidTools->Export Signed Application Package...
   网盘分享中的DemoForGoogleBilling.apk文件是可支付的,但支付会将钱打到我们公司账户上,因为我用的是上线app的key。

一:接入流程:
   1.申请Google开发者帐号,开发人员控制台左侧选择“设置”填写测试人员帐号。


   2.添加新应用,此处有个“上传APK”,此处上传的apk上传到Bate版或者ALPHA版,但包名、版本code、版本name、签名需跟最终上线的产品保持一致。此处上传测试版本的目的是当你支付接入完毕后测试时用。

    3.集成Google Billing。
     (1).Purchasing Items,购买商品时的通信过程

Android支付接入(七):Google <wbr>In-app-Billing
      (2).Consuming In-app Products,消耗产品时的通信过程


    4.测试支付。
      (1).测试支付官方文档链接http://developer.android.com/google/play/billing/billing_testing.html
      (2).Testing with staticresponses,静态测试,即当支付状态为一下四种情况时游戏逻辑是否正确。
官方给出的4种如下:
There are four reserved product IDs for testing static In-appBilling responses:
android.test.purchased
When you make an In-app Billing request with this product ID,Google Play responds as though you successfully purchased an item.The response includes a JSON string, which contains fake purchaseinformation (for example, a fake order ID). In some cases, the JSONstring is signed and the response includes the signature so you cantest your signature verification implementation using theseresponses.
android.test.canceled
When you make an In-app Billing request with this product IDGoogle Play responds as though the purchase was canceled. This canoccur when an error is encountered in the order process, such as aninvalid credit card, or when you cancel a user's order before it ischarged.
android.test.refunded
When you make an In-app Billing request with this product ID,Google Play responds as though the purchase was refunded. Refundscannot be initiated through Google Play's in-app billing service.Refunds must be initiated by you (the merchant). After you processa refund request through your Google Wallet merchant account, arefund message is sent to your application by Google Play. Thisoccurs only when Google Play gets notification from Google Walletthat a refund has been made. For more information about refunds,see Handling IN_APP_NOTIFY messages and In-app BillingPricing.
android.test.item_unavailable
When you make an In-app Billing request with this product ID,Google Play responds as though the item being purchased was notlisted in your application's product list.
      例:当配置为android.test.purchased时
[java] view plaincopy
  1. mHelper.launchPurchaseFlow(MainActivity.this,“android.test.purchased”,RC_REQUEST,mPurchaseFinishedListener);  

Android支付接入(七):Google <wbr>In-app-BillingAndroid支付接入(七):Google <wbr>In-app-Billing
      (3).当游戏逻辑测试通过后,进行支付测试。测试时手机设备上绑定的Google帐号必须是在开发者控制台中配置的测试帐号,绑定非大陆的信用卡,支付后会在开发者控制台看到支付的订单,由于是测试订单,可以将测试产生的费用返还给绑定的信用卡。
     测试效果图如下(由于本人没有非大陆的信用卡,所以只能看到这个界面,上线项目“蘑菇帮”测试ok)
Android支付接入(七):Google <wbr>In-app-Billing

支付接入过程中涉及到的接口及名词:

一:受管理商品和不受管理商品
   1.受管理商品即不可重复购买的,例如:解锁关卡,激活游戏等。
   2.不受管理商品即可重复购买的,例如:购买金币,购买药水,等消耗品。
   3.订阅商品,由于项目中没有涉及到,如有需要的可以翻阅一下Google Billing文档。
Google in-app BillingV3将所有商品默认为受管理的,如果有不受管理商品则需要调用consumeAsync去消耗调,(或者你可以通俗的理解为,当你成功购买一个道具,Google后台会将此道具加上标记,当你调用consumeAsync将订单消耗掉时,该订单标记被取消)。
二:三个回调

  1.IabHelper.OnIabPurchaseFinishedListener 支付完成的回调,如果是受管理的商品在此回调中直接可以将道具给用户

 

  2.IabHelper.OnConsumeFinishedListener 消耗完成的回调,当不受管理的商品被成功消耗进入此回调,此时将不受管理的商品给用户

 

    3.IabHelper.QueryInventoryFinishedListener 查询完成的回调,RestoreOrder的时候用,当有订单成功付款但由于种种原因(突然断网、断电等)没收到Google支付成功的回调时,在这里可以查询到此订单,此时需要对订单进行处理(给用户道具等)。

四:测试用的app一定要跟上传到Google的测试版的包名、版本code、name、签名一致,否则无法进行支付测试。

    1.当签名不一致或者版本code、版本name不一致时错误界面如下:

Android支付接入(七):Google <wbr>In-app-Billing

      2.当包名不一致时错误界面如下:

Android支付接入(七):Google <wbr>In-app-Billing

接下来跟大家一起看一下代码具体实现:
1.下载in-app-billing-v03,下载地址:http://pan.baidu.com/share/link?shareid=1387554851&uk=473193131将下载后的压缩包解压:

将src目录下两个包及包中的java文件引入工程,例如:

2.添加权限:
[html] view plaincopy
  1. <uses-permissionandroid:nameuses-permissionandroid:name="com.android.vending.BILLING"/>  

3.添加支付代码:
    初始化IapHelper:

[java] view plaincopy
  1. String base64EncodedPublicKey ="";此处填写Google控制台添加新应用程序后的appid  
  2.       mHelper =new IabHelper(this, base64EncodedPublicKey);  
  3.        // enable debuglogging (for a production application, you should set this tofalse).  
  4.       mHelper.enableDebugLogging(false);  
  5.     // Start setup. This is asynchronous andthe specified listener  
  6.        // will be called oncesetup completes.  
  7.        Log.d(TAG,"Starting setup.");  
  8.       mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener(){  
  9.           publicvoid onIabSetupFinished(IabResult result){  
  10.               Log.d(TAG,"Setupfinished.");  
  11.              if (!result.isSuccess()) {  
  12.                  // Ohnoes, there was a problem.  
  13.                  complain("Problemsetting up in-app billing: " + result);  
  14.                 return;  
  15.               }  
  16.              iap_is_ok = true;  
  17.               //Hooray, IAB is fully set up. Now, let's get an inventory of stuffwe own.  
  18.              Log.d(TAG, "Setup successful. Queryinginventory.");  
  19.            }  
  20.        });  

  调用支付接口:

[java] view plaincopy
  1. if(iap_is_ok){  
  2. mHelper.launchPurchaseFlow(MainActivity.this,skus[1],RC_REQUEST, mPurchaseFinishedListener);  
  3. }else {  
  4. showMessage("提示""GooglePlay初始化失败,当前无法进行支付,请确定您所在地区支持Google Play支付或重启游戏再试!");  
  5. }  

  调用查询接口:

 

[java] view plaincopy
  1. mHelper.queryInventoryAsync(mGotInventoryListener);  

  调用获取道具价格接口:(因Google市场是根据不同国家显示不同货币价格,所以显示到游戏道具列表中的价格不是定值,而是动态获取的)

 

[java] view plaincopy
  1. billingservice =mHelper.getService();  
  2. Bundle querySkus = newBundle();  
  3.    querySkus.putStringArrayList("ITEM_ID_LIST", skus);  
  4. try {  
  5. Bundle skuDetails = billingservice.getSkuDetails(3,MainActivity.this.getPackageName(),"inapp", querySkus);  
  6. ArrayList<String> responseList =skuDetails.getStringArrayList("DETAILS_LIST");  
  7. if (null!=responseList) {  
  8. for (String thisResponse :responseList) {  
  9.           try {  
  10. SkuDetails d = newSkuDetails(thisResponse);  
  11.    
  12. for (int i = 0; i <sku_list.size(); i++) {  
  13. if(sku_list.get(i).equals(d.getSku())) {  
  14. price_list.set(i, d.getPrice());  
  15. }  
  16. }  
  17. iapHandler.sendEmptyMessage(0);  
  18.    
  19. }catch (JSONException e) {  
  20. // TODO Auto-generated catchblock  
  21. e.printStackTrace();  
  22. }  
  23.             
  24.        }  
  25. }  
  26. }catch (RemoteException e) {  
  27. // TODO Auto-generated catchblock  
  28. e.printStackTrace();  
  29. }  

  三个回调:

 

[java] view plaincopy
  1. // Callback for when a purchase is finished  
  2. IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener =newIabHelper.OnIabPurchaseFinishedListener() {  
  3.       publicvoidonIabPurchaseFinished(IabResult result, Purchase purchase) {  
  4.            Log.d(TAG,"Purchase finished: " + result+", purchase: " +purchase);  
  5.           if (result.isFailure()) {  
  6.              // Oh noes!  
  7.               complain("Error purchasing: " + result);  
  8.              return;  
  9.            }  
  10.   
  11.            Log.d(TAG,"Purchase successful.");  
  12.           if(purchase.getSku().equals("coins_100")||purchase.getSku().equals("android.test.purchased")){  
  13.           mHelper.consumeAsync(purchase, mConsumeFinishedListener);  
  14. }elseif (purchase.getSku().equals("double_income")) {  
  15. //受管理的商品,开启双倍经验  
  16. showMessage("支付成功","成功购买双倍经验");  
  17. }  
  18.        }  
  19.     };  
  20. // Called when consumption is complete  
  21. IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =newIabHelper.OnConsumeFinishedListener() {  
  22.       publicvoid onConsumeFinished(Purchasepurchase, IabResult result) {  
  23.           Log.d(TAG,"Consumption finished. Purchase: "+purchase + ", result: " +result);  
  24.   
  25.           // We know this is the "gas"sku because it's the only onewe consume,  
  26.           // so we don't check whichsku was consumed. If you havemore than one  
  27.           //sku, you probably shouldcheck...  
  28.           if (result.isSuccess()) {  
  29.               //successfully consumed, so we apply the effects of the item inour  
  30.               //game world's logic, which in our case means filling the gas tank abit  
  31.           if(purchase.getSku().equals("coins_100")||purchase.getSku().equals("android.test.purchased")){  
  32.           showMessage("支付成功","成功购买100猫币");  
  33.     }  
  34.            }  
  35.           else {  
  36.               complain("Error while consuming: " + result);  
  37.            }  
  38.        }  
  39.     };  
  40.       
  41. // Listener that's called when we finish querying the items weown  
  42. IabHelper.QueryInventoryFinishedListener mGotInventoryListener =newIabHelper.QueryInventoryFinishedListener() {  
  43.       publicvoidonQueryInventoryFinished(IabResult result, Inventory inventory){  
  44.           Log.d(TAG,"Query inventory finished.");  
  45.           if (result.isFailure()) {  
  46.               complain("Failed to query inventory: " +result);  
  47.              return;  
  48.            }  
  49.   
  50.           Log.d(TAG,"Query inventory was successful.");  
  51.   
  52.           if(inventory.hasPurchase("double_income")) {  
  53.          //查询到有受管理的商品支付成功需要将道具给用户  
  54. showMessage("成功Restore双倍金币""查询到有双倍金币需要恢复");  
  55. }elseif(inventory.hasPurchase("cions_100")){  
  56. //查询到不受管理的商品支付成功需要将道具消耗掉  
  57. showMessage("成功Restore100金币","查询到有100金币需要恢复");  
  58. }  
  59.        }  
  60.     };  

  处理返回Activity后的数据:

[java] view plaincopy
  1. @Override  
  2. protectedvoid onActivityResult(int requestCode,int resultCode, Intent data) {  
  3. // TODO Auto-generated methodstub  
  4. Log.d(TAG, "onActivityResult("+ requestCode + "," +resultCode +"," + data);  
  5.   
  6.        // Pass on theactivity result to the helper for handling  
  7.       if(!mHelper.handleActivityResult(requestCode, resultCode, data)){  
  8.           // not handled, so handle it ourselves(here's where you'd  
  9.           // perform any handling of activityresults not related to in-app  
  10.           // billing...  
  11.           super.onActivityResult(requestCode,resultCode, data);  
  12.        }  
  13.       else {  
  14.           Log.d(TAG,"onActivityResult handled by IABUtil.");  
  15.        }  
  16. }  

  退出游戏后销毁IabHelper:

 

import java.util.HashMap;

import java.util.List;

import java.util.Map;



import org.json.JSONObject;


import android.app.AlertDialog;

import android.app.AlertDialog.Builder;

import android.content.DialogInterface;

import android.content.Intent;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.widget.Toast;



public class MainActivityextends Activity {

static IabHelper mHelper;

private staticboolean iap_is_ok =false;//初始化成功标识

static finalintRC_REQUEST = 10001;

private static StringSKU_GAS ="";

private static Map<String, Purchase>mapPurchase =new HashMap<String, Purchase>();

private static MainActivity mainActivity;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

mainActivity = this;

String base64EncodedPublicKey ="";//此处请填写你应用的appkey

        mHelper =new IabHelper(this, base64EncodedPublicKey);

        // enable debug logging (for a production application, you should set this to false).

        mHelper.enableDebugLogging(false); 

        //Start setup. This is asynchronous and the specified listener

        // will be called once setup completes.

        //初始化谷歌支付sdk

        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {

            publicvoid onIabSetupFinished(IabResult result) {

                if (!result.isSuccess()) {

                    return;

                }

                iap_is_ok =true;

Toast.makeText(MainActivity.this, "初始化成功", Toast.LENGTH_LONG).show();

            }

        });

}


// 查询库存(inventory)完成接口---查询未发货的订单

    static IabHelper.QueryInventoryFinishedListenermGotInventoryListener=new IabHelper.QueryInventoryFinishedListener() {

        publicvoid onQueryInventoryFinished(IabResult result, Inventory inventory) {

            if(result.isFailure()) {

                return;

            }

            Log.d(TAG, "查询成功!");

            // 因为SKU_GAS是可重复购买的产品,查询我们的已购买的产品,

            // 如果当中有SKU_GAS,我们应该立即消耗它,以方便下次可以重复购买。

            List<Purchase> listPu = inventory.getAllPurchases();//查询所有未通知google市场的收到的订单

            if(listPu.size() >= 0){

            for(Purchase item:listPu){

              mapPurchase.put(item.getSku(), item);

                 //通知服务器我已经付款

                 Service.purchase( item.getOriginalJson(), item.getSignature());

               }

            }

            Purchase gasPurchase = inventory.getPurchase(SKU_GAS);//查找当前商品是否已经通知发货

            if(gasPurchase!=null){

            showMessage("提示", "正在为您发货请稍后,请稍后...");

            }else{

            if(iap_is_ok){

    try {

    mHelper.launchPurchaseFlow(mainActivity,SKU_GAS,RC_REQUEST, mPurchaseFinishedListener,“您的商品订单id”);//到时候会一起放在google商品信息回传给你

    } catch (Exception e) {

    Common.error(e.getMessage());

    }

    }else{

    showMessage("提示","Google Play初始化失败,当前无法进行支付,请确定您所在地区支持Google Play支付或重启游戏再试!");

    }

            }

                        

        }

    };

    

    //通知谷歌这个商品我已经发货了

    public static void continuePurchase(String productId){

    mHelper.consumeAsync(mapPurchase.get(productId),mConsumeFinishedListener);

    }

 

// google play支付结果监听

    static IabHelper.OnIabPurchaseFinishedListenermPurchaseFinishedListener =new IabHelper.OnIabPurchaseFinishedListener() {

        publicvoid onIabPurchaseFinished(IabResult result, Purchase purchase) {

            //Log.d(TAG, "Purchase finished: " + result + ", purchase: " + purchase);

            if (result.isFailure()) {

Toast.makeText(mainActivity,"支付失败", Toast.LENGTH_LONG).show();

                return;

            }

Toast.makeText(mainActivity,"支付成功", Toast.LENGTH_LONG).show();

//添加未通知的商品信息

mapPurchase.put(purchase.getSku(), purchase);

        }

    };

    

    

    // 监听--通知谷歌我已经发货了

   static IabHelper.OnConsumeFinishedListenermConsumeFinishedListener =new IabHelper.OnConsumeFinishedListener() {

        public void onConsumeFinished(Purchase purchase, IabResult result) {

            if (result.isSuccess()) {

            //Log.d(TAG, "通知谷歌成功---"+purchase);

            }else{

            //Log.d(TAG, "通知谷歌失败.");

            }

        }

    };

    

   static Handler myHandler =new Handler() {  

        public void handleMessage(Message msg) {   

             switch (msg.what){  

                  case 1:  

                  mHelper.queryInventoryAsync(mGotInventoryListener);

                      break;   

             }   

             super.handleMessage(msg);   

        }   

   };

    //付款-支付

public staticvoid googlePlay(String productId){

SKU_GAS = productId;

myHandler.sendEmptyMessage(1);

}

private staticvoid showMessage(String title,String message){

new AlertDialog.Builder(mainActivity).setTitle(title).setMessage(message).setPositiveButton("确定",null).show();

}

//支付回调---通知服务器我已经付款

@Override

protected void onActivityResult(int requestCode,int resultCode, Intent data) {

if (mHelper ==null)return;

if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {

        super.onActivityResult(requestCode, resultCode, data);

        }else {

            String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");//获取订单详细信息

        String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");//获取谷歌市场的订单校验码

            if (requestCode ==RC_REQUEST) {           

            if(purchaseData!=null){

//google play 回调--通知服务已经支付成功

            Service.purchase(purchaseData, dataSignature);

           //Log.d(TAG, "支付回调用成功");

            }

           }

        }

}

@Override

protected void onDestroy() {

super.onDestroy();

DDleSDK.destroy();

if (mHelper !=null)mHelper.dispose();

        mHelper = null;

}


}



0 0
原创粉丝点击