Unverified Commit 24ad4894 by Rémi Verschelde Committed by GitHub

Merge pull request #39050 from timoschwarzer/google-play-billing-4.0

(4.0) Re-implement GodotPayment Android plugin using the Google Play Billing library
parents f8005cb6 4b00bf8e
......@@ -3,7 +3,6 @@ apply plugin: 'com.android.library'
android {
compileSdkVersion versions.compileSdk
buildToolsVersion versions.buildTools
useLibrary 'org.apache.http.legacy'
defaultConfig {
minSdkVersion versions.minSdk
......@@ -21,6 +20,7 @@ android {
dependencies {
implementation libraries.supportCoreUtils
implementation libraries.v4Support
implementation 'com.android.billingclient:billing:2.2.1'
if (rootProject.findProject(":lib")) {
compileOnly project(":lib")
......
/*************************************************************************/
/* ConsumeTask.java */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.plugin.payment;
import android.content.Context;
import android.os.AsyncTask;
import android.os.RemoteException;
import com.android.vending.billing.IInAppBillingService;
import java.lang.ref.WeakReference;
abstract public class ConsumeTask {
private Context context;
private IInAppBillingService mService;
private String mSku;
private String mToken;
private static class ConsumeAsyncTask extends AsyncTask<String, String, String> {
private WeakReference<ConsumeTask> mTask;
ConsumeAsyncTask(ConsumeTask consume) {
mTask = new WeakReference<>(consume);
}
@Override
protected String doInBackground(String... strings) {
ConsumeTask consume = mTask.get();
if (consume != null) {
return consume.doInBackground(strings);
}
return null;
}
@Override
protected void onPostExecute(String param) {
ConsumeTask consume = mTask.get();
if (consume != null) {
consume.onPostExecute(param);
}
}
}
public ConsumeTask(IInAppBillingService mService, Context context) {
this.context = context;
this.mService = mService;
}
public void consume(final String sku) {
mSku = sku;
PaymentsCache pc = new PaymentsCache(context);
Boolean isBlocked = pc.getConsumableFlag("block", sku);
mToken = pc.getConsumableValue("token", sku);
if (!isBlocked && mToken == null) {
// Consuming task is processing
} else if (!isBlocked) {
return;
} else if (mToken == null) {
this.error("No token for sku:" + sku);
return;
}
new ConsumeAsyncTask(this).execute();
}
private String doInBackground(String... params) {
try {
int response = mService.consumePurchase(3, context.getPackageName(), mToken);
if (response == 0 || response == 8) {
return null;
}
} catch (RemoteException e) {
return e.getMessage();
}
return "Some error";
}
private void onPostExecute(String param) {
if (param == null) {
success(new PaymentsCache(context).getConsumableValue("ticket", mSku));
} else {
error(param);
}
}
abstract protected void success(String ticket);
abstract protected void error(String message);
}
/*************************************************************************/
/* HandlePurchaseTask.java */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.plugin.payment;
import android.app.Activity;
import android.content.Intent;
import org.json.JSONException;
import org.json.JSONObject;
abstract public class HandlePurchaseTask {
private Activity context;
public HandlePurchaseTask(Activity context) {
this.context = context;
}
public void handlePurchaseRequest(int resultCode, Intent data) {
//Log.d("XXX", "Handling purchase response");
if (resultCode == Activity.RESULT_OK) {
try {
//int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
PaymentsCache pc = new PaymentsCache(context);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
//Log.d("XXX", "Purchase data:" + purchaseData);
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
//Log.d("XXX", "Purchase signature:" + dataSignature);
//Log.d("SARLANGA", purchaseData);
JSONObject jo = new JSONObject(purchaseData);
//String sku = jo.getString("productId");
//alert("You have bought the " + sku + ". Excellent choice, aventurer!");
//String orderId = jo.getString("orderId");
//String packageName = jo.getString("packageName");
String productId = jo.getString("productId");
//Long purchaseTime = jo.getLong("purchaseTime");
//Integer state = jo.getInt("purchaseState");
String developerPayload = jo.getString("developerPayload");
String purchaseToken = jo.getString("purchaseToken");
if (!pc.getConsumableValue("validation_hash", productId).equals(developerPayload)) {
error("Untrusted callback");
return;
}
//Log.d("XXX", "Este es el product ID:" + productId);
pc.setConsumableValue("ticket_signautre", productId, dataSignature);
pc.setConsumableValue("ticket", productId, purchaseData);
pc.setConsumableFlag("block", productId, true);
pc.setConsumableValue("token", productId, purchaseToken);
success(productId, dataSignature, purchaseData);
return;
} catch (JSONException e) {
error(e.getMessage());
}
} else if (resultCode == Activity.RESULT_CANCELED) {
canceled();
}
}
abstract protected void success(String sku, String signature, String ticket);
abstract protected void error(String message);
abstract protected void canceled();
}
/*************************************************************************/
/* PaymentsCache.java */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.plugin.payment;
import android.content.Context;
import android.content.SharedPreferences;
public class PaymentsCache {
public Context context;
public PaymentsCache(Context context) {
this.context = context;
}
public void setConsumableFlag(String set, String sku, Boolean flag) {
SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(sku, flag);
editor.apply();
}
public boolean getConsumableFlag(String set, String sku) {
SharedPreferences sharedPref = context.getSharedPreferences(
"consumables_" + set, Context.MODE_PRIVATE);
return sharedPref.getBoolean(sku, false);
}
public void setConsumableValue(String set, String sku, String value) {
SharedPreferences sharedPref = context.getSharedPreferences("consumables_" + set, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(sku, value);
//Log.d("XXX", "Setting asset: consumables_" + set + ":" + sku);
editor.apply();
}
public String getConsumableValue(String set, String sku) {
SharedPreferences sharedPref = context.getSharedPreferences(
"consumables_" + set, Context.MODE_PRIVATE);
//Log.d("XXX", "Getting asset: consumables_" + set + ":" + sku);
return sharedPref.getString(sku, null);
}
}
/*************************************************************************/
/* PurchaseTask.java */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.plugin.payment;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import com.android.vending.billing.IInAppBillingService;
abstract public class PurchaseTask {
private Activity context;
private IInAppBillingService mService;
public PurchaseTask(IInAppBillingService mService, Activity context) {
this.context = context;
this.mService = mService;
}
private boolean isLooping = false;
public void purchase(final String sku, final String transactionId) {
Log.d("XXX", "Starting purchase for: " + sku);
PaymentsCache pc = new PaymentsCache(context);
Boolean isBlocked = pc.getConsumableFlag("block", sku);
/*
if(isBlocked) {
Log.d("XXX", "Is awaiting payment confirmation");
error("Awaiting payment confirmation");
return;
}
*/
final String hash = transactionId;
Bundle buyIntentBundle;
try {
buyIntentBundle = mService.getBuyIntent(3, context.getApplicationContext().getPackageName(), sku, "inapp", hash);
} catch (RemoteException e) {
//Log.d("XXX", "Error: " + e.getMessage());
error(e.getMessage());
return;
}
Object rc = buyIntentBundle.get("RESPONSE_CODE");
int responseCode = 0;
if (rc == null) {
responseCode = PaymentsManager.BILLING_RESPONSE_RESULT_OK;
} else if (rc instanceof Integer) {
responseCode = ((Integer)rc).intValue();
} else if (rc instanceof Long) {
responseCode = (int)((Long)rc).longValue();
}
//Log.d("XXX", "Buy intent response code: " + responseCode);
if (responseCode == 1 || responseCode == 3 || responseCode == 4) {
canceled();
return;
}
if (responseCode == 7) {
alreadyOwned();
return;
}
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
pc.setConsumableValue("validation_hash", sku, hash);
try {
if (context == null) {
//Log.d("XXX", "No context!");
}
if (pendingIntent == null) {
//Log.d("XXX", "No pending intent");
}
//Log.d("XXX", "Starting activity for purchase!");
context.startIntentSenderForResult(
pendingIntent.getIntentSender(),
PaymentsManager.REQUEST_CODE_FOR_PURCHASE,
new Intent(),
Integer.valueOf(0), Integer.valueOf(0),
Integer.valueOf(0));
} catch (SendIntentException e) {
error(e.getMessage());
}
}
abstract protected void error(String message);
abstract protected void canceled();
abstract protected void alreadyOwned();
}
/*************************************************************************/
/* ReleaseAllConsumablesTask.java */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.plugin.payment;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.android.vending.billing.IInAppBillingService;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
abstract public class ReleaseAllConsumablesTask {
private Context context;
private IInAppBillingService mService;
private static class ReleaseAllConsumablesAsyncTask extends AsyncTask<String, String, String> {
private WeakReference<ReleaseAllConsumablesTask> mTask;
private String mSku;
private String mReceipt;
private String mSignature;
private String mToken;
ReleaseAllConsumablesAsyncTask(ReleaseAllConsumablesTask task, String sku, String receipt, String signature, String token) {
mTask = new WeakReference<ReleaseAllConsumablesTask>(task);
mSku = sku;
mReceipt = receipt;
mSignature = signature;
mToken = token;
}
@Override
protected String doInBackground(String... params) {
ReleaseAllConsumablesTask consume = mTask.get();
if (consume != null) {
return consume.doInBackground(mToken);
}
return null;
}
@Override
protected void onPostExecute(String param) {
ReleaseAllConsumablesTask consume = mTask.get();
if (consume != null) {
consume.success(mSku, mReceipt, mSignature, mToken);
}
}
}
public ReleaseAllConsumablesTask(IInAppBillingService mService, Context context) {
this.context = context;
this.mService = mService;
}
public void consumeItAll() {
try {
//Log.d("godot", "consumeItall for " + context.getPackageName());
Bundle bundle = mService.getPurchases(3, context.getPackageName(), "inapp", null);
if (bundle.getInt("RESPONSE_CODE") == 0) {
final ArrayList<String> myPurchases = bundle.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
final ArrayList<String> mySignatures = bundle.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
if (myPurchases == null || myPurchases.size() == 0) {
//Log.d("godot", "No purchases!");
notRequired();
return;
}
//Log.d("godot", "# products to be consumed:" + myPurchases.size());
for (int i = 0; i < myPurchases.size(); i++) {
try {
String receipt = myPurchases.get(i);
JSONObject inappPurchaseData = new JSONObject(receipt);
String sku = inappPurchaseData.getString("productId");
String token = inappPurchaseData.getString("purchaseToken");
String signature = mySignatures.get(i);
//Log.d("godot", "A punto de consumir un item con token:" + token + "\n" + receipt);
new ReleaseAllConsumablesAsyncTask(this, sku, receipt, signature, token).execute();
} catch (JSONException e) {
}
}
}
} catch (Exception e) {
Log.d("godot", "Error releasing products:" + e.getClass().getName() + ":" + e.getMessage());
}
}
private String doInBackground(String token) {
try {
//Log.d("godot", "Requesting to consume an item with token ." + token);
int response = mService.consumePurchase(3, context.getPackageName(), token);
//Log.d("godot", "consumePurchase response: " + response);
if (response == 0 || response == 8) {
return null;
}
} catch (Exception e) {
Log.d("godot", "Error " + e.getClass().getName() + ":" + e.getMessage());
}
return null;
}
abstract protected void success(String sku, String receipt, String signature, String token);
abstract protected void error(String message);
abstract protected void notRequired();
}
/*************************************************************************/
/* ValidateTask.java */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.plugin.payment;
import org.godotengine.godot.plugin.payment.utils.HttpRequester;
import org.godotengine.godot.plugin.payment.utils.RequestParams;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import java.lang.ref.WeakReference;
import org.json.JSONException;
import org.json.JSONObject;
abstract public class ValidateTask {
private Activity context;
private GodotPayment godotPayments;
private ProgressDialog dialog;
private String mSku;
private static class ValidateAsyncTask extends AsyncTask<String, String, String> {
private WeakReference<ValidateTask> mTask;
ValidateAsyncTask(ValidateTask task) {
mTask = new WeakReference<>(task);
}
@Override
protected void onPreExecute() {
ValidateTask task = mTask.get();
if (task != null) {
task.onPreExecute();
}
}
@Override
protected String doInBackground(String... params) {
ValidateTask task = mTask.get();
if (task != null) {
return task.doInBackground(params);
}
return null;
}
@Override
protected void onPostExecute(String response) {
ValidateTask task = mTask.get();
if (task != null) {
task.onPostExecute(response);
}
}
}
public ValidateTask(Activity context, GodotPayment godotPayments) {
this.context = context;
this.godotPayments = godotPayments;
}
public void validatePurchase(final String sku) {
mSku = sku;
new ValidateAsyncTask(this).execute();
}
private void onPreExecute() {
dialog = ProgressDialog.show(context, null, "Please wait...");
}
private String doInBackground(String... params) {
PaymentsCache pc = new PaymentsCache(context);
String url = godotPayments.getPurchaseValidationUrlPrefix();
RequestParams param = new RequestParams();
param.setUrl(url);
param.put("ticket", pc.getConsumableValue("ticket", mSku));
param.put("purchaseToken", pc.getConsumableValue("token", mSku));
param.put("sku", mSku);
//Log.d("XXX", "Haciendo request a " + url);
//Log.d("XXX", "ticket: " + pc.getConsumableValue("ticket", sku));
//Log.d("XXX", "purchaseToken: " + pc.getConsumableValue("token", sku));
//Log.d("XXX", "sku: " + sku);
param.put("package", context.getApplicationContext().getPackageName());
HttpRequester requester = new HttpRequester();
String jsonResponse = requester.post(param);
//Log.d("XXX", "Validation response:\n"+jsonResponse);
return jsonResponse;
}
private void onPostExecute(String response) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
JSONObject j;
try {
j = new JSONObject(response);
if (j.getString("status").equals("OK")) {
success();
return;
} else if (j.getString("status") != null) {
error(j.getString("message"));
} else {
error("Connection error");
}
} catch (JSONException e) {
error(e.getMessage());
} catch (Exception e) {
error(e.getMessage());
}
}
abstract protected void success();
abstract protected void error(String message);
abstract protected void canceled();
}
/*************************************************************************/
/* CustomSSLSocketFactory.java */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.plugin.payment.utils;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
/**
*
* @author Luis Linietsky <luis.linietsky@gmail.com>
*/
public class CustomSSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(truststore);
sslContext.init(null, tmf.getTrustManagers(), null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
package org.godotengine.godot.plugin.payment.utils;
import org.godotengine.godot.Dictionary;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.SkuDetails;
import java.util.List;
public class GodotPaymentUtils {
public static Dictionary convertPurchaseToDictionary(Purchase purchase) {
Dictionary dictionary = new Dictionary();
dictionary.put("order_id", purchase.getOrderId());
dictionary.put("package_name", purchase.getPackageName());
dictionary.put("purchase_state", Integer.valueOf(purchase.getPurchaseState()));
dictionary.put("purchase_time", Long.valueOf(purchase.getPurchaseTime()));
dictionary.put("purchase_token", purchase.getPurchaseToken());
dictionary.put("signature", purchase.getSignature());
dictionary.put("sku", purchase.getSku());
dictionary.put("is_acknowledged", Boolean.valueOf(purchase.isAcknowledged()));
dictionary.put("is_auto_renewing", Boolean.valueOf(purchase.isAutoRenewing()));
return dictionary;
}
public static Dictionary convertSkuDetailsToDictionary(SkuDetails details) {
Dictionary dictionary = new Dictionary();
dictionary.put("sku", details.getSku());
dictionary.put("title", details.getTitle());
dictionary.put("description", details.getDescription());
dictionary.put("price", details.getPrice());
dictionary.put("price_currency_code", details.getPriceCurrencyCode());
dictionary.put("price_amount_micros", Long.valueOf(details.getPriceAmountMicros()));
dictionary.put("free_trial_period", details.getFreeTrialPeriod());
dictionary.put("icon_url", details.getIconUrl());
dictionary.put("introductory_price", details.getIntroductoryPrice());
dictionary.put("introductory_price_amount_micros", Long.valueOf(details.getIntroductoryPriceAmountMicros()));
dictionary.put("introductory_price_cycles", details.getIntroductoryPriceCycles());
dictionary.put("introductory_price_period", details.getIntroductoryPricePeriod());
dictionary.put("original_price", details.getOriginalPrice());
dictionary.put("original_price_amount_micros", Long.valueOf(details.getOriginalPriceAmountMicros()));
dictionary.put("subscription_period", details.getSubscriptionPeriod());
dictionary.put("type", details.getType());
dictionary.put("is_rewarded", Boolean.valueOf(details.isRewarded()));
return dictionary;
}
public static Object[] convertPurchaseListToDictionaryObjectArray(List<Purchase> purchases) {
Object[] purchaseDictionaries = new Object[purchases.size()];
for (int i = 0; i < purchases.size(); i++) {
purchaseDictionaries[i] = GodotPaymentUtils.convertPurchaseToDictionary(purchases.get(i));
}
return purchaseDictionaries;
}
public static Object[] convertSkuDetailsListToDictionaryObjectArray(List<SkuDetails> skuDetails) {
Object[] skuDetailsDictionaries = new Object[skuDetails.size()];
for (int i = 0; i < skuDetails.size(); i++) {
skuDetailsDictionaries[i] = GodotPaymentUtils.convertSkuDetailsToDictionary(skuDetails.get(i));
}
return skuDetailsDictionaries;
}
}
/*************************************************************************/
/* HttpRequester.java */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.plugin.payment.utils;
import org.godotengine.godot.utils.Crypt;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.util.Date;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/**
*
* @author Luis Linietsky <luis.linietsky@gmail.com>
*/
public class HttpRequester {
private Context context;
private static final int TTL = 600000; // 10 minutos
private long cttl = 0;
public HttpRequester() {
//Log.d("XXX", "Creando http request sin contexto");
}
public HttpRequester(Context context) {
this.context = context;
//Log.d("XXX", "Creando http request con contexto");
}
public String post(RequestParams params) {
HttpPost httppost = new HttpPost(params.getUrl());
try {
httppost.setEntity(new UrlEncodedFormEntity(params.toPairsList()));
return request(httppost);
} catch (UnsupportedEncodingException e) {
return null;
}
}
public String get(RequestParams params) {
String response = getResponseFromCache(params.getUrl());
if (response == null) {
//Log.d("XXX", "Cache miss!");
HttpGet httpget = new HttpGet(params.getUrl());
long timeInit = new Date().getTime();
response = request(httpget);
long delay = new Date().getTime() - timeInit;
Log.d("HttpRequest::get(url)", "Url: " + params.getUrl() + " downloaded in " + String.format("%.03f", delay / 1000.0f) + " seconds");
if (response == null || response.length() == 0) {
response = "";
} else {
saveResponseIntoCache(params.getUrl(), response);
}
}
Log.d("XXX", "Req: " + params.getUrl());
Log.d("XXX", "Resp: " + response);
return response;
}
private String request(HttpUriRequest request) {
//Log.d("XXX", "Haciendo request a: " + request.getURI() );
Log.d("PPP", "Haciendo request a: " + request.getURI());
long init = new Date().getTime();
HttpClient httpclient = getNewHttpClient();
HttpParams httpParameters = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 0);
HttpConnectionParams.setSoTimeout(httpParameters, 0);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
try {
HttpResponse response = httpclient.execute(request);
Log.d("PPP", "Fin de request (" + (new Date().getTime() - init) + ") a: " + request.getURI());
//Log.d("XXX1", "Status:" + response.getStatusLine().toString());
if (response.getStatusLine().getStatusCode() == 200) {
String strResponse = EntityUtils.toString(response.getEntity());
//Log.d("XXX2", strResponse);
return strResponse;
} else {
Log.d("XXX3", "Response status code:" + response.getStatusLine().getStatusCode() + "\n" + EntityUtils.toString(response.getEntity()));
return null;
}
} catch (ClientProtocolException e) {
Log.d("XXX3", e.getMessage());
} catch (IOException e) {
Log.d("XXX4", e.getMessage());
}
return null;
}
private HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public void saveResponseIntoCache(String request, String response) {
if (context == null) {
//Log.d("XXX", "No context, cache failed!");
return;
}
SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("request_" + Crypt.md5(request), response);
editor.putLong("request_" + Crypt.md5(request) + "_ttl", new Date().getTime() + getTtl());
editor.apply();
}
public String getResponseFromCache(String request) {
if (context == null) {
Log.d("XXX", "No context, cache miss");
return null;
}
SharedPreferences sharedPref = context.getSharedPreferences("http_get_cache", Context.MODE_PRIVATE);
long ttl = getResponseTtl(request);
if (ttl == 0l || (new Date().getTime() - ttl) > 0l) {
Log.d("XXX", "Cache invalid ttl:" + ttl + " vs now:" + new Date().getTime());
return null;
}
return sharedPref.getString("request_" + Crypt.md5(request), null);
}
public long getResponseTtl(String request) {
SharedPreferences sharedPref = context.getSharedPreferences(
"http_get_cache", Context.MODE_PRIVATE);
return sharedPref.getLong("request_" + Crypt.md5(request) + "_ttl", 0l);
}
public long getTtl() {
return cttl > 0 ? cttl : TTL;
}
public void setTtl(long ttl) {
this.cttl = (ttl * 1000) + new Date().getTime();
}
}
/*************************************************************************/
/* RequestParams.java */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
package org.godotengine.godot.plugin.payment.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
/**
*
* @author Luis Linietsky <luis.linietsky@gmail.com>
*/
public class RequestParams {
private HashMap<String, String> params;
private String url;
public RequestParams() {
params = new HashMap<String, String>();
}
public void put(String key, String value) {
params.put(key, value);
}
public String get(String key) {
return params.get(key);
}
public void remove(Object key) {
params.remove(key);
}
public boolean has(String key) {
return params.containsKey(key);
}
public List<NameValuePair> toPairsList() {
List<NameValuePair> fields = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
fields.add(new BasicNameValuePair(key, this.get(key)));
}
return fields;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
......@@ -94,7 +94,7 @@ static const PluginConfig GODOT_PAYMENT = {
/*.binary_type =*/"local",
/*.binary =*/"res://android/build/libs/plugins/GodotPayment.release.aar",
/*.local_dependencies =*/{},
/*.remote_dependencies =*/{},
/*.remote_dependencies =*/String("com.android.billingclient:billing:2.2.1").split("|"),
/*.custom_maven_repos =*/{}
};
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment