How to check if firebase service is available? - android

In cases when the app is running behind a firewall or there is a network outage or some sort of censorship, How can we check using code to see if the app can access the firebase systems?

You should check if Google Play Service is available like this:
/**
* Check the device to make sure it has the Google Play Services APK. If it
* doesn't, display a dialog that allows users to download the APK from the
* Google Play Store or enable it in the device's system settings.
*/
public static boolean checkPlayServices(Context context) {
int resultCode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable
(context);
if (resultCode != ConnectionResult.SUCCESS) {
Log.i(TAG, "This device does not support Google Play Services. " +
"Push notifications are not supported");
return false;
}
return true;
}
You need to add the following line to your build.gradle also.
compile 'com.google.android.gms:play-services-gcm:11.8.0'

I am guessing currently there is no way you can check whether Firebase is available or not from codes inside the app. However you can check if Firebase itself is working fine by checking Firebase Status Dashboard.
In this site you can also find in what date Firebase service was not available or unstable in the past.
Hope it helps in some way.
https://status.firebase.google.com/

As the
FirebaseApp.getInstance() throws IllegalStateException
you my try below solution
private val isFirebaseEnabled: Boolean
get() {
return try {
FirebaseApp.getInstance() != null. //that is always true, nevertheless it will throw exception if Firebase is not available
} catch (e: IllegalStateException) {
false
}
}
unfortunately it won't check actual network restrictions. You may try to ping FCM and catch connection timeout. E.g.
private fun isInternetAvailable(): Boolean {
return try {
val connection = URL("https://theUrl.com").openConnection() as HttpURLConnection
connection.setRequestProperty("User-Agent", "Test")
connection.connectTimeout = 10000
connection.connect()
connection.disconnect()
true
} catch (e: Exception) {
false
}
}

Related

TcpClient.ConnectAsync and TcpClient.BeginConnect always returning true in Xamarin.Forms Android Application

