- Встраиваем In-App purchase в своё приложение
- In-app purchasing или внутренние платежи в приложениях для Android
- О чем это вообще?
- Что нам понадобится?
- Как это в принципе работает?
- Как все это устроено?
- Какие сообщения мы отсылаем маркету?
- Какие получаем ответы?
- А может, посмотрим лучше на код?
- А как же безопасность?
- Google Play Billing Library release notes
- Google Play Billing Library 4.0 Release (2021-05-18)
- Summary of changes
- Google Play Billing Library 3.0.3 Release (2021-03-12)
- Java and Kotlin Bug fixes
- Unity Bug fixes
- Google Play Billing Library 3.0.2 Release (2020-11-24)
- Bug fixes
- Google Play Billing Library 3.0.1 Release (2020-09-30)
- Bug fixes
- Google Play Billing Library 3.0 Release (2020-06-08)
- Summary of changes
- Bug fixes
- Google Play Billing Library 2.2.1 Release (2020-05-20)
- Bug fixes
- Google Play Billing Library 2.2.0 release and Unity support (2020-03-23)
- Google Play Billing Billing Library 2 for Unity
- Summary of changes
- Google Play Billing Library 2.1.0 Release and Kotlin Extension 2.1.0 Release (2019-12-10)
- Summary of changes
- Google Play Billing Library 2.0.3 Release (2019-08-05)
- Bug fixes
- Google Play Billing Library 2.0.2 Release (2019-07-08)
- Google Play Billing Library 2.0.1 Release (2019-06-06)
- Bug fixes
- Google Play Billing Library 2.0 Release (2019-05-07)
- Purchases must be acknowledged within three days
- BillingFlowParams.setSku() has been removed
- Developer payload is supported
- Consistent offers
- Pending transactions
- API changes
- consumeAsync
- queryPurchaseHistoryAsync
- BillingResult return values
- Bug fixes
- Google Play Billing Library 1.2.2 Release (2019-03-07)
- Bug fixes
- Other changes
- Play Billing Library 1.2.1 Release (2019-03-04)
- Major changes
- Other changes
- Bug fixes
- Google Play Billing Library 1.2 Release (2018-10-18)
- Summary of changes
- Price change confirmation
- Kotlin
- New proration mode
- New method for setting SKU details
- Kotlin
- Play Billing Library 1.1 Release (2018-05-07)
- Summary of changes
- Behavior changes
- Developers can set replaceSkusProrationMode in BillingFlowParams class
- Kotlin
- replaceSkusProration is no longer supported in BillingFlowParams class
- launchBillingFlow() now triggers a callback for failed responses
- Bug fixes
- Google Play Billing Library 1.0 Release (2017-09-19, Announcement)
- Important changes
- Behavior changes
- BillingClient.Builder class
- Kotlin
- launchBillingFlow method is now called using a BillingFlowParams class
- Kotlin
- New way to query available products
- Kotlin
- Kotlin
- Parameters order changed on onConsumeResponse() method
- Kotlin
- Unwrapped PurchaseResult object
- Kotlin
- Bug fixes
- Developer Preview 1 Release (2017-06-12, Announcement)
Встраиваем In-App purchase в своё приложение
Во второй части статьи про свою новогоднюю игрушку я расскажу про внутри игровые покупки. Я совсем не люблю рекламу в приложениях, по этому вопрос встраивания рекламы в своё приложение, для меня отпал сразу. Мой опыт выкладывания в Gooogle Play платных игр говорит о том, что резко падает количество желающих эту игру скачать, по этому вариант продажи игры, тоже отпал. И так как я не стремлюсь заработать на игре состояние, а делаю это больше в своё удовольствие, то решил что пусть пользователи сами решают, платить что-нибудь или нет.
Да, я решил использовать в игре донаты. Если потом вдруг будет интересная статистика по донатам в игре, то обязательно ею поделюсь в следующей статье.
Для работы со встраиваемыми покупками я остановился на очень простой, на мой взгляд, но вполне функциональной библиотеке Anjlab (ссылка на GitHub).
В Google play существуют два типа товаров:
- Продукт — приобретается разово, до реализации, не имеет срока действия
- Подписка — может приобретаться регулярно, имеет срок действия
Покупка товаров работает асинхронно, то есть сначала делаете запрос на покупку, потом получаете ответ об успешной покупке или коде ошибки.
Для подключения библиотеки в наше приложение необходимо в файле build.gradle (Module: app)
Добавить строку compile ‘com.anjlab.android.iab.v3:library:1.0.44’ в раздел dependencies (Не забываем после внесения изменений, нажать Sync Now в верхнем правом углу окна.)
Добавляем в файл с Activity две библиотеки:
Снабжаем нашу Activity функционалом BillingProcessor.IBillingHandler:
Для работы с покупками создаём объект класса BillingProcessor и добавляем требуемые методы:
В методе onCreate инициализируем переменную:
Заполняем кодом переопределённые методы:
Со стороны приложения всё сделали, теперь надо выполнить ряд действий в консоли Google Play.
Сначала необходимо получить «ЛИЦЕНЗИОННЫЙ КЛЮЧ ИЗ Google Play». Этот ключ уникальный для каждого приложения, по этому, чтобы его получить, приложение необходимо опубликовать, например, как бета-версию.
После того как приложение будет опубликовано, заходим в раздел управления приложением (просто щёлкнув на него в списке приложений), затем в левом меню раскрываем раздел «Инструменты разработки» и переходим в подраздел «Службы и API», там в панели «Лицензирование и продажа контента» и есть необходимый ключ, который имеет вид «MIIBIjANBgkqhkiG9w0BAQEFAAOCA. »
Этот ключ используется при вызове метода:
Теперь нам необходимо создать контент, который будем продавать. Для этого в левом меню переходим в раздел «Настройки страницы приложения» и подраздел «Контент для продажи».
Далее нам необходимо определить какой тип контента нам нужен — продукт или подписка, определившись с типом, переходим на соответствующую вкладку и создаём необходимый контент, заполняя требуемые поля. В приложении может быть как продукты, так и подписки одновременно.
Стоит обратить внимание на именование идентификатора продукта, именно он будет использоваться в нашем приложении.
Например, создаём продукт с идентификатором one_dollar_donate, и для покупки в приложении будем использовать следующий вызов функции:
С Наступающим Новым Годом! и пусть он будет интереснее предыдущих!
Источник
In-app purchasing или внутренние платежи в приложениях для Android
О чем это вообще?
С версией приложения Android Market 2.3.0 для разработчиков приложений для платформы Android открылась возможность предоставлять пользователям платежи внутри самих приложений. Теперь можно продавать уровни и артефакты, видео, музыку, плагины и прочее, пользуясь лишь встроенными средствами платформы. Давайте увидим, как это можно сделать.
Что нам понадобится?
Как обычно, любимая IDE, Android SDK и пример приложения.
Так же будет полезным представлять себе, что такое Service, BroadcastReceiver и, конечно, Activity.
Так же нам понадобится разрешение в файле манифеста —
, без него ничего не заработает.
Как это в принципе работает?
Работает все через сервис в приложении Android Market. Он умеет посылать запросы на получение деталей определенной вещи, которую хочет купить пользователь, на покупку, получать ответы о успехе или неудачи покупки, и прочее. Вся информация о вещах, которые вы продаете, должна быть заведена через Консоль Разработчика для конкретного приложения. Как только мы получили сигнал об успешной покупке, мы можем начать грузить с нашего сервера контент.
Как все это устроено?
На сервере в маркете хранится информация о вещах, которые можно купить. С сервером взаимодействует клиентское приложение маркета. С ним взаимодействует наше приложение.
Наше приложение будет состоять как минимум из:
- BillingService. Это сервис, который связан с приложением маркета, и отправляет ему всю информацию об операциях и получает на них ответы, в случае, если они синхронные.
- BillingReceiver. Получает асинхронные ответы от приложения маркета.
- PurchaseObserver. Сущность, которая будет оповещать UI об изменениях состояния покупок.
Какие сообщения мы отсылаем маркету?
Вначале нам нужно соединить наш BillingService с приложением маркета для того, чтобы вызывать метод sendBillingRequest сервиса MarketBillingService. Интерфейс сервиса описан в файле IMarketBillingService.aidl, его можно скачать отсюда, а положить надо в com.android.vending.billing пакет вашего приложения. IDE должна сразу же сгенерить IMarketBillingService.java файл, который нам понадобиться для вызова вышеупомянутого метода.
Сам метод принимает параметр Bundle, в котором и хранится вся информация. Самой важной является параметр с ключом «BILLING_REQUEST». Он определяет тип запроса. Они бывают:
• CHECK_BILLING_SUPPORTED – проверка доступности in-app billing.
• REQUEST_PURCHASE – запрос покупки.
• GET_PURCHASE_INFORMATION – получение информации об изменении состояния покупки.
• CONFIRM_NOTIFICATIONS – подтверждение факта получение уведомления от приложения маркета.
• RESTORE_TRANSACTIONS – восстановление транзакций по уже купленным вещам.
Какие получаем ответы?
Метод синхронно возвращает ответ, который тоже представляет из себя Bundle. В нем лежит:
• RESPONSE_CODE — код ответа
• PURCHASE_INTENT — PendingIntent , для того, чтобы запустить активти покупки.
• REQUEST_ID – идентификатор посланного запроса
В случае асинхронных ответов(получаемых через BillingReceiver), в них лежит следующее:
• com.android.vending.billing.RESPONSE_CODE
Код ответа. Маркет подтверждает успех или неудачу посылки запроса.
• com.android.vending.billing.IN_APP_NOTIFY
Оповещение о том, что статус покупки изменился. После этого сообщения нужно отправлять запрос с типом GET_PURCHASE_INFORMATION , чтобы получить инфу.
• com.android.vending.billing.PURCHASE_STATE_CHANGED
А тут приходит детальная информация о покупке. Она включает в себя nonce, список заказов, с указанием идентификаторов продуктов, их состояний и проч.
Последовательность при покупке будет такая:
1. Посылаем REQUEST_PURCHASE
2. Получаем синхронный ответ
3. Запускаем Activity покупки(также встроенную в приложение маркета)
4. Получаем асинхронное сообщение IN_APP_NOTIFY
5. Посылаем GET_PURCHASE_INFORMATION
6. Получаем синхронный ответ
7. Получаем асинхронный ответ PURCHASE_STATE_CHANGED
8. Отправляем CONFIRM_NOTIFICATIONS
9. Получаем синхронный ответ
А может, посмотрим лучше на код?
Итак, основные моменты в коде:
1. Коннект к маркету.
В onCreate() в BillingService пишем:
try <
boolean bindResult = getApplicationContext().bindService(
new Intent( «com.android.vending.billing.MarketBillingService.BIND» ),
this ,
Context.BIND_AUTO_CREATE);
if (bindResult) <
Log.i(TAG, «Service bind successful.» );
> else <
Log.e(TAG, «Could not bind to the MarketBillingService.» );
>
> catch (SecurityException e) <
Log.e(TAG, «Security exception: » + e);
>
//И чуть ниже:
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) <
Log.i(TAG, «MarketBillingService connected.» );
marketService = IMarketBillingService.Stub.asInterface(iBinder);
runPendingRequests();
>
* This source code was highlighted with Source Code Highlighter .
2. Отправка запросов.
В примере приложения создана иерархия классов для запросов и это правильно. Самая главная вещь в них – это отложенная отправка. Дело в том, что bindService происходит асинхронно, а значит ссылку на MarketBillingService мы получаем гораздо позже, чем кончается onCreate(), и даже позже, чем пытаемся в первый раз выполнить запросы. Поэтому делаем так:
/**
* Run the request, starting the connection if necessary.
*
* @return this request if the request was not executed in order to queue it.
*/
public final AbstractRequest runRequest() <
if (runIfConnected()) <
return null ;
>
return this ;
>
/**
* Try running the request directly if the service is already connected.
*
* @return true if the request ran successfully; false if the service
* is not connected or there was an error when trying to use it
*/
public boolean runIfConnected() <
if (service.isConnected()) <
try <
requestId = run();
if (requestId >= 0) <
service.addRequest(requestId, this );
>
return true ;
> catch (MyException e) <
onException(e);
>
>
return false ;
>
* This source code was highlighted with Source Code Highlighter .
Возвращение запроса нужно, чтобы запомнить его в списке ожидающих отправки запросов в сервисе. Потом, когда мы получим ссылку на MarketBillingService в onServiceConnected(), мы все запросы попробуем отправить еще раз.
3. Оповещение UI
В BillingService будем хранить ссылку на некую сущность, которая хранит в себе Handler от нашего UI. Тогда по получении ответов можно будет делать следующее:
private void notifyGui( int messageId, PurchasedItem item) <
if (observer != null ) <
observer.notifyGui(messageId, item);
> else <
// пошлем здесь оповещение в NotificationBar
>
>* This source code was highlighted with Source Code Highlighter .
Важно: не забывать обнулять observer сервиса из своей Activity при выходе из нее и восстанавливать эту ссылку. Делается это так:
@Override
protected void onUserLeaveHint() <
if (billingService != null ) <
unbindService( this );
billingService.resetEventDispatcher();
billingService = null ;
>
super.onUserLeaveHint();
>
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) <
//Connected to BillingService
if (componentName.getShortClassName().equals(serviceClassName)) <
billingService = ((BillingService.LocalBinder) iBinder).getService();
billingService.setObserver( new PurchaseObserver());
try <
billingService.checkBillingAvailability();
> catch (MyException e) <
Log.e(TAG, «Billing unavailable» , e);
Toast.makeText( this , «Billing unavailable» , Toast.LENGTH_LONG).show();
>
>
>
* This source code was highlighted with Source Code Highlighter .
4. Запуск Activity покупки.
Загляните в PurchaseObserver класс примера. Там есть метод public void startBuyPageActivity(PendingIntent pendingIntent, Intent intent). PendingIntent – это то, что мы получили ответом от маркета. А Intent – просто new Intent().
Что же этот метод делает?
На самом деле в этот класс передается инстанс вашей Activity. Дальше от нее через reflection происходит попытка получить метод startInstentSender. Этот метод появился только в Android 2.0. Если он есть, то метод вызывается, и Activity запускается в стеке Activity нашего приложения. Если же метод не найден, то происходит старт Activity в отдельном стеке.
А как же безопасность?
Вопрос безопасности – тема отдельной статьи, и так уже много. В примере приложения за безопасность отвечает класс Security. Скажу только, что верифицировать покупки нужно не в приложении(как это сделано в примере), а на собственном сервере, дабы не давать логику проверки в руки потенциальных обладателей apk.
Источник
Google Play Billing Library release notes
This topic contains release notes for the Google Play Billing Library.
Google Play Billing Library 4.0 Release (2021-05-18)
Version 4.0.0 of the Google Play Billing Library and Kotlin extensions are now available.
Summary of changes
Added new subscription replacement mode IMMEDIATE_AND_CHARGE_FULL_PRICE .
Added BillingClient.getConnectionState() method to retrieve the Play Billing Library’s connection state.
Updated Javadoc and implementation to indicate which thread a method can be called on and which thread results are posted.
Added BillingFlowParams.Builder.setSubscriptionUpdateParams() as a new way to initiate subscription updates. This replaces BillingFlowParams#getReplaceSkusProrationMode , BillingFlowParams#getOldSkuPurchaseToken , BillingFlowParams#getOldSku , BillingFlowParams.Builder#setReplaceSkusProrationMode , BillingFlowParams.Builder#setOldSku which have been removed.
Added Purchase#getSkus() and PurchaseHistoryRecord#getSkus() . These replace Purchase#getSku and PurchaseHistoryRecord#getSku which have been removed.
Removed BillingFlowParams#getSku , BillingFlowParams#getSkuDetails and BillingFlowParams#getSkuType .
Google Play Billing Library 3.0.3 Release (2021-03-12)
Version 3.0.3 of the Google Play Billing Library, Kotlin extension, and Unity plugin are now available.
Java and Kotlin Bug fixes
- Fix memory leak when endConnection() is called.
- Fix issue when the Google Play Billing Library is used by apps which utilize the single task launch mode. A onPurchasesUpdated() callback will be triggered when an app is resumed from the Android launcher and the billing dialog was visible prior to being suspended.
Unity Bug fixes
- Update to Java version 3.0.3 to fix memory leak and resolve issue preventing purchases when an app is resumed from the Android launcher and the billing dialog was visible prior to being suspended.
Google Play Billing Library 3.0.2 Release (2020-11-24)
Version 3.0.2 of the Google Play Billing Library and Kotlin extension are now available.
Bug fixes
- Fixed a bug in the Kotlin extension where the coroutine fails with error «Already resumed».
- Fixed unresolved references when the Kotlin extension is used with the kotlinx.coroutines library version 1.4+.
Google Play Billing Library 3.0.1 Release (2020-09-30)
Version 3.0.1 of the Google Play Billing Library and Kotlin extension are now available.
Bug fixes
- Fixed a bug where if the app was killed and restored during the billing flow, PurchasesUpdatedListener may not be called with the purchase result.
Google Play Billing Library 3.0 Release (2020-06-08)
Version 3.0.0 of the Google Play Billing Library, Kotlin extension, and Unity plugin are now available.
Summary of changes
- Removed rewarded SKU support.
- Removed the ChildDirected and UnderAgeOfConsent parameters.
- Removed deprecated developer payload methods.
- Removed deprecated methods BillingFlowParams.setAccountId() and BillingFlowParams.setDeveloperId() .
- Removed deprecated methods BillingFlowParams.setOldSkus(String oldSku) and BillingFlowParams.addOldSku(String oldSku) .
- Added nullability annotations.
Bug fixes
- SkuDetails.getIntroductoryPriceCycles() now returns int instead of String .
- Fixed a bug where the billing flow would be treated as having extra params even if no extra params were set.
Google Play Billing Library 2.2.1 Release (2020-05-20)
Version 2.2.1 of the Google Play Billing library is now available.
Bug fixes
- Updated the default version of the Java Play Billing library that the Kotlin extension depends on.
Google Play Billing Library 2.2.0 release and Unity support (2020-03-23)
Version 2.2.0 of the Google Play Billing provides functionality that helps developers ensure purchases are attributed to the correct user. These changes replace the need to build custom solutions based on developer payload. As part of this update, the developer payload functionality has been deprecated and will be removed in a future release. For more information, including recommended alternatives, see Developer payload.
Google Play Billing Billing Library 2 for Unity
In addition to the current Java and Kotlin versions of Google Play Billing Library 2, we released a version of the library for use with Unity. Game developers using the Unity in-app purchase API can upgrade now to take advantage of all Google Play Billing Library 2 features and to make the subsequent upgrades to future versions of the Google Play Billing Library easier.
Summary of changes
- Java Google Play Billing Library
- In AcknowledgePurchaseParams , deprecated setDeveloperPayload() and getDeveloperPayload() methods.
- In ConsumeParams , deprecated setDeveloperPayload() and getDeveloperPayload() methods.
- In BillingFlowParams , renamed setAccountId() to setObfuscatedAccountId() , and documented length restriction of 64 characters and restriction disallowing Personally Identifiable Information (PII) in this field. setAccountId() has been marked as deprecated and will be removed in a future library version.
- In BillingFlowParams , added setObfuscatedProfileId() which works similarly to setObfuscatedAccountId() . For more information, see Developer payload updates and alternatives.
- In Purchase , added the getAccountIdentifiers() method to return the obfuscated account identifiers set in BillingFlowParams .
- In BillingClient , the loadRewardedSku() method has been marked deprecated as part of deprecating rewarded SKUs. You can find more information about the deprecation in the Play Console Help Center.
Google Play Billing Library 2.1.0 Release and Kotlin Extension 2.1.0 Release (2019-12-10)
Version 2.1.0 of the Google Play Billing library and the new Kotlin extension are now available. The Play Billing Library Kotlin extension provides idiomatic API alternatives for Kotlin consumption, featuring better null-safety and coroutines. For code examples, see Use the Google Play Billing Library.
This version contains the following changes.
Summary of changes
- In BillingFlowParams , deprecated setOldSku(String oldSku) and replaced with setOldSku(String oldSku, String purchaseToken) , to disambiguate when multiple accounts on the device own the same sku.
Google Play Billing Library 2.0.3 Release (2019-08-05)
Version 2.0.3 of the Google Play Billing library is now available.
Bug fixes
- Fixed a bug where querySkuDetailsAsync() would occasionally fail with code DEVELOPER_ERROR instead of returning a successful result.
Google Play Billing Library 2.0.2 Release (2019-07-08)
Version 2.0.2 of the Google Play Billing library is now available. This release contains updates to the reference documentation and does not change library functionality.
Google Play Billing Library 2.0.1 Release (2019-06-06)
Version 2.0.1 of the Google Play Billing library is now available. This version contains the following changes.
Bug fixes
- Fixed a bug where debug messages were being returned as null in some cases.
- Fixed a potential memory leak issue.
Google Play Billing Library 2.0 Release (2019-05-07)
Version 2.0 of the Google Play Billing library is now available. This version contains the following changes.
Purchases must be acknowledged within three days
Google Play supports purchasing products from inside of your app (in-app) or outside of your app (out-of-app). In order for Google Play to ensure a consistent purchase experience regardless of where the user purchases your product, you must acknowledge all purchases received through the Google Play Billing Library as soon as possible after granting entitlement to the user. If you do not acknowledge a purchase within three days, the user automatically receives a refund, and Google Play revokes the purchase. For pending transactions (new in version 2.0), the three-day window starts when the purchase has moved to the PURCHASED state and does not apply while the purchase is in a PENDING state.
For subscriptions, you must acknowledge any purchase that has a new purchase token. This means that all initial purchases, plan changes, and re-signups need to be acknowledged, but you do not need to acknowledge subsequent renewals. To determine if a purchase needs acknowledgment, you can check the acknowledgement field in the purchase.
The Purchase object now includes an isAcknowledged() method that indicates whether a purchase has been acknowledged. In addition, the Google Play Developer API includes acknowledgement boolean values for both Purchases.products and Purchases.subscriptions . Before acknowledging a purchase, be sure to use these methods to determine if the purchase has already been acknowledged.
You can acknowledge a purchase by using one of the following methods:
- For consumable products, use consumeAsync() , found in the client API.
- For products that aren’t consumed, use acknowledgePurchase() , found in the client API.
- A new acknowledge() method is also available in the Server API.
BillingFlowParams.setSku() has been removed
The previously-deprecated BillingFlowParams#setSku() method has been removed in this release. Before rendering products in a purchase flow, you must now call BillingClient.querySkuDetailsAsync() , passing the resulting SkuDetails object to BillingFlowParams.Builder.setSkuDetails() .
Developer payload is supported
Version 2.0 of the Google Play Billing library adds support for developer payload—arbitrary strings that can be attached to purchases. You can attach a developer payload parameter to a purchase, but only when the purchase is acknowledged or consumed. This is unlike developer payload in AIDL, where the payload could be specified when launching the purchase flow. Because purchases can now be initiated from outside of your app, this change ensures that you always have an opportunity to add a payload to purchases.
To access the payload in the new library, Purchase objects now include a getDeveloperPayload() method.
Consistent offers
When you offer a discounted SKU, Google Play now returns the original price of the SKU so that you can show users that they are receiving a discount.
SkuDetails contains two new methods for retrieving the original SKU price:
- getOriginalPriceAmountMicros() — returns the unformatted original price of the SKU before discount.
- getOriginalPrice() — returns the original price with additional currency formatting.
Pending transactions
With version 2.0 of the Google Play Billing library, you must support purchases where additional action is required before granting entitlement. For example, a user might choose to purchase your in-app product at a physical store using cash. This means that the transaction is completed outside of your app. In this scenario, you should grant entitlement only after the user has completed the transaction.
To enable pending purchases, call enablePendingPurchases() as part of initializing your app.
Use Purchase.getPurchaseState() to determine whether the purchase state is PURCHASED or PENDING . Note that you should grant entitlement only when the state is PURCHASED . You should check for Purchase status updates by doing the following:
- When starting your app, call BillingClient.queryPurchases() to retrieve the list of unconsumed products associated with the user.
- Call Purchase.getPurchaseState() on each returned Purchase object.
- Implement the onPurchasesUpdated() method to respond to changes to Purchase objects.
In addition, the Google Play Developer API includes a PENDING state for Purchases.products . Pending transactions are not supported for subscriptions.
This release also introduces a new real-time developer notification type, OneTimeProductNotification . This notification type contains a single message whose value is either ONE_TIME_PRODUCT_PURCHASED or ONE_TIME_PRODUCT_CANCELED . This notification type is sent only for purchases associated with delayed forms of payment, such as cash.
When acknowledging pending purchases, be sure to acknowledge only when the purchase state is PURCHASED and not PENDING .
API changes
Version 2.0 of the Google Play Billing library contains several API changes to support new features and clarify existing functionality.
consumeAsync
consumeAsync() now takes a ConsumeParams object instead of a purchaseToken . ConsumeParams contains the purchaseToken as well as an optional developer payload.
The previous version of consumeAsync() has been removed in this release.
queryPurchaseHistoryAsync
To minimize confusion, queryPurchaseHistoryAsync() now returns a PurchaseHistoryRecord object instead of a Purchase object. The PurchaseHistoryRecord object is the same as a Purchase object, except that it reflects only the values returned by queryPurchaseHistoryAsync() and does not contain the autoRenewing , orderId , and packageName fields. Note that nothing has changed with the returned data— queryPurchaseHistoryAsync() returns the same data as before.
BillingResult return values
APIs that previously returned a BillingResponse integer value now return a BillingResult object. BillingResult contains the BillingResponse integer as well as a debug string that you can use to diagnose errors. The debug string uses an en-US locale and is not meant to be shown to end users.
Bug fixes
- SkuDetails.getIntroductoryPriceAmountMicros() now returns a long instead of a String .
Google Play Billing Library 1.2.2 Release (2019-03-07)
Version 1.2.2 of the Google Play Billing library is now available. This version contains the following changes.
Bug fixes
- Fixed a threading issue introduced in v1.2.1. Background calls no longer block the main thread.
Other changes
- Although using the main thread is still recommended, you can now instantiate the Google Play Billing Library from a background thread.
- Instantiation has been fully migrated to the background thread to reduce the chance of causing ANRs.
Play Billing Library 1.2.1 Release (2019-03-04)
Version 1.2.1 of the Google Play Billing library is now available. This version contains the following changes.
Major changes
- Added support for rewarded products. For more information on monetization options, see Add rewarded-product-specific features.
Other changes
- Added public constructors for PurchasesResult and SkuDetailsResult to make testing easier.
- SkuDetails objects can use a new method, getOriginalJson() .
- All AIDL service calls are now handled by background threads.
Bug fixes
- Null callback listeners are no longer passed into public APIs.
Google Play Billing Library 1.2 Release (2018-10-18)
Version 1.2 of the Google Play Billing library is now available. This version contains the following changes.
Summary of changes
- The Google Play Billing Library is now licensed under the Android Software Development Kit License Agreement.
- Added the launchPriceChangeConfirmationFlow API, which prompts users to review a pending change to a subscription price.
- Added support for a new proration mode, DEFERRED , when upgrading or downgrading a user’s subscription.
- In the BillingFlowParams class, replaced setSku() with setSkuDetails() .
- Minor bug fixes and code optimizations.
Price change confirmation
You can now change the price of a subscription in Google Play Console and prompt users to review and accept the new price when they enter your app.
To use this API, create a PriceChangeFlowParams object by using the skuDetails of the subscription product, and then call launchPriceChangeConfirmationFlow() . Implement the PriceChangeConfirmationListener to handle the result when the price change confirmation flow finishes, as shown in the following code snippet:
Kotlin
The price change confirmation flow displays a dialog containing the new pricing information, asking users to accept the new price. This flow returns a response code of type BillingClient.BillingResponse .
New proration mode
When upgrading or downgrading a user’s subscription, you can use a new proration mode, DEFERRED . This mode updates the user’s subscription when it next renews. To learn more about how to set this proration mode, see Set proration mode.
New method for setting SKU details
In the BillingFlowParams class, the setSku() method has been deprecated. This change serves to optimize the Google Play Billing flow.
When constructing a new instance of BillingFlowParams in your in-app billing client, we recommend that you instead work with the JSON object directly using setSkuDetails() , as shown in the following code snippet:
In the BillingFlowParams Builder class, the setSku() method has been deprecated. Instead, use the setSkuDetails() method, as shown in the following code snippet. The object passed into setSkuDetails() object comes from the querySkuDetailsAsync() method.
Kotlin
Play Billing Library 1.1 Release (2018-05-07)
Version 1.1 of the Google Play Billing library is now available. This version contains the following changes.
Summary of changes
- Added support to specify a proration mode in BillingFlowParams when upgrading/downgrading an existing subscription.
- The replaceSkusProration boolean flag in BillingFlowParams is no longer supported. Use replaceSkusProrationMode instead.
- launchBillingFlow() now triggers a callback for failed responses.
Behavior changes
Version 1.1 of the Google Play Billing library contains the following behavior changes.
Developers can set replaceSkusProrationMode in BillingFlowParams class
A ProrationMode provides further details on the type of proration when upgrading or downgrading a user’s subscription.
Kotlin
Currently, Google Play supports following proration modes:
IMMEDIATE_WITH_TIME_PRORATION | Replacement takes effect immediately, and the new expiration time will be prorated and credited or charged to the user. This is the current default behavior. |
IMMEDIATE_AND_CHARGE_PRORATED_PRICE | Replacement takes effect immediately, and the billing cycle remains the same. The price for the remaining period will be charged. Note: This option is only available for subscription upgrade. |
IMMEDIATE_WITHOUT_PRORATION | Replacement takes effect immediately, and the new price will be charged on next recurrence time. The billing cycle stays the same. |
replaceSkusProration is no longer supported in BillingFlowParams class
Developers used to be able to set a boolean flag to charge a prorated amount for a subscription upgrade request. Given that we are supporting ProrationMode , which contains more detailed proration instruction, this boolean flag is no longer supported.
launchBillingFlow() now triggers a callback for failed responses
The Billing Library will always trigger the PurhcasesUpdatedListener callback and return a BillingResponse asynchronously. The synchronous return value of BillingResponse is kept as well.
Bug fixes
- Properly exits early in async methods when service is disconnected.
- Builder param objects no longer mutates built objects.
- Issue 68087141: launchBillingFlow() now trigger callback for failed responses.
Google Play Billing Library 1.0 Release (2017-09-19, Announcement)
Version 1.0 of the Google Play Billing library is now available. This version contains the following changes.
Important changes
- Embedded billing permission inside library’s manifest. It’s not necessary to add the com.android.vending.BILLING permission inside Android manifest anymore.
- New builder added to BillingClient.Builder class.
- Introduced builder pattern for SkuDetailsParams class to be used on methods to query SKUs.
- Several API methods were updated for consistency (the same return argument names and order).
Behavior changes
Version 1.0 of the Google Play Billing library contains the following behavior changes.
BillingClient.Builder class
BillingClient.Builder is now initialized via the newBuilder pattern:
Kotlin
launchBillingFlow method is now called using a BillingFlowParams class
To initiate the billing flow for a purchase or subscription, the launchBillingFlow() method receives a BillingFlowParams instance initialized with parameters specific to the request:
Kotlin
New way to query available products
Arguments for queryPurchaseHistoryAsync() and querySkuDetailsAsync() methods were wrapped into a Builder pattern:
Kotlin
The result is now returned via result code and a list of SkuDetails objects instead of previous wrapper class for your convenience and to be consistent across our API:
Kotlin
Parameters order changed on onConsumeResponse() method
The order of arguments for onConsumeResponse from the ConsumeResponseListener interface has changed to be consistent across our API:
Kotlin
Unwrapped PurchaseResult object
PurchaseResult has been unwraped to be consistent across our API:
Kotlin
Bug fixes
Developer Preview 1 Release (2017-06-12, Announcement)
Developer preview launched, aimed to simplify the development process when it comes to billing, allowing developers to focus their efforts on implementing logic specific to the Android app, such as application architecture and navigation structure.
The library includes several convenient classes and features for you to use when integrating your Android apps with the Google Play Billing API. The library also provides an abstraction layer on top of the Android Interface Definition Language (AIDL) service, making it easier for developers to define the interface between the app and the Google Play Billing API.
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник