Android 应用内购买

Godot offers a first-party GodotGooglePlayBilling Android plugin compatible with Godot 4 which uses the Google Play Billing library.

用法

入门

Make sure you have enabled and successfully set up Android Gradle Builds. Follow the compiling instructions on the GodotGooglePlayBilling github page.

Then put the files ./godot-google-play-billing/build/outputs/aar/GodotGooglePlayBilling.***.release.aar and ./GodotGooglePlayBilling.gdap into your project in the res://android/plugins folder.

The plugin should now show up in the Android export settings, where you can enable it.

Initialize the plugin

To use the GodotGooglePlayBilling API:

  1. Obtain a reference to the GodotGooglePlayBilling singleton

  2. Connect handlers for the plugin signals

  3. Call startConnection

最小连接示例:

  1. var payment
  2. func _ready():
  3. if Engine.has_singleton("GodotGooglePlayBilling"):
  4. payment = Engine.get_singleton("GodotGooglePlayBilling")
  5. # These are all signals supported by the API
  6. # You can drop some of these based on your needs
  7. payment.billing_resume.connect(_on_billing_resume) # No params
  8. payment.connected.connect(_on_connected) # No params
  9. payment.disconnected.connect(_on_disconnected) # No params
  10. payment.connect_error.connect(_on_connect_error) # Response ID (int), Debug message (string)
  11. payment.price_change_acknowledged.connect(_on_price_acknowledged) # Response ID (int)
  12. payment.purchases_updated.connect(_on_purchases_updated) # Purchases (Dictionary[])
  13. payment.purchase_error.connect(_on_purchase_error) # Response ID (int), Debug message (string)
  14. payment.sku_details_query_completed.connect(_on_product_details_query_completed) # Products (Dictionary[])
  15. payment.sku_details_query_error.connect(_on_product_details_query_error) # Response ID (int), Debug message (string), Queried SKUs (string[])
  16. payment.purchase_acknowledged.connect(_on_purchase_acknowledged) # Purchase token (string)
  17. payment.purchase_acknowledgement_error.connect(_on_purchase_acknowledgement_error) # Response ID (int), Debug message (string), Purchase token (string)
  18. payment.purchase_consumed.connect(_on_purchase_consumed) # Purchase token (string)
  19. payment.purchase_consumption_error.connect(_on_purchase_consumption_error) # Response ID (int), Debug message (string), Purchase token (string)
  20. payment.query_purchases_response.connect(_on_query_purchases_response) # Purchases (Dictionary[])
  21. payment.startConnection()
  22. else:
  23. print("Android IAP support is not enabled. Make sure you have enabled 'Gradle Build' and the GodotGooglePlayBilling plugin in your Android export settings! IAP will not work.")

The API must be in a connected state prior to use. The connected signal is sent when the connection process succeeds. You can also use isReady() to determine if the plugin is ready for use. The getConnectionState() function returns the current connection state of the plugin.

Return values for getConnectionState():

  1. # Matches BillingClient.ConnectionState in the Play Billing Library
  2. enum ConnectionState {
  3. DISCONNECTED, # not yet connected to billing service or was already closed
  4. CONNECTING, # currently in process of connecting to billing service
  5. CONNECTED, # currently connected to billing service
  6. CLOSED, # already closed and shouldn't be used again
  7. }

Query available items

Once the API has connected, query SKUs using querySkuDetails(). You must successfully complete an SKU query before calling the purchase() or queryPurchases() functions, or they will return an error. querySkuDetails() takes two parameters: an array of SKU name strings, and a string specifying the type of SKU being queried. The SKU type string should be "inapp" for normal in-app purchases or "subs" for subscriptions. The name strings in the array should match the SKU product ids defined in the Google Play Console entry for your app.

querySkuDetails() 的示例用法:

  1. func _on_connected():
  2. payment.querySkuDetails(["my_iap_item"], "inapp") # "subs" for subscriptions
  3. func _on_product_details_query_completed(product_details):
  4. for available_product in product_details:
  5. print(available_product)
  6. func _on_product_details_query_error(response_id, error_message, products_queried):
  7. print("on_product_details_query_error id:", response_id, " message: ",
  8. error_message, " products: ", products_queried)

查询用户购买记录

To retrieve a user’s purchases, call the queryPurchases() function passing a string with the type of SKU to query. The SKU type string should be "inapp" for normal in-app purchases or "subs" for subscriptions. The query_purchases_response signal is sent with the result. The signal has a single parameter: a Dictionary with a status code and either an array of purchases or an error message. Only active subscriptions and non-consumed one-time purchases are included in the purchase array.

queryPurchases() 的示例用法:

  1. func _query_purchases():
  2. payment.queryPurchases("inapp") # Or "subs" for subscriptions
  3. func _on_query_purchases_response(query_result):
  4. if query_result.status == OK:
  5. for purchase in query_result.purchases:
  6. _process_purchase(purchase)
  7. else:
  8. print("queryPurchases failed, response code: ",
  9. query_result.response_code,
  10. " debug message: ", query_result.debug_message)

You should query purchases during startup after successfully retrieving SKU details. Since the user may make a purchase or resolve a pending transaction from outside your app, you should recheck for purchases when resuming from the background. To accomplish this, you can use the billing_resume signal.

billing_resume 的示例用法:

  1. func _on_billing_resume():
  2. if payment.getConnectionState() == ConnectionState.CONNECTED:
  3. _query_purchases()

For more information on processing the purchase items returned by queryPurchases(), see Processing a purchase item

购买项目

To initiate the purchase flow for an item, call purchase() passing the product id string of the SKU you wish to purchase. Reminder: you must query the SKU details for an item before you can pass it to purchase().

purchase() 的示例用法:

  1. payment.purchase("my_iap_item")

The payment flow will send a purchases_updated signal on success or a purchase_error signal on failure.

  1. func _on_purchases_updated(purchases):
  2. for purchase in purchases:
  3. _process_purchase(purchase)
  4. func _on_purchase_error(response_id, error_message):
  5. print("purchase_error id:", response_id, " message: ", error_message)

处理购买项目

The query_purchases_response and purchases_updated signals provide an array of purchases in Dictionary format. The purchase Dictionary includes keys that map to values of the Google Play Billing Purchase class.

购买项目:

  1. dictionary.put("order_id", purchase.getOrderId());
  2. dictionary.put("package_name", purchase.getPackageName());
  3. dictionary.put("purchase_state", purchase.getPurchaseState());
  4. dictionary.put("purchase_time", purchase.getPurchaseTime());
  5. dictionary.put("purchase_token", purchase.getPurchaseToken());
  6. dictionary.put("quantity", purchase.getQuantity());
  7. dictionary.put("signature", purchase.getSignature());
  8. // PBL V4 replaced getSku with getSkus to support multi-sku purchases,
  9. // use the first entry for "sku" and generate an array for "skus"
  10. ArrayList<String> skus = purchase.getSkus();
  11. dictionary.put("sku", skus.get(0)); # Not available in plugin
  12. String[] skusArray = skus.toArray(new String[0]);
  13. dictionary.put("products", productsArray);
  14. dictionary.put("is_acknowledged", purchase.isAcknowledged());
  15. dictionary.put("is_auto_renewing", purchase.isAutoRenewing());

检查购买状态

Check the purchase_state value of a purchase to determine if a purchase was completed or is still pending.

PurchaseState 取值:

  1. # Matches Purchase.PurchaseState in the Play Billing Library
  2. enum PurchaseState {
  3. UNSPECIFIED,
  4. PURCHASED,
  5. PENDING,
  6. }

If a purchase is in a PENDING state, you should not award the contents of the purchase or do any further processing of the purchase until it reaches the PURCHASED state. If you have a store interface, you may wish to display information about pending purchases needing to be completed in the Google Play Store. For more details on pending purchases, see Handling pending transactions in the Google Play Billing Library documentation.

消耗品

If your in-app item is not a one-time purchase but a consumable item (e.g. coins) which can be purchased multiple times, you can consume an item by calling consumePurchase() passing the purchase_token value from the purchase dictionary. Calling consumePurchase() automatically acknowledges a purchase. Consuming a product allows the user to purchase it again, it will no longer appear in subsequent queryPurchases() calls unless it is repurchased.

consumePurchase() 的示例用法:

  1. func _process_purchase(purchase):
  2. if "my_consumable_iap_item" in purchase.products and purchase.purchase_state == PurchaseState.PURCHASED:
  3. # Add code to store payment so we can reconcile the purchase token
  4. # in the completion callback against the original purchase
  5. payment.consumePurchase(purchase.purchase_token)
  6. func _on_purchase_consumed(purchase_token):
  7. _handle_purchase_token(purchase_token, true)
  8. func _on_purchase_consumption_error(response_id, error_message, purchase_token):
  9. print("_on_purchase_consumption_error id:", response_id,
  10. " message: ", error_message)
  11. _handle_purchase_token(purchase_token, false)
  12. # Find the sku associated with the purchase token and award the
  13. # product if successful
  14. func _handle_purchase_token(purchase_token, purchase_successful):
  15. # check/award logic, remove purchase from tracking list