I have made an application in my Xamarin.Forms project where I can connect my Android phone to my Computer using a TCP connection. I have found while using both TcpClient.ConnectAsync and TcpClient.BeginConnect, they both return that client.Connected is true even though the port isn't open. I have verified this because I tried random IPs and random ports and it still says connection was successful.
When using TcpClient.ConnectAsync, it doesn't return true unless I press the button that runs the code under Button_Clicked 2 times, but when using TcpClient.BeginConnect, client.Connected always returns true. I know for a fact that the client isn't connected because I have a detection system that kicks the user to the reconnect page when the connection is lost.
The code I have for my TCPClient in MainPage.xaml.cs:
TcpClient client = new TcpClient();
private async void Button_Clicked(object sender, EventArgs e)
{
await client.ConnectAsync(ipAddress.Text, Convert.ToInt32(Port.Text));
if (client.Connected)
{
await DisplayAlert("Connected", "The client has successfully connected", "OK");
}
else
{
await DisplayAlert("Connection Unsuccessful", "The client couldn't connect!", "OK");
}
}
I have also tried using TcpClient.BeginConnect from How to set the timeout for a TcpClient?:
TcpClient client = new TcpClient();
private async void Button_Clicked(object sender, EventArgs e)
{
var result = client.BeginConnect(ipAddress.Text, Convert.ToInt32(Port.Text), null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
if (success)
{
await DisplayAlert("Connected", "The client has successfully connected", "OK");
}
else
{
await DisplayAlert("Connection Unsuccessful", "The client couldn't connect!", "OK");
}
}
I tried looking up the issue and the only thing I found was: TcpClient.Connected returns true yet client is not connected, what can I use instead? but, this link is stating that the client.Connected bool remains true after disconnection, while my problem is that it says the client connects even even though the client never gets a true connection to the server.
The project is currently using .NET Standard 2.0
I have found out the reason it would return client.Connected is true is because running the same ConnectAsync/BeginConnect method twice while the client is still trying to connect and hasn't yet timed out will cause the client.Connected value to be true for some reason.
The only way to fix this it to wait for the timeout to complete, or if the timeout is too long, to dispose the client and create a new one.

Android: Receiving wrong UTM from Google Ads

According to my boss, some of our applications have been invested on advertising of the app via Google Ads. In order for them to parse the data and analyze them correctly, they are using the UTM auto-tagging approach. It is my job from the client (Android Device) to send the UTM using Firebase Analytics and also a custom event to Firebase depending on this UTM.
However, our data shows that both Firebase SDK and our events are transferred incorrectly. The click numbers and the download numbers do not match. Since both of them are incorrect, I'm guessing the received UTM on the device itself is wrong, and this needs to be received correctly and I am unable to find an answer for this.
I'm using Install Referrer Library to track down what the UTM is after the app is downloaded to the device. I am guessing Firebase SDK also uses somewhat similar approach. On our end, the UTM is recorded to SharedPreferences and it is not queried again if the query was successful.
Here is the related code for it (the processReferrer method basically parses the UTM according to our needs):
/**
* Checks if the referrer information is recorded before, if not, creates
* a connection to Google Play and saves the data to shared preferences.
*/
private static void fetchReferrerInformation(Context context)
{
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
String utmData = preferences.getString(UTM_DATA, "");
// Only connect if utm is not recorded before.
if (TextUtils.isEmpty(utmData))
{
InstallReferrerClient client;
try
{
client = InstallReferrerClient.newBuilder(context).build();
client.startConnection(new InstallReferrerStateListener()
{
#Override
public void onInstallReferrerSetupFinished(int responseCode)
{
switch (responseCode)
{
case InstallReferrerClient.InstallReferrerResponse.OK:
{
ReferrerDetails response;
try
{
response = client.getInstallReferrer();
}
catch (Exception e)
{
Log.e(TAG, "Error while fetching referrer information.", e);
if (Fabric.isInitialized())
Crashlytics.logException(new IllegalStateException("Exception while fetching UTM information.", e));
return;
}
if (response != null)
{
processReferrer(context, response.getInstallReferrer());
}
break;
}
case InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED:
{
Log.w(TAG, "Install referrer client: Feature is not supported.");
break;
}
case InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE:
{
Log.w(TAG, "Install referrer client: Service is unavailable.");
break;
}
}
try
{
client.endConnection();
}
catch (Exception ignored){}
}
#Override
public void onInstallReferrerServiceDisconnected()
{
// Do nothing, we need to fetch the information once and
// it is not really necessary to try to reconnect.
// If app is opened once more, the attempt will be made anyway.
}
});
}
catch (Exception e)
{
if (Fabric.isInitialized())
Crashlytics.logException(new IllegalStateException("Exception while fetching UTM information.", e));
}
}
else
Log.i(TAG, "UTM is already recorded, skipping connection initialization. Value: " +
utmData);
}
The approach is pretty simple, however the data seems to be wrong. So, does it seem that the implementation is somewhat incorrect? If not, why is the data received from Google Ads is wrong? Any help is appreciated, thank you very much.
Edit: Upon some testing, here is what I've found:
Works:
An API 19 real device (GM Discovery II Mini) and in between API 25-29 emulators with Play Store installed. Edit: UTM can also be fetched with API 23 and 24 Genymotion Emulators, where Play Store is installed.
Doesn't work:
An API 24 Android Studio emulator with latest Google Play Services and Play Store installed (device is also logged in to my account), and a real device (General Mobile 4G Dual, API 23) cannot query the UTM information. The code below lands on the case of InstallReferrerResponse.FEATURE_NOT_SUPPORTED. So I am almost sure that the install referrer client is bugged on some API levels.
Edit: Opened an issue to the Google: https://issuetracker.google.com/issues/149342702
As I don't know how you are processing the resonse, I can show you the way we did it in our implementation.
ReferrerDetails response = referrerClient.getInstallReferrer();
if (response == null) {
break;
}
String[] installReferrer = response.getInstallReferrer().split("&");
if (installReferrer.length >= 1) {
utmSource = installReferrer[0].split("=")[1];
}
if (installReferrer.length >= 2) {
utmMedium = installReferrer[1].split("=")[1];
}
Compare this snippet with yours and check if anything differs.

How multiple users use google cloud speech at the same time

I'm building an app that uses Google Cloud Speech.
I have a Google Service account key in my app, and I use it to call the API.
It works well when used by one user, but does not work when multiple users use it at the same time.
For example, only one user is available or all are unavailable.
The rights of the service account key are project owner.
I think it's a service account key issue...
How do I fix it?
private class AccessTokenTask extends AsyncTask<Void, Void, AccessToken> {
#Override
protected AccessToken doInBackground(Void... voids) {
final SharedPreferences prefs = mContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
String tokenValue = prefs.getString(PREF_ACCESS_TOKEN_VALUE, null);
long expirationTime = prefs.getLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME, -1);
// Check if the current token is still valid for a while
if (tokenValue != null && expirationTime > 0) {
if (expirationTime > System.currentTimeMillis() + ACCESS_TOKEN_EXPIRATION_TOLERANCE) {
return new AccessToken(tokenValue, new Date(expirationTime));
}
}
final InputStream stream = mContext.getResources().openRawResource(R.raw.credential);
try {
final GoogleCredentials credentials = GoogleCredentials.fromStream(stream).createScoped(SCOPE);
final AccessToken token = credentials.refreshAccessToken();
prefs.edit()
.putString(PREF_ACCESS_TOKEN_VALUE, token.getTokenValue())
.putLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME, token.getExpirationTime().getTime())
.apply();
return token;
} catch (IOException e) {
Log.e(TAG, "Failed to obtain access token.", e);
}
return null;
}
#Override
protected void onPostExecute(AccessToken accessToken) {
mAccessTokenTask = null;
final ManagedChannel channel = new OkHttpChannelProvider()
.builderForAddress(GOOGLE_API_HOSTNAME, GOOGLE_API_PORT)
.nameResolverFactory(new DnsNameResolverProvider())
.intercept(new GoogleCredentialsInterceptor(new GoogleCredentials(accessToken)
.createScoped(SCOPE)))
.build();
mApi = SpeechGrpc.newStub(channel);
// Schedule access token refresh before it expires
if (mHandler != null) {
mHandler.postDelayed(mFetchAccessTokenRunnable,
Math.max(accessToken.getExpirationTime().getTime() - System.currentTimeMillis() - ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE));
}
}
}
This code is the code that calls 'credential.json' file on Android and gets 'Access token'.
The server for this app is python and communicates via http.
https://github.com/GoogleCloudPlatform/android-docs-samples/tree/master/speech/Speech
The description in the link above tells you to delegate the authentication to the server.
I want to write that part with python code.
What should I do?
In the link you provided in the description, they suggest you to read first the basic authentication concepts document. In your case, use a service account for the Android application.
I understand that you have already been able to provide end user credentials to a Google Cloud Platform API, as for example Cloud Speech API.
If you want to authenticate multiple users to your application you should use instead Firebase authentication. The link contains a brief explanation and a tutorial.
There are several Python client libraries for GCP that you can use, depending on what operations do you want to perform on the server. And regarding Python authentication on the server side, this documentation shows how the authentication for Google Cloud Storage works (have this example in mind as a reference).

Is Google play caching the products purchased for offline reference?

Confused as to how the billing service is validating an old purchase after uninstall / reinstall, clearing app data and while the device is offline. I am using James Montemagno's Plugin.InAppBilling for Xamarin. I have a pretty simple MyProduct kind of class with this function.
The IEnumerable that is returned from GetPurchasesAsync has my test purchase in it, when the device is offline. Is this information stored in google play services offline? How do I get rid of it?
public async Task<bool> WasItemPurchased()
{
var billing = CrossInAppBilling.Current;
try
{
var connected = await billing.ConnectAsync();
if (!connected)
{
//Couldn't connect
this.PurchYN = false;
}
//check purchases
var purchases = await billing.GetPurchasesAsync(ItemType.InAppPurchase);
//check for null just incase
if (purchases?.Any(p => p.ProductId == this.AppProdID) ?? false)
{
//Purchase restored
this.PurchYN = true;
}
else
{
//no purchases found
this.PurchYN = false;
}
}
catch (InAppBillingPurchaseException purchaseEx)
{
//Billing Exception handle this based on the type
Debug.WriteLine("Error: " + purchaseEx);
}
catch (Exception ex)
{
this.PurchYN = false;
}
finally
{
await billing.DisconnectAsync();
}
return this.PurchYN;
}
If you clear the cached data for the Play store it should get rid of it.

Android in app purchase: Signature verification failed

I have tried for several days to solve this problem, using the Dungeons demo code that comes with the SDK. I've tried to Google for an answer but can't find one.
In the Dungeons demo, I passed my public key from the dev console.
Signed the apk and uploaded to console without publish.
Testing for both android.test.purchased & product list created on console with published for subscription (The main feature I want for my app).
But still I get an error of Signature verification failed and then the signature does not match data. How can I solve this?
public static ArrayList<VerifiedPurchase> verifyPurchase(String signedData, String signature)
{
if (signedData == null) {
Log.e(TAG, "data is null");
return null;
}
if (Consts.DEBUG) {
Log.i(TAG, "signedData: " + signedData);
}
boolean verified = false;
if (!TextUtils.isEmpty(signature)) {
String base64EncodedPublicKey = "MIIBIjA....AQAB";
PublicKey key = Security.generatePublicKey(base64EncodedPublicKey);
verified = Security.verify(key, signedData, signature);
if (!verified) {
Log.w(TAG, "signature does not match data.");
return null;
}
}
}
public static boolean verify(PublicKey publicKey, String signedData, String signature)
{
if (Consts.DEBUG) {
Log.i(TAG, "signature: " + signature);
}
Signature sig;
try {
sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(Base64.decode(signature))) {
Log.e(TAG, "Signature verification failed.");
return false;
}
return true;
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "NoSuchAlgorithmException.");
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key specification.");
} catch (SignatureException e) {
Log.e(TAG, "Signature exception.");
} catch (Base64DecoderException e) {
Log.e(TAG, "Base64 decoding failed.");
}
return false;
}
This problem is still going on in the current Google billing version. Basically the android.test.purchased is broken; After you buy android.test.purchased the verifyPurchase function in Security.java will always fail and the QueryInventoryFinishedListener will stop at the line if (result.isFailure()); this is because the android.test.purchased item always fails the TextUtils.isEmpty(signature) check in Security.java as it is not a real item and has no signature returned by the server.
My advice (from lack of any other solution) is to NEVER use "android.test.purchased". There are various code tweaks on the net but none of them work 100%.
If you have used the android.test.purchased then one way to get rid of the error is to do the following:-
Edit Security.java and change the "return false" line in the verifyPurchase to "return true" - this is temporary, we'll be putting it back in a minute.
In your QueryInventoryFinishedListener, after the "if (result.isFailure()) {...}" lines add the following to consume and get rid of your never ending android.test.purchased item:
if (inventory.hasPurchase(SKU_ANDROID_TEST_PURCHASE_GOOD)) {
mHelper.consumeAsync(inventory.getPurchase(SKU_ANDROID_TEST_PURCHASE_GOOD),null);
}
Run your app so the consunmeAsync happens, this gets rid of the "android.test.purchased" item on the server.
Remove the consumeAsync code (or comment it out).
Back in the Security.java, change the "return true" back to "return false".
Your QueryInventoryFinishedListener will no longer error on the verify, everything is back to "normal" (if you can call it that). Remember - don't bother using android.test.purchased again as it will just cause this error again... it's broke! The only real way to test your purchasing it to upload an APK, wait for it to appear, and then test it (the same APK) on your device with logging enabled.
Yes, the problem still occurs.
After I bought android.test.purchased I start getting the error on quering the inventory.
It is possible to fix your phone by just clearing data of Google Play Store application and running Google Play one time.
When you clear data of Google Play it forgets that you bought android.test.purchased
Please check that base64EncodedPublicKey and the one from the Play Developer Console are equal.
Once you re-upload the APK in the Developer Console, the public key may change, if so update your base64EncodedPublicKey.
You can skip the verifying process for those "android.test.*" product ids. If you are using the sample code from the TrivialDrive example, open IabHelper.java, find the following line code, change it from
if (Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) { ... }
into
boolean verifySignature = !sku.startsWith("android.test."); // or inplace the condition in the following line
if (verifySignature && !Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) { ... }
It's harmless, even if you forgot to rollback the code. So, you can continue to test the further workflow step.
Based on GMTDev's answer, this is what I do in order to fix the testing issues when consuming products in the simplest possible way. In Security.java, replace the verifyPurchase() method with this:
public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) ||
TextUtils.isEmpty(signature)) {
Log.e(TAG, "Purchase verification failed: missing data.");
return BuildConfig.DEBUG; // Line modified by Cristian. Original line was: return false;
}
PublicKey key = Security.generatePublicKey(base64PublicKey);
return Security.verify(key, signedData, signature);
}
I only modified one line (see comment), and this way you can keep the code like that for debugging and still publish your release versions safely.
The error is caused because of the wrong license key. Maybe the license key is probably from your another app.
The solution is to use the proper license key from :
Play console > App > Development Tools > Licensing & in-app billing
What worked for me, while using In-app Billing v3 and the included utility classes, was consuming the test purchase within the returned onActivityResult call.
No changes to IabHelper, Security, or any of the In-app Billing util classes are needed to avoid this for future test purchases.
If you have already tried purchasing the test product and are now stuck on the purchase signature verification failed error, which you likely are since you are looking up answers for this error, then you should:
make the changes that GMTDev recommended
run the app to ensure that it consumes the product
remove/undo GMTDev's changes
implement the code below within onActivityResult.
Not only does this allow for the purchase testing process to be fluid but this should also avoid any conflicting issues with iab returning the " Item Already Owned " error when attempting to repurchase the test product.
If this is being called from within a fragment and your fragment's onActivityResult isn't being called then be sure to call YourFragmentName.onActivityResult(requestCode, resultCode, data) from your parent ActivityFragment if necessary. This is explained in more detail in Calling startIntentSenderForResult from Fragment (Android Billing v3).
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_PURCHASE) {
//this ensures that the mHelper.flagEndAsync() gets called
//prior to starting a new async request.
mHelper.handleActivityResult(requestCode, resultCode, data);
//get needed data from Intent extra to recreate product object
int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
// Strip out getActivity() if not being used within a fragment
if (resultCode == getActivity().RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
String sku = jo.getString("productId");
//only auto consume the android.test.purchased product
if (sku.equals("android.test.purchased")) {
//build the purchase object from the response data
Purchase purchase = new Purchase("inapp", purchaseData, dataSignature);
//consume android.test.purchased
mHelper.consumeAsync(purchase,null);
}
} catch (JSONException je) {
//failed to parse the purchase data
je.printStackTrace();
} catch (IllegalStateException ise) {
//most likely either disposed, not setup, or
//another billing async process is already running
ise.printStackTrace();
} catch (Exception e) {
//unexpected error
e.printStackTrace();
}
}
}
}
It will only remove the purchase if it's sku is "android.test.purchased" so it should be safe to use.
This Solution worked for me. I changed the new verifyPurchase method in purchase class with old one.
Signature verification fails only for the default test product.
A quick fix :
Goto IabHelper class.
Invert the if conditions of Security.verifyPurchase.
Thats it!
Remember to revert the changes when test product is replaced by actual product
Ran into the same issue (signature verification, and getting rid of the test purchase) today (Oct 30, 2018).
The signature issue is probably being caused by the fact that these test sku's are not really part of your app, and are thus do not have your app's signature. I did open a ticket with Google, but not sure if they can fix this. The workaround, as others pointed out, is to replace the code
if (verifyValidSignature(purchase.getOriginalJson(), purchase.getSignature())) {
with
if (verifyValidSignature(purchase.getOriginalJson(), purchase.getSignature()) ||
(purchase.getSku().startsWith("android.test.")) ) {
Regarding "how to get rid of the purchase of android.test.purchased SKU", I found that a simple reboot of the device, followed by waiting for a minute or so and/or re-starting your app a couple of times fixed it for me (i.e. I didn't have to 'consume' the purchase by code). I am guessing that the wait is needed so that the Play store completes syncing with Google's servers. (Not sure if this will continue to work this way in the future, but if it works for you now, this might help you move forward.)
Check this answer:
Is the primary account on your test device the same as your Google
Play developer account?
If not you won't get signatures on the android.test.* static responses
unless the app has been published on Play before.
See the table at
http://developer.android.com/guide/market/billing/billing_testing.html#static-responses-table
for the full set of conditions.
And it's comment:
I don't think the static ids return signature anymore. See
https://groups.google.com/d/topic/android-developers/PCbCJdOl480/discussion
Also, previously the sample code (used by many big apps) from Google Play Billing Library allowed an empty signature. That's why it's static purchases worked there.
But it was a security hole, so when it was published, Google submitted an update.
I have the same problem and follow #Deadolus said based on https://www.gaffga.de/implementing-in-app-billing-for-android/
The key point is we need to make the SKU is consumable even the inventory query result is failed. Below is the sample how i did that.
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory finished.");
// Have we been disposed of in the meantime? If so, quit.
if (mHelper == null) return;
// Is it a failure?
if (result.isFailure()) {
try {
Purchase purchase = new Purchase("inapp", "{\"packageName\":\"PACKAGE_NAME\","+
"\"orderId\":\"transactionId.android.test.purchased\","+
"\"productId\":\"android.test.purchased\",\"developerPayload\":\"\",\"purchaseTime\":0,"+
"\"purchaseState\":0,\"purchaseToken\":\"inapp:PACKAGE_NAME :android.test.purchased\"}",
"");
} catch (JSONException e) {
e.printStackTrace();
}
mHelper.consumeAsync(purchase, null);
complain("Failed to query inventory: " + result);
return;
}
Log.d(TAG, "Query inventory was successful.");
/*
* Check for items we own. Notice that for each purchase, we check
* the developer payload to see if it's correct! See
* verifyDeveloperPayload().
*/
}
};
Replace PACKAGE_NAME in the code above with the package name of your app.
This is what worked for me:
Call BillingClient.querySkuDetailsAsync to query if item if available
Wait for SkuDetailsResponseListener.onSkuDetailsResponse
Wait another 500ms
Start purchase using BillingClient.launchBillingFlow...
The step 3 shouldn't be necessary because when I received onSkuDetailsResponse it should be OK but it isn't, had to wait a little bit. After that purchase works, no more "Item not available error". This is how I tested it:
clear my app data
clear Google Play data
run app
purchase android.test.purchased
try to purchase my items (it fails with item not available)
use my solution above, it works
For Cordova and Hybrid apps you need to use this.iap.subscribe(this.productId) method to subscription InAppPurchase.
Following are the code working fine for me:
getProdutIAP() {
this.navCtrl.push('subscribeDialogPage');
this.iap
.getProducts(['productID1']).then((products: any) => {
this.buy(products);
})
.catch((err) => {
console.log(JSON.stringify(err));
alert('Finished Purchase' + JSON.stringify(err));
console.log(err);
});
}
buy(products: any) {
// this.getProdutIAP();
// alert(products[0].productId);
this.iap.subscribe(products[0].productId).then((buydata: any) => {
alert('buy Purchase' + JSON.stringify(buydata));
// this.sub();
}).catch((err) => {
// this.navCtrl.push('subscribeDialogPage');
alert('buyError' + JSON.stringify(err));
});
}
sub() {
this.platform.ready().then(() => {
this.iap
.subscribe(this.productId)
.then((data) => {
console.log('subscribe Purchase' + JSON.stringify(data));
alert('subscribe Purchase' + JSON.stringify(data));
this.getReceipt();
}).catch((err) => {
this.getReceipt();
alert('subscribeError' + JSON.stringify(err));
console.log(err);
});
})
}

Categories

Resources