21 Commits
3.1.0 ... 4.0.0

Author SHA1 Message Date
Björn Ritzl
40648f4773 Merge pull request #52 from defold/Issue-51-update-billing-library-to-version-5
Updated the Android billing library to version 5
2022-09-08 10:32:27 +02:00
Björn Ritzl
3d3433e07f Update iap.script_api 2022-09-08 10:32:04 +02:00
Björn Ritzl
52493d8c83 Improved API docs. Recurrence mode 2022-09-08 10:06:10 +02:00
Björn Ritzl
c09aa64ab5 Added title and description 2022-09-08 09:51:39 +02:00
Björn Ritzl
d0ca1e05fd Update iap.script_api 2022-09-08 09:51:28 +02:00
Björn Ritzl
05e9001404 Fixed issues with subscriptions 2022-09-07 11:58:19 +02:00
Björn Ritzl
a26bb45791 Initial update 2022-09-06 23:59:27 +02:00
Björn Ritzl
0a10ff0878 Merge pull request #49 from dapetcu21/master
Fix bundling for Android 12 SDK
2022-05-02 15:03:34 +02:00
Marius Petcu
508a4f8681 Keep a single property indentation style 2022-05-02 15:30:38 +03:00
Marius Petcu
5e1738d353 Fix bundling on Android 12
Bundling fails because the `<receiver>` tag needs `android:exported="true"`.
2022-05-02 15:28:44 +03:00
Alexey Gulev
df7f05c1a6 Merge pull request #48 from defold/fix/mutex-scope
Smaller mutex scope + use new SDK android methods (Defold 1.2.188)
2021-10-31 22:01:05 +01:00
Alexey Gulev
3ecd6ef587 Smaller mutex scope + use new SDK android methods (Defold 1.2.188) 2021-10-31 13:22:18 +01:00
JCash
92d90bb4de Fixed nul pointer deferencing 2021-10-06 09:55:49 +02:00
Björn Ritzl
e6e2f2de63 Update iap.script_api 2021-09-09 13:26:08 +02:00
Björn Ritzl
3468b52658 Merge pull request #41 from BigButtonCo/master
Add original_json to transaction for validating purchases on android
2021-09-09 13:23:13 +02:00
Mathias Westerdahl
bda785ef08 Merge pull request #44 from defold/buffer-threading-fix
Fixed threading issue of checking if command buffer is empty
2021-09-07 14:34:35 +02:00
JCash
b3b79006d7 Fixed threading issue of checking if command buffer is empty 2021-08-02 10:10:00 +02:00
Björn Ritzl
8b2c7b0bca Removed old Amazon SDK version 2021-07-22 19:58:18 +02:00
BigButtonCo
1a6d2f01e5 Merge branch 'defold:master' into master 2021-06-03 20:05:02 +02:00
BigButtonCo
276437b981 Update IapGooglePlay.java 2021-04-12 19:26:56 +02:00
BigButtonCo
246fcd3179 Added original_json 2021-04-12 19:22:33 +02:00
11 changed files with 280 additions and 151 deletions

View File

@@ -23,6 +23,10 @@
type: string
desc: Facebook only. [icon:facebook] Optional custom unique request id to
set for this transaction. The id becomes attached to the payment within the Graph API.
- name: token
type: string
desc: [icon:googleplay] Which subscription offer to use when buying a subscription. The token can be retrieved from
the subscriptions table returned when calling iap.list()
examples:
- desc: |-
@@ -128,15 +132,56 @@
- name: price
type: number
desc: The price of the product.
[icon:googleplay]: Used only for in-app products
- name: price_string
type: string
desc: The price of the product, as a formatted string (amount and currency symbol).
[icon:googleplay]: Used only for in-app products
- name: currency_code
type: string
desc: The currency code. On Google Play, this reflects the merchant's locale, instead of the user's.
[icon:ios] [icon:googleplay] [icon:facebook]
desc: [icon:ios] [icon:googleplay] [icon:facebook] The currency code.
[icon:googleplay]: The merchant's locale, instead of the user's
[icon:googleplay]: Used only for in-app products
- name: subscriptions
type: table
desc: [icon:googleplay] List of subscription offers.
Each offer contains a token and a list of price and billing options.
See https://developer.android.com/reference/com/android/billingclient/api/ProductDetails.PricingPhase
members:
- name: token
type: string
desc: The token associated with the pricing phases for the subscription.
- name: pricing
type: table
desc: The pricing phases for the subscription.
members:
- name: price_string
type: string
desc: Formatted price for the payment cycle, including currency sign.
- name: price
type: number
desc: Price of the payment cycle in micro-units.
- name: currency_code
type: string
desc: ISO 4217 currency code
- name: billing_period
type: string
desc: Billing period of the payment cycle, specified in ISO 8601 format
- name: billing_cycle_count
type: number
desc: Number of cycles for which the billing period is applied.
- name: recurrence_mode
type: string
desc: FINITE, INFINITE or NONE
- name: error
type: table
@@ -226,6 +271,10 @@
type: string
desc: Apple only[icon:apple]. The original transaction. This field is only set when `state` is `TRANS_STATE_RESTORED`.
- name: original_json
type: string
desc: Android only[icon:android]. The purchase order details in JSON format.
- name: signature
type: string
desc: Google Play only[icon:googleplay]. A string containing the signature of the purchase data that was signed with the private key of the developer.

