android_in_app_purchases.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. .. _doc_android_in_app_purchases:
  2. Android in-app purchases
  3. ========================
  4. Godot offers a first-party ``GodotGooglePlayBilling`` Android plugin compatible with Godot 3.2.2 and higher.
  5. This plugin uses the `Google Play Billing library <https://developer.android.com/google/play/billing>`__
  6. instead of the now deprecated AIDL IAP implementation. For details of how to migrate from the older
  7. ``GodotPaymentsV3``, see the migration guide: `Migrating from Godot 3.2.1 and lower (GodotPaymentsV3)`_.
  8. If you learn better by looking at an example, you can find the demo project
  9. `here <https://github.com/godotengine/godot-demo-projects/tree/master/mobile/android_iap>`__.
  10. Usage
  11. -----
  12. Getting started
  13. ***************
  14. Make sure you have enabled and successfully set up :ref:`Android Custom Builds <doc_android_custom_build>`.
  15. Grab the ``GodotGooglePlayBilling`` plugin binary and config from the `releases page <https://github.com/godotengine/godot-google-play-billing/releases>`__
  16. and put both into `res://android/plugins`.
  17. The plugin should now show up in the Android export settings, where you can enable it.
  18. Initialize the plugin
  19. *********************
  20. To use the ``GodotGooglePlayBilling`` API:
  21. 1. Obtain a reference to the ``GodotGooglePlayBilling`` singleton
  22. 2. Connect handlers for the plugin signals
  23. 3. Call ``startConnection``
  24. Initialization example:
  25. ::
  26. var payment
  27. func _ready():
  28. if Engine.has_singleton("GodotGooglePlayBilling"):
  29. payment = Engine.get_singleton("GodotGooglePlayBilling")
  30. # These are all signals supported by the API
  31. # You can drop some of these based on your needs
  32. payment.connect("billing_resume", self, "_on_billing_resume") # No params
  33. payment.connect("connected", self, "_on_connected") # No params
  34. payment.connect("disconnected", self, "_on_disconnected") # No params
  35. payment.connect("connect_error", self, "_on_connect_error") # Response ID (int), Debug message (string)
  36. payment.connect("price_change_acknowledged", self, "_on_price_acknowledged") # Response ID (int)
  37. payment.connect("purchases_updated", self, "_on_purchases_updated") # Purchases (Dictionary[])
  38. payment.connect("purchase_error", self, "_on_purchase_error") # Response ID (int), Debug message (string)
  39. payment.connect("sku_details_query_completed", self, "_on_sku_details_query_completed") # SKUs (Dictionary[])
  40. payment.connect("sku_details_query_error", self, "_on_sku_details_query_error") # Response ID (int), Debug message (string), Queried SKUs (string[])
  41. payment.connect("purchase_acknowledged", self, "_on_purchase_acknowledged") # Purchase token (string)
  42. payment.connect("purchase_acknowledgement_error", self, "_on_purchase_acknowledgement_error") # Response ID (int), Debug message (string), Purchase token (string)
  43. payment.connect("purchase_consumed", self, "_on_purchase_consumed") # Purchase token (string)
  44. payment.connect("purchase_consumption_error", self, "_on_purchase_consumption_error") # Response ID (int), Debug message (string), Purchase token (string)
  45. payment.connect("query_purchases_response", self, "_on_query_purchases_response") # Purchases (Dictionary[])
  46. payment.startConnection()
  47. else:
  48. print("Android IAP support is not enabled. Make sure you have enabled 'Custom Build' and the GodotGooglePlayBilling plugin in your Android export settings! IAP will not work.")
  49. The API must be in a connected state prior to use. The ``connected`` signal is sent
  50. when the connection process succeeds. You can also use ``isReady()`` to determine if the plugin
  51. is ready for use. The ``getConnectionState()`` function returns the current connection state
  52. of the plugin.
  53. Return values for ``getConnectionState()``:
  54. ::
  55. # Matches BillingClient.ConnectionState in the Play Billing Library
  56. enum ConnectionState {
  57. DISCONNECTED, # not yet connected to billing service or was already closed
  58. CONNECTING, # currently in process of connecting to billing service
  59. CONNECTED, # currently connected to billing service
  60. CLOSED, # already closed and shouldn't be used again
  61. }
  62. Query available items
  63. *********************
  64. Once the API has connected, query SKUs using ``querySkuDetails()``. You must successfully complete
  65. a SKU query before before calling the ``purchase()`` or ``queryPurchases()`` functions,
  66. or they will return an error. ``querySkuDetails()`` takes two parameters: an array
  67. of SKU name strings, and a string specifying the type of SKU being queried.
  68. The SKU type string should be ``"inapp"`` for normal in-app purchases or ``"subs"`` for subscriptions.
  69. The name strings in the array should match the SKU product ids defined in the Google Play Console entry
  70. for your app.
  71. Example use of ``querySkuDetails()``:
  72. ::
  73. func _on_connected():
  74. payment.querySkuDetails(["my_iap_item"], "inapp") # "subs" for subscriptions
  75. func _on_sku_details_query_completed(sku_details):
  76. for available_sku in sku_details:
  77. print(available_sku)
  78. func _on_sku_details_query_error(response_id, error_message, skus_queried):
  79. print("on_sku_details_query_error id:", response_id, " message: ",
  80. error_message, " skus: ", skus_queried)
  81. Query user purchases
  82. ********************
  83. To retrieve a user's purchases, call the ``queryPurchases()`` function passing
  84. a string with the type of SKU to query. The SKU type string should be
  85. ``"inapp"`` for normal in-app purchases or ``"subs"`` for subscriptions.
  86. The ``query_purchases_response`` signal is sent with the result.
  87. The signal has a single parameter: a :ref:`Dictionary <class_Dictionary>` with
  88. a status code and either an array of purchases or an error message.
  89. Only active subscriptions and non-consumed one-time purchases are
  90. included in the purchase array.
  91. Example use of ``queryPurchases()``:
  92. ::
  93. func _query_purchases():
  94. payment.queryPurchases("inapp") # Or "subs" for subscriptions
  95. func _on_query_purchases_response(query_result):
  96. if query_result.status == OK:
  97. for purchase in query_result.purchases:
  98. _process_purchase(purchase)
  99. else:
  100. print("queryPurchases failed, response code: ",
  101. query_result.response_code,
  102. " debug message: ", query_result.debug_message)
  103. You should query purchases during startup after succesfully retrieving SKU details.
  104. Since the user may make a purchase or resolve a pending transaction from
  105. outside your app, you should recheck for purchases when resuming from the
  106. background. To accomplish this, you can use the ``billing_resume`` signal.
  107. Example use of ``billing_resume``:
  108. ::
  109. func _on_billing_resume():
  110. if payment.getConnectionState() == ConnectionState.CONNECTED:
  111. _query_purchases()
  112. For more information on processing the purchase items returned by
  113. ``queryPurchases()``, see `Processing a purchase item`_
  114. Purchase an item
  115. ****************
  116. To initiate the purchase flow for an item, call ``purchase()`` passing the
  117. product id string of the SKU you wish to purchase.
  118. Reminder: you **must** query the SKU details for an item before you can
  119. pass it to ``purchase()``.
  120. Example use of ``purchase()``:
  121. ::
  122. payment.purchase("my_iap_item")
  123. The payment flow will send a ``purchases_updated`` signal on success or a
  124. ``purchase_error`` signal on failure.
  125. ::
  126. func _on_purchases_updated(purchases):
  127. for purchase in purchases:
  128. _process_purchase(purchase)
  129. func _on_purchase_error(response_id, error_message):
  130. print("purchase_error id:", response_id, " message: ", error_message)
  131. Processing a purchase item
  132. **************************
  133. The ``query_purchases_response`` and ``purchases_updated`` signals provide an array
  134. of purchases in :ref:`Dictionary <class_Dictionary>` format. The purchase Dictionary
  135. includes keys that map to values of the Google Play Billing
  136. `Purchase <https://developer.android.com/reference/com/android/billingclient/api/Purchase>`_ class.
  137. Purchase fields:
  138. ::
  139. dictionary.put("order_id", purchase.getOrderId());
  140. dictionary.put("package_name", purchase.getPackageName());
  141. dictionary.put("purchase_state", purchase.getPurchaseState());
  142. dictionary.put("purchase_time", purchase.getPurchaseTime());
  143. dictionary.put("purchase_token", purchase.getPurchaseToken());
  144. dictionary.put("quantity", purchase.getQuantity());
  145. dictionary.put("signature", purchase.getSignature());
  146. // PBL V4 replaced getSku with getSkus to support multi-sku purchases,
  147. // use the first entry for "sku" and generate an array for "skus"
  148. ArrayList<String> skus = purchase.getSkus();
  149. dictionary.put("sku", skus.get(0));
  150. String[] skusArray = skus.toArray(new String[0]);
  151. dictionary.put("skus", skusArray);
  152. dictionary.put("is_acknowledged", purchase.isAcknowledged());
  153. dictionary.put("is_auto_renewing", purchase.isAutoRenewing());
  154. Check purchase state
  155. ********************
  156. Check the ``purchase_state`` value of a purchase to determine if a
  157. purchase was completed or is still pending.
  158. PurchaseState values:
  159. ::
  160. # Matches Purchase.PurchaseState in the Play Billing Library
  161. enum PurchaseState {
  162. UNSPECIFIED,
  163. PURCHASED,
  164. PENDING,
  165. }
  166. If a purchase is in a ``PENDING`` state, you should not award the contents of the
  167. purchase or do any further processing of the purchase until it reaches the
  168. ``PURCHASED`` state. If you have a store interface, you may wish to display
  169. information about pending purchases needing to be completed in the Google Play Store.
  170. For more details on pending purchases, see
  171. `Handling pending transactions <https://developer.android.com/google/play/billing/integrate#pending>`_
  172. in the Google Play Billing Library documentation.
  173. Consumables
  174. ***********
  175. If your in-app item is not a one-time purchase but a consumable item (e.g. coins) which can be purchased
  176. multiple times, you can consume an item by calling ``consumePurchase()`` passing
  177. the ``purchase_token`` value from the purchase dictionary.
  178. Calling ``consumePurchase()`` automatically acknowledges a purchase.
  179. Consuming a product allows the user to purchase it again, it will no longer appear
  180. in subsequent ``queryPurchases()`` calls unless it is repurchased.
  181. Example use of ``consumePurchase()``:
  182. ::
  183. func _process_purchase(purchase):
  184. if purchase.sku == "my_consumable_iap_item" and purchase.purchase_state == PurchaseState.PURCHASED:
  185. # Add code to store payment so we can reconcile the purchase token
  186. # in the completion callback against the original purchase
  187. payment.consumePurchase(purchase.purchase_token)
  188. func _on_purchase_consumed(purchase_token):
  189. _handle_purchase_token(purchase_token, true)
  190. func _on_purchase_consumption_error(response_id, error_message, purchase_token):
  191. print("_on_purchase_consumption_error id:", response_id,
  192. " message: ", error_message)
  193. _handle_purchase_token(purchase_token, false)
  194. # Find the sku associated with the purchase token and award the
  195. # product if successful
  196. func _handle_purchase_token(purchase_token, purchase_successful):
  197. # check/award logic, remove purchase from tracking list
  198. Acknowledging purchases
  199. ***********************
  200. If your in-app item is a one-time purchase, you must acknowledge the purchase by
  201. calling the ``acknowledgePurchase()`` function, passing the ``purchase_token``
  202. value from the purchase dictionary. If you do not acknowledge a purchase within
  203. three days, the user automatically receives a refund, and Google Play revokes the purchase.
  204. If you are calling ``comsumePurchase()`` it automatically acknowledges the purchase and
  205. you do not need to call ``acknowledgePurchase()``.
  206. Example use of ``acknowledgePurchase()``:
  207. ::
  208. func _process_purchase(purchase):
  209. if purchase.sku == "my_one_time_iap_item" and \
  210. purchase.purchase_state == PurchaseState.PURCHASED and \
  211. not purchase.is_acknowledged:
  212. # Add code to store payment so we can reconcile the purchase token
  213. # in the completion callback against the original purchase
  214. payment.acknowledgePurchase(purchase.purchase_token)
  215. func _on_purchase_acknowledged(purchase_token):
  216. _handle_purchase_token(purchase_token, true)
  217. func _on_purchase_acknowledgement_error(response_id, error_message, purchase_token):
  218. print("_on_purchase_acknowledgement_error id: ", response_id,
  219. " message: ", error_message)
  220. _handle_purchase_token(purchase_token, false)
  221. # Find the sku associated with the purchase token and award the
  222. # product if successful
  223. func _handle_purchase_token(purchase_token, purchase_successful):
  224. # check/award logic, remove purchase from tracking list
  225. Subscriptions
  226. *************
  227. Subscriptions work mostly like regular in-app items. Use ``"subs"`` as the second
  228. argument to ``querySkuDetails()`` to get subscription details. Pass ``"subs"``
  229. to ``queryPurchases()`` to get subscription purchase details.
  230. You can check ``is_auto_renewing`` in the a subscription purchase
  231. returned from ``queryPurchases()`` to see if a user has cancelled an
  232. auto-renewing subscription.
  233. You need to acknowledge new subscription purchases, but not automatic
  234. subscription renewals.
  235. If you support upgrading or downgrading between different subscription levels,
  236. you should use ``updateSubscription()`` to use the subscription update flow to
  237. change an active subscription. Like ``purchase()``, results are returned by the
  238. ``purchases_updated`` and ``purchase_error`` signals.
  239. There are three parameters to ``updateSubscription()``:
  240. 1. The purchase token of the currently active subscription
  241. 2. The product id string of the subscription SKU to change to
  242. 3. The proration mode to apply to the subscription.
  243. The proration values are defined as:
  244. ::
  245. enum SubscriptionProrationMode {
  246. # Replacement takes effect immediately, and the remaining time
  247. # will be prorated and credited to the user.
  248. IMMEDIATE_WITH_TIME_PRORATION = 1,
  249. # Replacement takes effect immediately, and the billing cycle remains the same.
  250. # The price for the remaining period will be charged.
  251. # This option is only available for subscription upgrade.
  252. IMMEDIATE_AND_CHARGE_PRORATED_PRICE,
  253. # Replacement takes effect immediately, and the new price will be charged on
  254. # next recurrence time. The billing cycle stays the same.
  255. IMMEDIATE_WITHOUT_PRORATION,
  256. # Replacement takes effect when the old plan expires, and the new price
  257. # will be charged at the same time.
  258. DEFERRED,
  259. # Replacement takes effect immediately, and the user is charged full price
  260. # of new plan and is given a full billing cycle of subscription,
  261. # plus remaining prorated time from the old plan.
  262. IMMEDIATE_AND_CHARGE_FULL_PRICE,
  263. }
  264. Default behavior is ``IMMEDIATE_WITH_TIME_PRORATION``.
  265. Example use of ``updateSubscription``:
  266. ::
  267. payment.updateSubscription(_active_subscription_purchase.purchase_token, \
  268. "new_sub_sku", SubscriptionProrationMode.IMMEDIATE_WITH_TIME_PRORATION)
  269. The ``confirmPriceChange()`` function can be used to launch price change confirmation flow
  270. for a subscription. Pass the product id of the subscription SKU subject to the price change.
  271. The result will be sent by the ``price_change_acknowledged`` signal.
  272. Example use of ``confirmPriceChange()``:
  273. ::
  274. enum BillingResponse {SUCCESS = 0, CANCELLED = 1}
  275. func confirm_price_change(product_id):
  276. payment.confirmPriceChange(product_id)
  277. func _on_price_acknowledged(response_id):
  278. if response_id == BillingResponse.SUCCESS:
  279. print("price_change_accepted")
  280. elif response_id == BillingResponse.CANCELED:
  281. print("price_change_canceled")
  282. Migrating from Godot 3.2.1 and lower (GodotPaymentsV3)
  283. ------------------------------------------------------
  284. The new ``GodotGooglePlayBilling`` API is not compatible with its predecessor ``GodotPaymentsV3``.
  285. Changes
  286. *******
  287. - You need to enable the Custom Build option in your Android export settings and install
  288. the ``GodotGooglePlayBilling`` plugin manually (see below for details)
  289. - All purchases have to be acknowledged by your app. This is a
  290. `requirement from Google <https://developer.android.com/google/play/billing/integrate#process>`__.
  291. Purchases that are not acknowledged by your app will be refunded.
  292. - Support for subscriptions
  293. - Signals (no polling or callback objects)