android_in_app_purchases.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. .. _doc_android_in_app_purchases:
  2. Android in-app purchases
  3. ========================
  4. Godot offers a first-party ``GodotGooglePlayBilling`` Android plugin compatible with Godot 4.2+ which uses the `Google Play Billing library <https://developer.android.com/google/play/billing>`_.
  5. Usage
  6. -----
  7. Getting started
  8. ~~~~~~~~~~~~~~~
  9. Make sure you have enabled and successfully set up :ref:`Android Gradle Builds <doc_android_gradle_build>`.
  10. Follow the installation instructions on the ``GodotGooglePlayBilling`` `github page <https://github.com/godotengine/godot-google-play-billing>`__.
  11. Initialize the plugin
  12. ~~~~~~~~~~~~~~~~~~~~~
  13. To use the ``GodotGooglePlayBilling`` API:
  14. 1. Access the ``BillingClient`` autoload singleton, it's automatically added when the plugin is enabled.
  15. 2. Connect to its signals to receive billing results.
  16. 3. Call ``start_connection``.
  17. Initialization example:
  18. ::
  19. func _ready():
  20. BillingClient.connected.connect(_on_connected) # No params
  21. BillingClient.disconnected.connect(_on_disconnected) # No params
  22. BillingClient.connect_error.connect(_on_connect_error) # response_code: int, debug_message: String
  23. BillingClient.query_product_details_response.connect(_on_query_product_details_response) # response: Dictionary
  24. BillingClient.query_purchases_response.connect(_on_query_purchases_response) # response: Dictionary
  25. BillingClient.on_purchase_updated.connect(_on_purchase_updated) # response: Dictionary
  26. BillingClient.consume_purchase_response.connect(_on_consume_purchase_response) # response: Dictionary
  27. BillingClient.acknowledge_purchase_response.connect(_on_acknowledge_purchase_response) # response: Dictionary
  28. BillingClient.start_connection()
  29. The API must be in a connected state prior to use. The ``connected`` signal is sent
  30. when the connection process succeeds. You can also use ``is_ready()`` to determine if the plugin
  31. is ready for use. The ``get_connection_state()`` function returns the current connection state
  32. of the plugin.
  33. Return values for ``get_connection_state()``:
  34. ::
  35. # Matches BillingClient.ConnectionState in the Play Billing Library.
  36. # Access in your script as: BillingClient.ConnectionState.CONNECTED
  37. enum ConnectionState {
  38. DISCONNECTED, # This client was not yet connected to billing service or was already closed.
  39. CONNECTING, # This client is currently in process of connecting to billing service.
  40. CONNECTED, # This client is currently connected to billing service.
  41. CLOSED, # This client was already closed and shouldn't be used again.
  42. }
  43. Query available items
  44. ~~~~~~~~~~~~~~~~~~~~~
  45. Once the API has connected, query product IDs using `query_product_details()`. You must successfully complete
  46. a product details query before calling the ``purchase()``, ``purchase_subscription()``, or ``update_subscription()`` functions,
  47. or they will return an error. ``query_product_details()`` takes two parameters: an array
  48. of product ID strings and the type of product being queried.
  49. The product type should be ``BillingClient.ProductType.INAPP`` for normal in-app purchases or ``BillingClient.ProductType.SUBS`` for subscriptions.
  50. The ID strings in the array should match the product IDs defined in the Google Play Console entry
  51. for your app.
  52. Example use of ``query_product_details()``:
  53. ::
  54. func _on_connected():
  55. BillingClient.query_product_details(["my_iap_item"], BillingClient.ProductType.INAPP) # BillingClient.ProductType.SUBS for subscriptions.
  56. func _on_query_product_details_response(query_result: Dictionary):
  57. if query_result.response_code == BillingClient.BillingResponseCode.OK:
  58. print("Product details query success")
  59. for available_product in query_result.result_array:
  60. print(available_product)
  61. else:
  62. print("Product details query failed")
  63. print("response_code: ", query_result.response_code, "debug_message: ", query_result.debug_message)
  64. Query user purchases
  65. ~~~~~~~~~~~~~~~~~~~~
  66. To retrieve a user's purchases, call the ``query_purchases()`` function passing
  67. a product type to query. The product type should be
  68. ``BillingClient.ProductType.INAPP`` for normal in-app purchases or ``BillingClient.ProductType.SUBS`` for subscriptions.
  69. The ``query_purchases_response`` signal is sent with the result.
  70. The signal has a single parameter: a :ref:`Dictionary <class_Dictionary>` with
  71. a response code and either an array of purchases or a debug message.
  72. Only active subscriptions and non-consumed one-time purchases are
  73. included in the purchase array.
  74. Example use of ``query_purchases()``:
  75. ::
  76. func _query_purchases():
  77. BillingClient.query_purchases(BillingClient.ProductType.INAPP) # Or BillingClient.ProductType.SUBS for subscriptions.
  78. func _on_query_purchases_response(query_result: Dictionary):
  79. if query_result.response_code == BillingClient.BillingResponseCode.OK:
  80. print("Purchase query success")
  81. for purchase in query_result.result_array:
  82. _process_purchase(purchase)
  83. else:
  84. print("Purchase query failed")
  85. print("response_code: ", query_result.response_code, "debug_message: ", query_result.debug_message)
  86. Purchase an item
  87. ~~~~~~~~~~~~~~~~
  88. To launch the billing flow for an item:
  89. - Use ``purchase()`` for in-app products, passing the product ID string.
  90. - Use ``purchase_subscription()`` for subscriptions, passing the product ID and base plan ID. You may also optionally provide an offer ID.
  91. For both ``purchase()`` and ``purchase_subscription()``, you can optionally pass a boolean to indicate whether
  92. offers are `personallised <https://developer.android.com/google/play/billing/integrate#personalized-price>`_
  93. Reminder: you **must** query the product details for an item before you can
  94. pass it to ``purchase()``.
  95. This method returns a dictionary indicating whether the billing flow was successfully launched.
  96. It includes a response code and either an array of purchases or a debug message.
  97. Example use of ``purchase()``:
  98. ::
  99. var result = BillingClient.purchase("my_iap_item")
  100. if result.response_code == BillingClient.BillingResponseCode.OK:
  101. print("Billing flow launch success")
  102. else:
  103. print("Billing flow launch failed")
  104. print("response_code: ", result.response_code, "debug_message: ", result.debug_message)
  105. The result of the purchase will be sent through the ``on_purchases_updated`` signal.
  106. ::
  107. func _on_purchases_updated(result: Dictionary):
  108. if result.response_code == BillingClient.BillingResponseCode.OK:
  109. print("Purchase update received")
  110. for purchase in result.result_array:
  111. _process_purchase(purchase)
  112. else:
  113. print("Purchase update error")
  114. print("response_code: ", result.response_code, "debug_message: ", result.debug_message)
  115. Processing a purchase item
  116. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  117. The ``query_purchases_response`` and ``on_purchases_updated`` signals provide an array
  118. of purchases in :ref:`Dictionary <class_Dictionary>` format. The purchase Dictionary
  119. includes keys that map to values of the Google Play Billing
  120. `Purchase <https://developer.android.com/reference/com/android/billingclient/api/Purchase>`_ class.
  121. Purchase fields:
  122. ::
  123. order_id: String
  124. purchase_token: String
  125. package_name: String
  126. purchase_state: int
  127. purchase_time: int (milliseconds since the epoch (Jan 1, 1970))
  128. original_json: String
  129. is_acknowledged: bool
  130. is_auto_renewing: bool
  131. quantity: int
  132. signature: String
  133. product_ids: PackedStringArray
  134. Check purchase state
  135. ~~~~~~~~~~~~~~~~~~~~
  136. Check the ``purchase_state`` value of a purchase to determine if a
  137. purchase was completed or is still pending.
  138. PurchaseState values:
  139. ::
  140. # Matches Purchase.PurchaseState in the Play Billing Library
  141. # Access in your script as: BillingClient.PurchaseState.PURCHASED
  142. enum PurchaseState {
  143. UNSPECIFIED,
  144. PURCHASED,
  145. PENDING,
  146. }
  147. If a purchase is in a ``PENDING`` state, you should not award the contents of the
  148. purchase or do any further processing of the purchase until it reaches the
  149. ``PURCHASED`` state. If you have a store interface, you may wish to display
  150. information about pending purchases needing to be completed in the Google Play Store.
  151. For more details on pending purchases, see
  152. `Handling pending transactions <https://developer.android.com/google/play/billing/integrate#pending>`_
  153. in the Google Play Billing Library documentation.
  154. Consumables
  155. ~~~~~~~~~~~
  156. If your in-app item is not a one-time purchase but a consumable item (e.g. coins) which can be purchased
  157. multiple times, you can consume an item by calling ``consume_purchase()`` passing
  158. the ``purchase_token`` value from the purchase dictionary.
  159. Calling ``consume_purchase()`` automatically acknowledges a purchase.
  160. Consuming a product allows the user to purchase it again, it will no longer appear
  161. in subsequent ``query_purchases()`` calls unless it is repurchased.
  162. Example use of ``consume_purchase()``:
  163. ::
  164. func _process_purchase(purchase):
  165. if "my_consumable_iap_item" in purchase.product_ids and purchase.purchase_state == BillingClient.PurchaseState.PURCHASED:
  166. # Add code to store payment so we can reconcile the purchase token
  167. # in the completion callback against the original purchase
  168. BillingClient.consume_purchase(purchase.purchase_token)
  169. func _on_consume_purchase_response(result: Dictionary):
  170. if result.response_code == BillingClient.BillingResponseCode.OK:
  171. print("Consume purchase success")
  172. _handle_purchase_token(result.token, true)
  173. else:
  174. print("Consume purchase failed")
  175. print("response_code: ", result.response_code, "debug_message: ", result.debug_message, "purchase_token: ", result.token)
  176. # Find the product associated with the purchase token and award the
  177. # product if successful
  178. func _handle_purchase_token(purchase_token, purchase_successful):
  179. # check/award logic, remove purchase from tracking list
  180. Acknowledging purchases
  181. ~~~~~~~~~~~~~~~~~~~~~~~
  182. If your in-app item is a one-time purchase, you must acknowledge the purchase by
  183. calling the ``acknowledge_purchase()`` function, passing the ``purchase_token``
  184. value from the purchase dictionary. If you do not acknowledge a purchase within
  185. three days, the user automatically receives a refund, and Google Play revokes the purchase.
  186. If you are calling ``comsume_purchase()`` it automatically acknowledges the purchase and
  187. you do not need to call ``acknowledge_purchase()``.
  188. Example use of ``acknowledge_purchase()``:
  189. ::
  190. func _process_purchase(purchase):
  191. if "my_one_time_iap_item" in purchase.product_ids and \
  192. purchase.purchase_state == BillingClient.PurchaseState.PURCHASED and \
  193. not purchase.is_acknowledged:
  194. # Add code to store payment so we can reconcile the purchase token
  195. # in the completion callback against the original purchase
  196. BillingClient.acknowledge_purchase(purchase.purchase_token)
  197. func _on_acknowledge_purchase_response(result: Dictionary):
  198. if result.response_code == BillingClient.BillingResponseCode.OK:
  199. print("Acknowledge purchase success")
  200. _handle_purchase_token(result.token, true)
  201. else:
  202. print("Acknowledge purchase failed")
  203. print("response_code: ", result.response_code, "debug_message: ", result.debug_message, "purchase_token: ", result.token)
  204. # Find the product associated with the purchase token and award the
  205. # product if successful
  206. func _handle_purchase_token(purchase_token, purchase_successful):
  207. # check/award logic, remove purchase from tracking list
  208. Subscriptions
  209. ~~~~~~~~~~~~~
  210. Subscriptions work mostly like regular in-app items. Use ``BillingClient.ProductType.SUBS`` as the second
  211. argument to ``query_product_details()`` to get subscription details. Pass ``BillingClient.ProductType.SUBS``
  212. to ``query_purchases()`` to get subscription purchase details.
  213. You can check ``is_auto_renewing`` in the a subscription purchase
  214. returned from ``query_purchases()`` to see if a user has cancelled an
  215. auto-renewing subscription.
  216. You need to acknowledge new subscription purchases, but not automatic
  217. subscription renewals.
  218. If you support upgrading or downgrading between different subscription levels,
  219. you should use ``update_subscription()`` to use the subscription update flow to
  220. change an active subscription. Like ``purchase()``, results are returned by the
  221. ``on_purchases_updated`` signal.
  222. These are the parameters of ``update_subscription()``:
  223. 1. old_purchase_token: The purchase token of the currently active subscription
  224. 2. replacement_mode: The replacement mode to apply to the subscription
  225. 3. product_id: The product ID of the new subscription to switch to
  226. 4. base_plan_id: The base plan ID of the target subscription
  227. 5. offer_id: The offer ID under the base plan (optional)
  228. 6. is_offer_personalized: Whether to enable personalized pricing (optional)
  229. The replacement modes values are defined as:
  230. ::
  231. # Access in your script as: BillingClient.ReplacementMode.WITH_TIME_PRORATION
  232. enum ReplacementMode {
  233. # Unknown...
  234. UNKNOWN_REPLACEMENT_MODE = 0,
  235. # The new plan takes effect immediately, and the remaining time will be prorated and credited to the user.
  236. # Note: This is the default behavior.
  237. WITH_TIME_PRORATION = 1,
  238. # The new plan takes effect immediately, and the billing cycle remains the same.
  239. CHARGE_PRORATED_PRICE = 2,
  240. # The new plan takes effect immediately, and the new price will be charged on next recurrence time.
  241. WITHOUT_PRORATION = 3,
  242. # Replacement takes effect immediately, and the user is charged full price of new plan and
  243. # is given a full billing cycle of subscription, plus remaining prorated time from the old plan.
  244. CHARGE_FULL_PRICE = 5,
  245. # The new purchase takes effect immediately, the new plan will take effect when the old item expires.
  246. DEFERRED = 6,
  247. }
  248. Default behavior is ``WITH_TIME_PRORATION``.
  249. Example use of ``update_subscription``:
  250. ::
  251. BillingClient.update_subscription(_active_subscription_purchase.purchase_token, \
  252. BillingClient.ReplacementMode.WITH_TIME_PRORATION, "new_sub_product_id", "base_plan_id")