View File

@@ -4,9 +4,9 @@
<uses-sdk android:minSdkVersion="{{android.minimum_sdk_version}}" android:targetSdkVersion="{{android.target_sdk_version}}" />
<application>
<!-- For Amazon IAP -->
<receiver android:name = "com.amazon.device.iap.ResponseReceiver" android:permission = "com.amazon.inapp.purchasing.Permission.NOTIFY" >
<receiver android:exported="true" android:name="com.amazon.device.iap.ResponseReceiver" android:permission="com.amazon.inapp.purchasing.Permission.NOTIFY">
<intent-filter>
<action android:name = "com.amazon.inapp.purchasing.NOTIFY" />
<action android:name="com.amazon.inapp.purchasing.NOTIFY" />
</intent-filter>
</receiver>
</application>

View File

@@ -1,3 +1,3 @@
dependencies {
implementation 'com.android.billingclient:billing:3.0.0'
implementation 'com.android.billingclient:billing:5.0.0'
}

View File

@@ -1,7 +1,8 @@
#if defined(DM_PLATFORM_ANDROID)
#include <dmsdk/sdk.h>
#include <jni.h>
#include <dmsdk/dlib/android.h>
#include <stdlib.h>
#include <unistd.h>
#include "iap.h"
@@ -9,19 +10,6 @@
#define LIB_NAME "iap"
static JNIEnv* Attach()
{
JNIEnv* env;
dmGraphics::GetNativeAndroidJavaVM()->AttachCurrentThread(&env, NULL);
return env;
}
static void Detach()
{
dmGraphics::GetNativeAndroidJavaVM()->DetachCurrentThread();
}
struct IAP
{
IAP()
@@ -52,24 +40,27 @@ static IAP g_IAP;
static int IAP_ProcessPendingTransactions(lua_State* L)
{
JNIEnv* env = Attach();
DM_LUA_STACK_CHECK(L, 0);
dmAndroid::ThreadAttacher threadAttacher;
JNIEnv* env = threadAttacher.GetEnv();
env->CallVoidMethod(g_IAP.m_IAP, g_IAP.m_ProcessPendingConsumables, g_IAP.m_IAPJNI);
Detach();
return 0;
}
static int IAP_List(lua_State* L)
{
int top = lua_gettop(L);
DM_LUA_STACK_CHECK(L, 0);
char* buf = IAP_List_CreateBuffer(L);
if( buf == 0 )
{
assert(top == lua_gettop(L));
return 0;
}
JNIEnv* env = Attach();
dmAndroid::ThreadAttacher threadAttacher;
JNIEnv* env = threadAttacher.GetEnv();
IAPCommand* cmd = new IAPCommand;
cmd->m_Callback = dmScript::CreateCallback(L, 2);
cmd->m_Command = IAP_PRODUCT_RESULT;
@@ -77,39 +68,48 @@ static int IAP_List(lua_State* L)
jstring products = env->NewStringUTF(buf);
env->CallVoidMethod(g_IAP.m_IAP, g_IAP.m_List, products, g_IAP.m_IAPJNI, (jlong)cmd);
env->DeleteLocalRef(products);
Detach();
free(buf);
assert(top == lua_gettop(L));
return 0;
}
static int IAP_Buy(lua_State* L)
{
DM_LUA_STACK_CHECK(L, 0);
int top = lua_gettop(L);
const char* id = luaL_checkstring(L, 1);
const char* token = "";
JNIEnv* env = Attach();
if (top >= 2 && lua_istable(L, 2)) {
luaL_checktype(L, 2, LUA_TTABLE);
lua_pushvalue(L, 2);
lua_getfield(L, -1, "token");
token = lua_isnil(L, -1) ? "" : luaL_checkstring(L, -1);
lua_pop(L, 2);
}
dmAndroid::ThreadAttacher threadAttacher;
JNIEnv* env = threadAttacher.GetEnv();
jstring ids = env->NewStringUTF(id);
env->CallVoidMethod(g_IAP.m_IAP, g_IAP.m_Buy, ids, g_IAP.m_IAPJNI);
jstring tokens = env->NewStringUTF(token);
env->CallVoidMethod(g_IAP.m_IAP, g_IAP.m_Buy, ids, tokens, g_IAP.m_IAPJNI);
env->DeleteLocalRef(ids);
Detach();
env->DeleteLocalRef(tokens);
assert(top == lua_gettop(L));
return 0;
}
static int IAP_Finish(lua_State* L)
{
DM_LUA_STACK_CHECK(L, 0);
if(g_IAP.m_autoFinishTransactions)
{
dmLogWarning("Calling iap.finish when autofinish transactions is enabled. Ignored.");
return 0;
}
int top = lua_gettop(L);
luaL_checktype(L, 1, LUA_TTABLE);
lua_getfield(L, -1, "state");
@@ -119,7 +119,6 @@ static int IAP_Finish(lua_State* L)
{
dmLogError("Invalid transaction state (must be iap.TRANS_STATE_PURCHASED).");
lua_pop(L, 1);
assert(top == lua_gettop(L));
return 0;
}
}
@@ -135,20 +134,19 @@ static int IAP_Finish(lua_State* L)
const char * receipt = lua_tostring(L, -1);
lua_pop(L, 1);
JNIEnv* env = Attach();
dmAndroid::ThreadAttacher threadAttacher;
JNIEnv* env = threadAttacher.GetEnv();
jstring receiptUTF = env->NewStringUTF(receipt);
env->CallVoidMethod(g_IAP.m_IAP, g_IAP.m_FinishTransaction, receiptUTF, g_IAP.m_IAPJNI);
env->DeleteLocalRef(receiptUTF);
Detach();
}
assert(top == lua_gettop(L));
return 0;
}
static int IAP_Acknowledge(lua_State* L)
{
int top = lua_gettop(L);
DM_LUA_STACK_CHECK(L, 0);
luaL_checktype(L, 1, LUA_TTABLE);
@@ -159,7 +157,6 @@ static int IAP_Acknowledge(lua_State* L)
{
dmLogError("Invalid transaction state (must be iap.TRANS_STATE_PURCHASED).");
lua_pop(L, 1);
assert(top == lua_gettop(L));
return 0;
}
}
@@ -175,14 +172,13 @@ static int IAP_Acknowledge(lua_State* L)
const char * receipt = lua_tostring(L, -1);
lua_pop(L, 1);
JNIEnv* env = Attach();
dmAndroid::ThreadAttacher threadAttacher;
JNIEnv* env = threadAttacher.GetEnv();
jstring receiptUTF = env->NewStringUTF(receipt);
env->CallVoidMethod(g_IAP.m_IAP, g_IAP.m_AcknowledgeTransaction, receiptUTF, g_IAP.m_IAPJNI);
env->DeleteLocalRef(receiptUTF);
Detach();
}
assert(top == lua_gettop(L));
return 0;
}
@@ -190,13 +186,11 @@ static int IAP_Restore(lua_State* L)
{
// TODO: Missing callback here for completion/error
// See iap_ios.mm
DM_LUA_STACK_CHECK(L, 1);
int top = lua_gettop(L);
JNIEnv* env = Attach();
dmAndroid::ThreadAttacher threadAttacher;
JNIEnv* env = threadAttacher.GetEnv();
env->CallVoidMethod(g_IAP.m_IAP, g_IAP.m_Restore, g_IAP.m_IAPJNI);
Detach();
assert(top == lua_gettop(L));
lua_pushboolean(L, 1);
return 1;
@@ -204,6 +198,8 @@ static int IAP_Restore(lua_State* L)
static int IAP_SetListener(lua_State* L)
{
DM_LUA_STACK_CHECK(L, 0);
IAP* iap = &g_IAP;
bool had_previous = iap->m_Listener != 0;
@@ -215,15 +211,17 @@ static int IAP_SetListener(lua_State* L)
// On first set listener, trigger process old ones.
if (!had_previous) {
JNIEnv* env = Attach();
dmAndroid::ThreadAttacher threadAttacher;
JNIEnv* env = threadAttacher.GetEnv();
env->CallVoidMethod(g_IAP.m_IAP, g_IAP.m_ProcessPendingConsumables, g_IAP.m_IAPJNI);
Detach();
}
return 0;
}
static int IAP_GetProviderId(lua_State* L)
{
DM_LUA_STACK_CHECK(L, 1);
lua_pushinteger(L, g_IAP.m_ProviderId);
return 1;
}
@@ -402,13 +400,8 @@ static dmExtension::Result InitializeIAP(dmExtension::Params* params)
g_IAP.m_autoFinishTransactions = dmConfigFile::GetInt(params->m_ConfigFile, "iap.auto_finish_transactions", 1) == 1;
JNIEnv* env = Attach();
jclass activity_class = env->FindClass("android/app/NativeActivity");
jmethodID get_class_loader = env->GetMethodID(activity_class,"getClassLoader", "()Ljava/lang/ClassLoader;");
jobject cls = env->CallObjectMethod(dmGraphics::GetNativeAndroidActivity(), get_class_loader);
jclass class_loader = env->FindClass("java/lang/ClassLoader");
jmethodID find_class = env->GetMethodID(class_loader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
dmAndroid::ThreadAttacher threadAttacher;
JNIEnv* env = threadAttacher.GetEnv();
const char* provider = dmConfigFile::GetString(params->m_ConfigFile, "android.iap_provider", "GooglePlay");
const char* class_name = "com.defold.iap.IapGooglePlay";
@@ -422,17 +415,11 @@ static dmExtension::Result InitializeIAP(dmExtension::Params* params)
dmLogWarning("Unknown IAP provider name [%s], defaulting to GooglePlay", provider);
}
jstring str_class_name = env->NewStringUTF(class_name);
jclass iap_class = (jclass)env->CallObjectMethod(cls, find_class, str_class_name);
env->DeleteLocalRef(str_class_name);
str_class_name = env->NewStringUTF("com.defold.iap.IapJNI");
jclass iap_jni_class = (jclass)env->CallObjectMethod(cls, find_class, str_class_name);
env->DeleteLocalRef(str_class_name);
jclass iap_class = dmAndroid::LoadClass(env, class_name);
jclass iap_jni_class = dmAndroid::LoadClass(env, "com.defold.iap.IapJNI");
g_IAP.m_List = env->GetMethodID(iap_class, "listItems", "(Ljava/lang/String;Lcom/defold/iap/IListProductsListener;J)V");
g_IAP.m_Buy = env->GetMethodID(iap_class, "buy", "(Ljava/lang/String;Lcom/defold/iap/IPurchaseListener;)V");
g_IAP.m_Buy = env->GetMethodID(iap_class, "buy", "(Ljava/lang/String;Ljava/lang/String;Lcom/defold/iap/IPurchaseListener;)V");
g_IAP.m_Restore = env->GetMethodID(iap_class, "restore", "(Lcom/defold/iap/IPurchaseListener;)V");
g_IAP.m_Stop = env->GetMethodID(iap_class, "stop", "()V");
g_IAP.m_ProcessPendingConsumables = env->GetMethodID(iap_class, "processPendingConsumables", "(Lcom/defold/iap/IPurchaseListener;)V");
@@ -440,13 +427,11 @@ static dmExtension::Result InitializeIAP(dmExtension::Params* params)
g_IAP.m_AcknowledgeTransaction = env->GetMethodID(iap_class, "acknowledgeTransaction", "(Ljava/lang/String;Lcom/defold/iap/IPurchaseListener;)V");
jmethodID jni_constructor = env->GetMethodID(iap_class, "<init>", "(Landroid/app/Activity;Z)V");
g_IAP.m_IAP = env->NewGlobalRef(env->NewObject(iap_class, jni_constructor, dmGraphics::GetNativeAndroidActivity(), g_IAP.m_autoFinishTransactions));
g_IAP.m_IAP = env->NewGlobalRef(env->NewObject(iap_class, jni_constructor, threadAttacher.GetActivity()->clazz, g_IAP.m_autoFinishTransactions));
jni_constructor = env->GetMethodID(iap_jni_class, "<init>", "()V");
g_IAP.m_IAPJNI = env->NewGlobalRef(env->NewObject(iap_jni_class, jni_constructor));
Detach();
lua_State*L = params->m_L;
int top = lua_gettop(L);
luaL_register(L, LIB_NAME, IAP_methods);
@@ -494,11 +479,11 @@ static dmExtension::Result FinalizeIAP(dmExtension::Params* params)
g_IAP.m_Listener = 0;
}
JNIEnv* env = Attach();
dmAndroid::ThreadAttacher threadAttacher;
JNIEnv* env = threadAttacher.GetEnv();
env->CallVoidMethod(g_IAP.m_IAP, g_IAP.m_Stop);
env->DeleteGlobalRef(g_IAP.m_IAP);
env->DeleteGlobalRef(g_IAP.m_IAPJNI);
Detach();
g_IAP.m_IAP = NULL;
return dmExtension::RESULT_OK;
}

View File

@@ -593,7 +593,11 @@ static dmExtension::Result UpdateIAP(dmExtension::Params* params)
static dmExtension::Result FinalizeIAP(dmExtension::Params* params)
{
if (g_IAP.m_Listener)
{
dmScript::DestroyCallback(g_IAP.m_Listener);
}
g_IAP.m_Listener = 0;
if (g_IAP.m_PendingTransactions) {

View File

@@ -121,18 +121,22 @@ void IAP_Queue_Push(IAPCommandQueue* queue, IAPCommand* cmd)
void IAP_Queue_Flush(IAPCommandQueue* queue, IAPCommandFn fn, void* ctx)
{
assert(fn != 0);
if (queue->m_Commands.Empty())
{
return;
}
DM_MUTEX_SCOPED_LOCK(queue->m_Mutex);
for(uint32_t i = 0; i != queue->m_Commands.Size(); ++i)
dmArray<IAPCommand> tmp;
{
fn(&queue->m_Commands[i], ctx);
DM_MUTEX_SCOPED_LOCK(queue->m_Mutex);
tmp.Swap(queue->m_Commands);
}
for(uint32_t i = 0; i != tmp.Size(); ++i)
{
fn(&tmp[i], ctx);
}
queue->m_Commands.SetSize(0);
}
#endif // DM_PLATFORM_HTML5 || DM_PLATFORM_ANDROID || DM_PLATFORM_IOS

View File

@@ -21,7 +21,7 @@ struct DM_ALIGNED(16) IAPCommand
// Used for storing eventual callback info (if needed)
dmScript::LuaCallbackInfo* m_Callback;
// THe actual command payload
// The actual command payload
int32_t m_Command;
int32_t m_ResponseCode;
void* m_Data;

View File

@@ -81,7 +81,7 @@ public class IapAmazon implements PurchasingListener {
}
}
public void buy(final String product, final IPurchaseListener listener) {
public void buy(final String product, final String token, final IPurchaseListener listener) {
synchronized (purchaseListeners) {
RequestId req = PurchasingService.purchase(product);
if (req != null) {

View File

@@ -19,26 +19,34 @@ import android.util.Log;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClient.BillingResponseCode;
import com.android.billingclient.api.BillingClient.SkuType;
import com.android.billingclient.api.BillingClient.ProductType;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.Purchase.PurchasesResult;
import com.android.billingclient.api.Purchase.PurchaseState;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.ProductDetails;
import com.android.billingclient.api.ProductDetails.OneTimePurchaseOfferDetails;
import com.android.billingclient.api.ProductDetails.PricingPhases;
import com.android.billingclient.api.ProductDetails.PricingPhase;
import com.android.billingclient.api.ProductDetails.RecurrenceMode;
import com.android.billingclient.api.ProductDetails.SubscriptionOfferDetails;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.BillingFlowParams.ProductDetailsParams;
import com.android.billingclient.api.QueryPurchasesParams;
import com.android.billingclient.api.QueryProductDetailsParams;
import com.android.billingclient.api.QueryProductDetailsParams.Product;
import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.android.billingclient.api.PurchasesResponseListener;
import com.android.billingclient.api.ProductDetailsResponseListener;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
public class IapGooglePlay implements PurchasesUpdatedListener {
public static final String TAG = "IapGooglePlay";
private Map<String, SkuDetails> products = new HashMap<String, SkuDetails>();
private Map<String, ProductDetails> products = new HashMap<String, ProductDetails>();
private BillingClient billingClient;
private IPurchaseListener purchaseListener;
private boolean autoFinishTransactions;
@@ -102,6 +110,7 @@ public class IapGooglePlay implements PurchasesUpdatedListener {
p.put("date", toISO8601(new Date(purchase.getPurchaseTime())));
p.put("receipt", purchase.getPurchaseToken());
p.put("signature", purchase.getSignature());
p.put("original_json", purchase.getOriginalJson());
}
catch (JSONException e) {
Log.wtf(TAG, "Failed to convert purchase", e);
@@ -109,16 +118,67 @@ public class IapGooglePlay implements PurchasesUpdatedListener {
return p.toString();
}
private JSONObject convertSkuDetails(SkuDetails skuDetails) {
JSONObject p = new JSONObject();
private JSONArray convertSubscriptionOfferPricingPhases(SubscriptionOfferDetails details) {
JSONArray a = new JSONArray();
try {
p.put("price_string", skuDetails.getPrice());
p.put("ident", skuDetails.getSku());
p.put("currency_code", skuDetails.getPriceCurrencyCode());
p.put("price", skuDetails.getPriceAmountMicros() * 0.000001);
List<PricingPhase> pricingPhases = details.getPricingPhases().getPricingPhaseList();
for (PricingPhase pricingPhase : pricingPhases) {
JSONObject o = new JSONObject();
o.put("price_string", pricingPhase.getFormattedPrice());
o.put("price", pricingPhase.getPriceAmountMicros() * 0.000001);
o.put("currency_code", pricingPhase.getPriceCurrencyCode());
o.put("billing_period", pricingPhase.getBillingPeriod());
o.put("billing_cycle_count", pricingPhase.getBillingCycleCount());
switch (pricingPhase.getRecurrenceMode()) {
case RecurrenceMode.FINITE_RECURRING:
o.put("recurrence_mode", "FINITE");
break;
case RecurrenceMode.INFINITE_RECURRING:
o.put("recurrence_mode", "INFINITE");
break;
default:
case RecurrenceMode.NON_RECURRING:
o.put("recurrence_mode", "NONE");
break;
}
a.put(o);
}
}
catch(JSONException e) {
Log.wtf(TAG, "Failed to convert sku details", e);
Log.wtf(TAG, "Failed to convert subscription offer pricing phases", e);
}
return a;
}
private JSONObject convertProductDetails(ProductDetails productDetails) {
JSONObject p = new JSONObject();
try {
p.put("ident", productDetails.getProductId());
p.put("title", productDetails.getTitle());
p.put("description", productDetails.getDescription());
if (productDetails.getProductType().equals(ProductType.INAPP)) {
OneTimePurchaseOfferDetails offerDetails = productDetails.getOneTimePurchaseOfferDetails();
p.put("price_string", offerDetails.getFormattedPrice());
p.put("currency_code", offerDetails.getPriceCurrencyCode());
p.put("price", offerDetails.getPriceAmountMicros() * 0.000001);
}
else if (productDetails.getProductType().equals(ProductType.SUBS)) {
List<SubscriptionOfferDetails> subscriptionOfferDetails = productDetails.getSubscriptionOfferDetails();
JSONArray a = new JSONArray();
for (SubscriptionOfferDetails offerDetails : subscriptionOfferDetails) {
JSONObject o = new JSONObject();
o.put("token", offerDetails.getOfferToken());
o.put("pricing", convertSubscriptionOfferPricingPhases(offerDetails));
a.put(o);
}
p.put("subscriptions", a);
}
else {
Log.i(TAG, "convertProductDetails() unknown product type " + productDetails.getProductType());
}
}
catch(JSONException e) {
Log.wtf(TAG, "Failed to convert product details", e);
}
return p;
}
@@ -183,21 +243,6 @@ public class IapGooglePlay implements PurchasesUpdatedListener {
return billingResponseCodeToDefoldResponse(result.getResponseCode());
}
/**
* Query Google Play for purchases done within the app.
*/
private List<Purchase> queryPurchases(final String type) {
PurchasesResult result = billingClient.queryPurchases(type);
List<Purchase> purchases = result.getPurchasesList();
if (purchases == null) {
purchases = new ArrayList<Purchase>();
}
if (result.getBillingResult().getResponseCode() != BillingResponseCode.OK) {
Log.e(TAG, "Unable to query pending purchases: " + result.getBillingResult().getDebugMessage());
}
return purchases;
}
/**
* This method is called either explicitly from Lua or from extension code
* when "set_listener()" is called from Lua.
@@ -206,13 +251,35 @@ public class IapGooglePlay implements PurchasesUpdatedListener {
*/
public void processPendingConsumables(final IPurchaseListener purchaseListener) {
Log.d(TAG, "processPendingConsumables()");
List<Purchase> purchasesList = new ArrayList<Purchase>();
purchasesList.addAll(queryPurchases(SkuType.INAPP));
purchasesList.addAll(queryPurchases(SkuType.SUBS));
for (Purchase purchase : purchasesList) {
PurchasesResponseListener purchasesListener = new PurchasesResponseListener() {
private List<Purchase> allPurchases = new ArrayList<Purchase>();
private int queries = 2;
@Override
public void onQueryPurchasesResponse(BillingResult billingResult, List<Purchase> purchases) {
if (billingResult.getResponseCode() != BillingResponseCode.OK) {
Log.e(TAG, "Unable to query pending purchases: " + billingResult.getDebugMessage());
}
if (purchases != null) {
allPurchases.addAll(purchases);
}
// we're finished when we have queried for both in-app and subs
queries--;
if (queries == 0) {
for (Purchase purchase : allPurchases) {
handlePurchase(purchase, purchaseListener);
}
}
}
};
final QueryPurchasesParams inappParams = QueryPurchasesParams.newBuilder().setProductType(ProductType.INAPP).build();
final QueryPurchasesParams subsParams = QueryPurchasesParams.newBuilder().setProductType(ProductType.SUBS).build();
billingClient.queryPurchasesAsync(inappParams, purchasesListener);
billingClient.queryPurchasesAsync(subsParams, purchasesListener);
}
/**
* Consume a purchase. This will acknowledge the purchase and make it
@@ -220,7 +287,7 @@ public class IapGooglePlay implements PurchasesUpdatedListener {
*/
private void consumePurchase(final String purchaseToken, final ConsumeResponseListener consumeListener) {
Log.d(TAG, "consumePurchase() " + purchaseToken);
ConsumeParams consumeParams = ConsumeParams.newBuilder()
final ConsumeParams consumeParams = ConsumeParams.newBuilder()
.setPurchaseToken(purchaseToken)
.build();
@@ -272,7 +339,7 @@ public class IapGooglePlay implements PurchasesUpdatedListener {
* Handle a purchase. If the extension is configured to automatically
* finish transactions the purchase will be immediately consumed. Otherwise
* the product will be returned via the listener without being consumed.
* NOTE: Billing 3.0 requires purchases to be acknowledged within 3 days of
* NOTE: Billing 3.0+ requires purchases to be acknowledged within 3 days of
* purchase unless they are consumed.
*/
private void handlePurchase(final Purchase purchase, final IPurchaseListener purchaseListener) {
@@ -309,12 +376,18 @@ public class IapGooglePlay implements PurchasesUpdatedListener {
* Buy a product. This method stores the listener and uses it in the
* onPurchasesUpdated() callback.
*/
private void buyProduct(SkuDetails sku, final IPurchaseListener purchaseListener) {
private void buyProduct(ProductDetails pd, final String token, final IPurchaseListener purchaseListener) {
this.purchaseListener = purchaseListener;
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
.setSkuDetails(sku)
.build();
List<ProductDetailsParams> productDetailsParams = new ArrayList();
if (pd.getProductType().equals(ProductType.SUBS)) {
productDetailsParams.add(ProductDetailsParams.newBuilder().setProductDetails(pd).setOfferToken(token).build());
}
else {
productDetailsParams.add(ProductDetailsParams.newBuilder().setProductDetails(pd).build());
}
final BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder().setProductDetailsParamsList(productDetailsParams).build();
BillingResult billingResult = billingClient.launchBillingFlow(this.activity, billingFlowParams);
if (billingResult.getResponseCode() != BillingResponseCode.OK) {
@@ -326,21 +399,21 @@ public class IapGooglePlay implements PurchasesUpdatedListener {
/**
* Called from Lua.
*/
public void buy(final String product, final IPurchaseListener purchaseListener) {
public void buy(final String product, final String token, final IPurchaseListener purchaseListener) {
Log.d(TAG, "buy()");
SkuDetails sku = this.products.get(product);
if (sku != null) {
buyProduct(sku, purchaseListener);
ProductDetails pd = this.products.get(product);
if (pd != null) {
buyProduct(pd, token, purchaseListener);
}
else {
List<String> skuList = new ArrayList<String>();
skuList.add(product);
querySkuDetailsAsync(skuList, new SkuDetailsResponseListener() {
List<String> productList = new ArrayList<String>();
productList.add(product);
queryProductDetailsAsync(productList, new ProductDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {
if (billingResult.getResponseCode() == BillingResponseCode.OK && (skuDetailsList != null) && !skuDetailsList.isEmpty()) {
buyProduct(skuDetailsList.get(0), purchaseListener);
public void onProductDetailsResponse(BillingResult billingResult, List<ProductDetails> productDetailsList) {
if (billingResult.getResponseCode() == BillingResponseCode.OK && (productDetailsList != null) && !productDetailsList.isEmpty()) {
buyProduct(productDetailsList.get(0), token, purchaseListener);
}
else {
Log.e(TAG, "Unable to get product details before buying: " + billingResult.getDebugMessage());
@@ -355,30 +428,43 @@ public class IapGooglePlay implements PurchasesUpdatedListener {
* Get details for a list of products. The products can be a mix of
* in-app products and subscriptions.
*/
private void querySkuDetailsAsync(final List<String> skuList, final SkuDetailsResponseListener listener) {
SkuDetailsResponseListener detailsListener = new SkuDetailsResponseListener() {
private List<SkuDetails> allSkuDetails = new ArrayList<SkuDetails>();
private void queryProductDetailsAsync(final List<String> productList, final ProductDetailsResponseListener listener) {
ProductDetailsResponseListener detailsListener = new ProductDetailsResponseListener() {
private List<ProductDetails> allProductDetails = new ArrayList<ProductDetails>();
private int queries = 2;
@Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetails) {
if (skuDetails != null) {
// cache skus (cache will be used to speed up buying)
for (SkuDetails sd : skuDetails) {
IapGooglePlay.this.products.put(sd.getSku(), sd);
public void onProductDetailsResponse(BillingResult billingResult, List<ProductDetails> productDetails) {
if (productDetails != null) {
// cache products (cache will be used to speed up buying)
for (ProductDetails pd : productDetails) {
IapGooglePlay.this.products.put(pd.getProductId(), pd);
}
// add to list of all sku details
allSkuDetails.addAll(skuDetails);
// add to list of all product details
allProductDetails.addAll(productDetails);
}
// we're finished when we have queried for both in-app and subs
queries--;
if (queries == 0) {
listener.onSkuDetailsResponse(billingResult, allSkuDetails);
listener.onProductDetailsResponse(billingResult, allProductDetails);
}
}
};
billingClient.querySkuDetailsAsync(SkuDetailsParams.newBuilder().setSkusList(skuList).setType(SkuType.INAPP).build(), detailsListener);
billingClient.querySkuDetailsAsync(SkuDetailsParams.newBuilder().setSkusList(skuList).setType(SkuType.SUBS).build(), detailsListener);
// we don't know if a product is a subscription or inapp product type
// instread we create two product lists from the same set of products and use INAPP for one and SUBS for the other
List<Product> inappProductList = new ArrayList();
List<Product> subsProductList = new ArrayList();
for (String productId : productList) {
inappProductList.add(Product.newBuilder().setProductId(productId).setProductType(ProductType.INAPP).build());
subsProductList.add(Product.newBuilder().setProductId(productId).setProductType(ProductType.SUBS).build());
}
// do one query per product type
final QueryProductDetailsParams inappParams = QueryProductDetailsParams.newBuilder().setProductList(inappProductList).build();
final QueryProductDetailsParams subsParams = QueryProductDetailsParams.newBuilder().setProductList(subsProductList).build();
billingClient.queryProductDetailsAsync(inappParams, detailsListener);
billingClient.queryProductDetailsAsync(subsParams, detailsListener);
}
/**
@@ -387,21 +473,21 @@ public class IapGooglePlay implements PurchasesUpdatedListener {
public void listItems(final String products, final IListProductsListener productsListener, final long commandPtr) {
Log.d(TAG, "listItems()");
// create list of skus from comma separated string
List<String> skuList = new ArrayList<String>();
// create list of product ids from comma separated string
List<String> productList = new ArrayList<String>();
for (String p : products.split(",")) {
if (p.trim().length() > 0) {
skuList.add(p);
productList.add(p);
}
}
querySkuDetailsAsync(skuList, new SkuDetailsResponseListener() {
queryProductDetailsAsync(productList, new ProductDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetails) {
public void onProductDetailsResponse(BillingResult billingResult, List<ProductDetails> productDetails) {
JSONArray a = new JSONArray();
if (billingResult.getResponseCode() == BillingResponseCode.OK) {
for (SkuDetails sd : skuDetails) {
a.put(convertSkuDetails(sd));
for (ProductDetails pd : productDetails) {
a.put(convertProductDetails(pd));
}
}
else {

View File

@@ -3,7 +3,7 @@ local dirtylarry = require "dirtylarry/dirtylarry"
local GOLDBARS_SMALL = "com.defold.iap.goldbar.small"
local GOLDBARS_MEDIUM = "com.defold.iap.goldbar.medium"
local GOLDBARS_LARGE = "com.defold.iap.goldbar.large"
local SUBSCRIPTION = "com.defold.iap.subscription"
local SUBSCRIPTION = "com.defold.iap.subscription.one"
local NON_CONSUMABLE = "com.defold.iap.removeads"
local items = {
@@ -66,6 +66,7 @@ local function list()
for k,p in pairs(products) do
available_items[p.ident] = p
log("Item %s", p.ident)
pprint(p)
local button = item_buttons[p.ident]
if button then
gui.set_color(gui.get_node(button.."/larrylabel"), vmath.vector4(1,1,1,1))