caTea 블로그

Android 인앱결제 구현하기 본문

android

Android 인앱결제 구현하기

ZaRas 2015. 6. 22. 16:59
반응형

boolean mIsPremium = false;

    

static final String SKU_PREMIUM = "premium";

private final String TAG = "PremiumUpgradeActivity";

private IInAppBillingService mService = null;

private IabHelper mHelper;

private TextView backView = null;

private TextView infoText = null;



protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_premium);

Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND");

// This is the key line that fixed everything for me

intent.setPackage("com.android.vending"); //롤리팝 버젼 부터 이코드가 들어가야함

bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), mServiceConn, Context.BIND_AUTO_CREATE);

String base64EncodiedPushedkey = "라이센스키!!!";

        // developer console  -> 서비스및 API -> 어플리케이션용 라이센스 키를 복사해서 넣으시면 됩니다.

        InAppInit_U(base64EncodiedPushedkey, true);

 

        Button innapp1 = (Button) findViewById(R.id.innapp1);

        innapp1.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                InAppBuyItem_U(SKU_PREMIUM); // 제품id를 써줍니다. 앱배포시에 인앱상품등록시  등록할 id입니다.

            }

        });

        

        backView = (TextView) findViewById(R.id.premium_back_view);

        backView.setOnClickListener(this);

}



public void InAppInit_U(String strPublicKey, boolean bDebug) {

        Log.d("myLog", "Creating IAB helper." + bDebug);

        mHelper = new IabHelper(this, strPublicKey);

 

        if (bDebug == true) {

            mHelper.enableDebugLogging(true, "IAB");

        }

 

        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {

 

            @Override

            public void onIabSetupFinished(IabResult result) {

                // TODO Auto-generated method stub

                boolean bInit = result.isSuccess();

                Log.d("myLog", "IAB Init " + bInit + result.getMessage());

 

                if (bInit == true) {

                    Log.d("myLog", "Querying inventory.");

 

                    mHelper.queryInventoryAsync(mGotInventoryListener);

                }

                

            }


        });

    }

IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {

        public void onQueryInventoryFinished(IabResult result,

                Inventory inventory) {

            if (result.isFailure()) {

                Log.d("myLog", "Failed to query inventory: " + result);

                SendConsumeResult(null, result);

                return;

            }

 

            /*

             * Check for items we own. Notice that for each purchase, we check

             * the developer payload to see if it's correct! See

             * verifyDeveloperPayload().

             */

 

            Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM);

            mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));

            if(mIsPremium == true){

            Configuration.setPremium(PremiumUpgradeActivity.this,mIsPremium);

            updateUi();

            }

            Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));

            Log.d("myLog", "Query inventory was successful.");

        }


    };



코드를 보면 알겠지만 엑티비티가 띄워지면 InAppInit_U 함수를 타고 mHelper.queryInventoryAsync(mGotInventoryListener); 코드를 실행하게된다 그러면 mGotInventoryListener 콜백함수로 들어오게되는데 mIsPremium 이 true면 구매한 앱이고 false 면 구매하지 않은 앱이다




public void InAppBuyItem_U(final String strItemId) {

        runOnUiThread(new Runnable() {

 

            @Override

            public void run() {

                // TODO Auto-generated method stub

 

                /*

                 * TODO: for security, generate your payload here for

                 * verification. See the comments on verifyDeveloperPayload()

                 * for more info. Since this is a SAMPLE, we just use an empty

                 * string, but on a production app you should carefully generate

                 * this.

                 */

            try{

            String payload = Configuration.userId

            mHelper.launchPurchaseFlow(PremiumUpgradeActivity.this, strItemId, 1001, mPurchaseFinishedListener, payload);

     

                    Log.d("myLog", "InAppBuyItem_U " + strItemId);

                 }catch(Exception e){

                 e.printStackTrace();

                 }

                

            }

        });

    }


IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {

        public void onIabPurchaseFinished(IabResult result, Purchase purchase) {

            Log.d("myLog", "Purchase finished: " + result + ", purchase: "

                    + purchase);  //결제 완료 되었을때 각종 결제 정보들을 볼 수 있습니다. 이정보들을 서버에 저장해 놓아야 결제 취소시 변경된 정보를 관리 할 수 있을것 같습니다~

 

            if (purchase != null) {

                if (!verifyDeveloperPayload(purchase)) {

                    Log.d("myLog",

                            "Error purchasing. Authenticity verification failed.");

                }

 

                mHelper.consumeAsync(purchase, mConsumeFinishedListener);

            } else {

                Toast.makeText(PremiumUpgradeActivity.this,

                        getResources().getString(R.string.premium_near_nonpass),

                        Toast.LENGTH_SHORT).show();

            }

        }

    };



@Override

protected void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

if(mServiceConn != null){

unbindService(mServiceConn);

}

}


boolean verifyDeveloperPayload(Purchase p) {

        String payload = p.getDeveloperPayload();

 

        /*

         * TODO: verify that the developer payload of the purchase is correct.

         * It will be the same one that you sent when initiating the purchase.

         * 

         * WARNING: Locally generating a random string when starting a purchase

         * and verifying it here might seem like a good approach, but this will

         * fail in the case where the user purchases an item on one device and

         * then uses your app on a different device, because on the other device

         * you will not have access to the random string you originally

         * generated.

         * 

         * So a good developer payload has these characteristics:

         * 

         * 1. If two different users purchase an item, the payload is different

         * between them, so that one user's purchase can't be replayed to

         * another user.

         * 

         * 2. The payload must be such that you can verify it even when the app

         * wasn't the one who initiated the purchase flow (so that items

         * purchased by the user on one device work on other devices owned by

         * the user).

         * 

         * Using your own server to store and verify developer payloads across

         * app installations is recommended.

         */

 

        return true;

    }


결제 버튼 클릭시 InAppBuyItem_U 함수를 타게 된다 결제가 끝나면 mPurchaseFinishedListener 콜백함수로 오게된다 여기서 다양한 result 값을 받게된다 그럼 20000




728x90