确认购买

If your in-app item is a one-time purchase, you must acknowledge the purchase by calling the acknowledgePurchase() function, passing the purchase_token value from the purchase dictionary. If you do not acknowledge a purchase within three days, the user automatically receives a refund, and Google Play revokes the purchase. If you are calling comsumePurchase() it automatically acknowledges the purchase and you do not need to call acknowledgePurchase().

acknowledgePurchase() 的示例用法:

  1. func _process_purchase(purchase):
  2. if "my_one_time_iap_item" in purchase.products and \
  3. purchase.purchase_state == PurchaseState.PURCHASED and \
  4. not purchase.is_acknowledged:
  5. # Add code to store payment so we can reconcile the purchase token
  6. # in the completion callback against the original purchase
  7. payment.acknowledgePurchase(purchase.purchase_token)
  8. func _on_purchase_acknowledged(purchase_token):
  9. _handle_purchase_token(purchase_token, true)
  10. func _on_purchase_acknowledgement_error(response_id, error_message, purchase_token):
  11. print("_on_purchase_acknowledgement_error id: ", response_id,
  12. " message: ", error_message)
  13. _handle_purchase_token(purchase_token, false)
  14. # Find the sku associated with the purchase token and award the
  15. # product if successful
  16. func _handle_purchase_token(purchase_token, purchase_successful):
  17. # check/award logic, remove purchase from tracking list

订阅

订阅的工作原理和普通的应用内项目没有太大区别. 只要使用 "subs" 作为 querySkuDetails() 的第二个参数, 就可以得到订阅的详细信息. 在 queryPurchases() 的结果中检查 is_auto_renewing 来查看用户是否取消了自动更新的订阅。

You can check is_auto_renewing in the a subscription purchase returned from queryPurchases() to see if a user has cancelled an auto-renewing subscription.

You need to acknowledge new subscription purchases, but not automatic subscription renewals.

If you support upgrading or downgrading between different subscription levels, you should use updateSubscription() to use the subscription update flow to change an active subscription. Like purchase(), results are returned by the purchases_updated and purchase_error signals. There are three parameters to updateSubscription():

  1. The purchase token of the currently active subscription

  2. The product id string of the subscription SKU to change to

  3. The proration mode to apply to the subscription.

The proration values are defined as:

  1. enum SubscriptionProrationMode {
  2. # Replacement takes effect immediately, and the remaining time
  3. # will be prorated and credited to the user.
  4. IMMEDIATE_WITH_TIME_PRORATION = 1,
  5. # Replacement takes effect immediately, and the billing cycle remains the same.
  6. # The price for the remaining period will be charged.
  7. # This option is only available for subscription upgrade.
  8. IMMEDIATE_AND_CHARGE_PRORATED_PRICE,
  9. # Replacement takes effect immediately, and the new price will be charged on
  10. # next recurrence time. The billing cycle stays the same.
  11. IMMEDIATE_WITHOUT_PRORATION,
  12. # Replacement takes effect when the old plan expires, and the new price
  13. # will be charged at the same time.
  14. DEFERRED,
  15. # Replacement takes effect immediately, and the user is charged full price
  16. # of new plan and is given a full billing cycle of subscription,
  17. # plus remaining prorated time from the old plan.
  18. IMMEDIATE_AND_CHARGE_FULL_PRICE,
  19. }

Default behavior is IMMEDIATE_WITH_TIME_PRORATION.

Example use of updateSubscription:

  1. payment.updateSubscription(_active_subscription_purchase.purchase_token, \
  2. "new_sub_sku", SubscriptionProrationMode.IMMEDIATE_WITH_TIME_PRORATION)

The confirmPriceChange() function can be used to launch price change confirmation flow for a subscription. Pass the product id of the subscription SKU subject to the price change. The result will be sent by the price_change_acknowledged signal.

Example use of confirmPriceChange():

  1. enum BillingResponse {SUCCESS = 0, CANCELLED = 1}
  2. func confirm_price_change(product_id):
  3. payment.confirmPriceChange(product_id)
  4. func _on_price_acknowledged(response_id):
  5. if response_id == BillingResponse.SUCCESS:
  6. print("price_change_accepted")
  7. elif response_id == BillingResponse.CANCELED:
  8. print("price_change_canceled")