Android app Subscription details expiry date - android

How to get Subscription details like Expiry date and Active status etc. I have completed buying subscription flow using
mHelper.launchSubscriptionPurchaseFlow((Activity) mContext, RegistrationAcceptActivity.SKU_SUBSCRIBE, RegistrationAcceptActivity.RC_REQUEST,
mPurchaseFinishedListener, "");
Once the it executed successfully, I got
{"orderId":"GPA.1380-1270-1169-98789","packageName":"com.xxx","productId":"xxxx","purchaseTime":1458222969093,"purchaseState":0,"purchaseToken":"aaaabbbbccccddddeeeeasdfsadfasdfsadfxcvxcvxcvxcsdfasdafsadfsd","autoRenewing":true}
But still I am searching for how to get subscription detail whenever needed. Ex: I need to send the updated expiry date to my server while splash activity loading.
Some one suggested to use Google Developer console(V2) API. Some of the classes are deprecated like HTTPDefaultClient etc.
I am unable to conclude whether this is the right solution or I need to follow some other way to get subscription details.

Related

Google Play Store Subscriptions History

I'am using subscriptions in my application and it is working perfectly during testing. However, I didn't find a way to get user subscription history for all transactions.
Example:
-User subscribed to product id "sub1" for 3 months. (purchaseToken : "X")
-User canceled subscription for same product id "sub1"
-User resubscribed for same product id (purchaseToken : "Y")
In this scenario when querying queryPurchaseHistoryAsync() function it is returning only latest purchase. Also when using this [API][https://developers.google.com/android-publisher/api-ref/purchases/subscriptions/get] it returns only information of a specific purchase token ("Y" retreived from queryPurchaseHistoryAsync()).
Is there any other way to get user subscriptions history (Detailed transactions)
?
Any help would be greatly appreciated
After a lot of searching it turned out that there is no API that returns detailed transactions of specific subscription.

Migrating from Android Pay to Google Payment API

TL;DR: Can I process a transaction using a PaymentDataRequest built using WalletConstants.TOTAL_PRICE_STATUS_ESTIMATED as the TransactionInfo's "TotalPriceStatus"?
Full Issue Description
I have an app that currently has AndroidPay integrated as a payment method, and I want to migrate this to use the new Google Payment API.
Users can purchase things that are shipped to them, and since shipping costs can change based on location, I can't calculate the final cost of the order until I get the user's shipping address from the MaskedWallet (AndroidPay) or PaymentData (Google Payment). When using AndroidPay, the user is shown a bottom-sheet dialog when I request the MaskedWallet, then I can calculate the order total, and then request the FullWallet with an exact amount to charge the user.
If I follow the same basic pattern with Google Payment, I request a PaymentData like so:
PaymentDataRequest.Builder request = PaymentDataRequest.newBuilder()
.setTransactionInfo(TransactionInfo.newBuilder()
.setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_ESTIMATED)
.setTotalPrice("123")
.setCurrencyCode("USD")
.build())
.addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_CARD)
.addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD)
.setPhoneNumberRequired(true)
.setEmailRequired(true)
.setShippingAddressRequired(true)
.setPaymentMethodTokenizationParameters(getTokenizationParameters())
.setCardRequirements(getCardRequirements());
where getTokenizationParameters() and getCardRequirements() are locally defined helper methods. After I make this request, a dialog is shown to the user that confirms their address and credit card (just like requesting the MaskedWallet for AndroidPay), then I show a confirmation UI of my own that shows a breakdown in the price. When the user clicks to confirm the purchase and place the order, I'm creating another PaymentDataRequest, but this time using WalletConstants.TOTAL_PRICE_STATUS_FINAL in the TransactionInfo because I know know exactly how much the customer will be charged, like so:
PaymentDataRequest.Builder request = PaymentDataRequest.newBuilder()
.setTransactionInfo(TransactionInfo.newBuilder()
.setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
.setTotalPrice("133.5")
.setCurrencyCode("USD")
.build())
.addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_CARD)
.addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD)
.setPhoneNumberRequired(true)
.setEmailRequired(true)
.setUiRequired(false)
.setShippingAddressRequired(true)
.setPaymentMethodTokenizationParameters(getTokenizationParameters())
.setCardRequirements(getCardRequirements());
I'm doing this second request in part because this mirrors the process used in Android Pay with a FullWallet, but the UX is terrible because of this second dialog.
Do I have to create a PaymentDataRequest using WalletConstants.TOTAL_PRICE_STATUS_FINAL to get a PaymentData that I can use to charge the user, or can I use WalletConstants.TOTAL_PRICE_STATUS_ESTIMATED and use that PaymentData to charge the user, even though the exact dollar amount the user is charged may be different from the amount I created the request with?
As you correctly pointed out, unlike the old Android Pay API which had loadMaskedWallet and loadFullWallet that were supposed to be called in different parts of the flow, the Google Pay API only has a single loadPaymentData call which can be, in this sense, considered a combination of the two (i.e. calling loadFullWallet immediately after loadMaskedWallet).
This means that there's no need to make the second PaymentDataRequest - since your final price is not known when you request the payment credentials from Google, TOTAL_PRICE_STATUS_ESTIMATED is the correct approach. Once you've received the payment credentials successfully, there's no need to make any further calls to the API.
Keep in mind that Google does not process transactions, so you would still need to provide your payment processor / gateway with the correct final amount.

How to verify purchase for android app in server side (google play in app billing v3)

I have a simple app (needs user login with account). I provide some premium features for paid users, like more news content.
I need to record if the user has bought this item in my server database. When I provide data content to user's device, I can then check the user's status, and provide different content for paid user.
I checked the official Trivialdrive sample provided by Google, it does not provide any sample code for server-side verification, here are my questions.
I found the sample use my app's public key inside to verify purchase, it looks not good, I think I can just move the verification process to my server combined with user login credentials to see whether the user purchase completed, and then update the database.
Also there is purchase API I can use to query, what I need is to pass the user's purchaseToken into server.
I am not sure what method I should take to verify the user's purchase, and mark the user's status in my database, maybe both?
And I am afraid there is a situation, if a user bought this item from google play, but for some reason, just in that time, when my app launched verification to my server, the network connection is down or my own server is down, user just paid the money in google play but I did not record the purchase in my server? What should I do, How can I deal with this situation.
It sounds what you're looking for is a way to check if the user has premium features enabled on their account, so this is where I would start;
Ensure there is a flag of some sort on your database indicating if the user has premium features and include that in the API response payload when requesting account info. This flag will be your primary authority for "premium features".
When a user makes an in-app purchase, cache the details (token, order id, and product id) locally on the client (i.e the app) then send it to your API.
Your API should then send the purchaseToken to the Google Play Developer API for validation.
A few things might happen from here:
The receipt is valid, your API responds to the client with a 200 Ok status code
The receipt is invalid, your API responds to the client with a 400 Bad Request status code
Google Play API is down, your API responds with a 502 Bad Gateway status code
In the case of 1. or 2. (2xx or 4xx status codes) your client clears the cache of purchase details because it doesn't need it anymore because the API has indicated that it has been received.
Upon a successful validation (case 1.), you should set the premium flag to true for the user.
In the case of 3. (5xx status code) or a network timeout the client should keep trying until it receives a 2xx or 4xx status code from your API.
Depending on your requirements, you could make it wait a few seconds before sending again or just send the details to your API when ever the app is launched again or comes out of background if the purchase details are present on the app cache.
This approach should take care of network timeouts, servers being unavailable, etc.
There are now a few questions you need to consider:
What should happen immediately after a purchase? Should the app wait until validation is successful before providing premium content or should it tentatively grant access and take it away if the validation fails?
Granting tentative access to premium features smooths the process for a majority of your users, but you will be granting access to a number of fraudulent users too while your API validates the purchaseToken.
To put this in another way: Purchase is valid until proven fraudulent or; fraudulent until proven valid?
In order to identify if the user still has a valid subscription when their subscription period comes up for renewal, you will need to schedule a re-validation on the purchaseToken to run at the expiryTimeMillis that was returned in the result.
If the expiryTimeMillis is in the past, you can set the premium flag to false. If it's in the future, re-schedule it again for the new expiryTimeMillis.
Lastly, to ensure the user has premium access (or not), your app should query your API for the users details on app launch or when it comes out of background.
The documentation on this is confusing and weirdly verbose with the things that are almost inconsequential while leaving the actually important documentation almost unlinked and super hard to find. This should work great on most popular server platform that can run the google api client libraries, including Java, Python, .Net, and NodeJS, among others. Note: I've tested only the Python api client as shown below.
Necessary steps:
Make an API project, from the API Access link in your Google Play console
Make a new service account, save the JSON private key that gets generated. You'll need to take this file to your server.
Press Done in the Play console's service account section to refresh and then grant access to the service account
Go get a google api client library for your server platform from https://developers.google.com/api-client-library
Use your particular platform's client library to build a service interface and directly read the result of your purchase verification.
You do not need to bother with authorization scopes, making custom requests calls, refreshing access tokens, etc. the api client library takes care of everything. Here's a python library usage example to verify a subscription:
First, install the google api client in your pipenv like this:
$ pipenv install google-api-python-client
Then you can set up api client credentials using the private key json file for authenticating the service account.
credentials = service_account.Credentials.from_service_account_file("service_account.json")
Now you can verify subscription purchases or product purchases using the library, directly.
#Build the "service" interface to the API you want
service = googleapiclient.discovery.build("androidpublisher", "v3", credentials=credentials)
#Use the token your API got from the app to verify the purchase
result = service.purchases().subscriptions().get(packageName="your.app.package.id", subscriptionId="sku.name", token="token-from-app").execute()
#result is a python object that looks like this ->
# {'kind': 'androidpublisher#subscriptionPurchase', 'startTimeMillis': '1534326259450', 'expiryTimeMillis': '1534328356187', 'autoRenewing': False, 'priceCurrencyCode': 'INR', 'priceAmountMicros': '70000000', 'countryCode': 'IN', 'developerPayload': '', 'cancelReason': 1, 'orderId': 'GPA.1234-4567-1234-1234..5', 'purchaseType': 0}
The documentation for the platform service interface for the play developer API is not linked in an easy to find way, for some it is downright hard to find. Here are the links for the popular platforms that I found:
Python | Java | .NET | PHP | NodeJS (Github TS) | Go (Github JSON)
Complete example of using Google API Client Library for PHP:
Setup your Google Project and access to Google Play for your service account as described in Marc's answer here https://stackoverflow.com/a/35138885/1046909.
Install the library: https://developers.google.com/api-client-library/php/start/installation.
Now you are able to verify your receipt the following way:
$client = new \Google_Client();
$client->setAuthConfig('/path/to/service/account/credentials.json');
$client->addScope('https://www.googleapis.com/auth/androidpublisher');
$service = new \Google_Service_AndroidPublisher($client);
$purchase = $service->purchases_subscriptions->get($packageName, $productId, $token);
After that $purchase is instance of Google_Service_AndroidPublisher_SubscriptionPurchase
$purchase->getAutoRenewing();
$purchase->getCancelReason();
...
You can try using Purchases.subscriptions: get server-side. It takes packageName, subscriptionId and token as paramaters and requires authorization.
Checks whether a user's subscription purchase is valid and returns its
expiry time.
If successful, this method returns a Purchases.subscriptions resource in the response body.
I answer to this concern
the network connection is down or my own server is down, user just
paid the money in google play but I did not record the purchase in my
server? What should I do, How can I deal with this situation.
The situation is:
User purchases 'abc' item using google play service -> return OK -> fail to verify with server for some reasons such as no Internet connection.
Solution is:
On the client side, before showing the 'Google Wallet' button, you check if the 'abc' item is already owned.
if yes, verify with server again
if no, show the 'Google Wallet' button.
Purchase purchase = mInventory.getPurchase('abc');
if (purchase != null) // Verify with server
else // show Google Wallet button
https://developer.android.com/google/play/billing/billing_reference.html#getSkuDetails
Marc Greenstock's answer is definitely enlightening, a few things to pay attention though which took me a long time to figure out (at least way more time than I expected):
I had to check "Enable G Suite Domain-wide Delegation" on Service Account settings. Without this I kept getting this error: "The current user has insufficient permissions to perform the requested operation"
Image with Enable G Suite Domain-wide Delegation option checked
For testing purposes you can create a JWT token for your service account here, just don't forget to select RS256 Algorithm.
The public key is the "private_key_id" from your downloaded JSON file. It also has the following format:
-----BEGIN PUBLIC KEY-----
{private_key_id}
-----END PUBLIC KEY-----
The private key is the "private_key" from your downloaded JSON file
The required claims for the JWT generation are described here.
Confused about what exactly a JWT Token is and how it is assembled? Don't be ashamed, check this link. Odds are you are just like me and took a long time to bother looking for what exactly it is, it is (way) simpler than it looks.
I had some serious problems using the suggested google API python library, but implementing the communication from scratch is not so hard.
First of all you have to create a service account at Google Play Console as described in all answers and get the JSON file containing the private key. Save it to your server.
Then use the following code. No need to obtain the google API client library. You only need the following (very common) python libraries Requests and Pycrypto
import requests
import datetime
import json
import base64
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
jwtheader64 = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9"
#SERVICE_ACCOUNT_FILE: full path to the json key file obtained from google
with open(SERVICE_ACCOUNT_FILE) as json_file:
authinfo = json.load(json_file)
packageName = #your package name
product = #your inapp id
token = #your purchase token
#create the JWT to use for authentication
now = datetime.datetime.now()
now1970 = (now - datetime.datetime(1970,1,1)).total_seconds()
jwtclaim = {"iss":authinfo["client_email"],"scope":"https://www.googleapis.com/auth/androidpublisher","aud": "https://oauth2.googleapis.com/token","iat":now1970,"exp":now1970+1800,"sub":authinfo["client_email"]}
jwtclaimstring = json.dumps(jwtclaim).encode(encoding='UTF-8')
jwtclaim64 = base64.urlsafe_b64encode(jwtclaimstring).decode(encoding='UTF-8')
tosign = (jwtheader64+"."+jwtclaim64).encode(encoding='UTF-8')
#sign it with your private key
private = authinfo["private_key"].encode(encoding='UTF-8')
signingkey = RSA.importKey(private)
signer = Signature_pkcs1_v1_5.new(signingkey)
digest = SHA256.new()
digest.update(tosign)
signature = signer.sign(digest)
res = base64.urlsafe_b64encode(signature).decode(encoding='UTF-8')
#send it to Google authentication server to obtain your access token
headers = {'Content-Type': 'mapplication/x-www-form-urlencoded'}
payload = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion="+jwtheader64+"."+jwtclaim64+"."+res
r = requests.post("https://oauth2.googleapis.com/token",headers=headers,data=payload)
if r.status_code == 200:
authdata = json.loads(r.text)
accesstoken = authdata['access_token']
bearerheader = {'Authorization':'Bearer '+authdata['access_token']}
#Now you have at last your authentication token, so you can use it to make calls. In this example we want to verify a subscription
url = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications/"+packageName+"/purchases/subscriptions/"+product+"/tokens/"+token
subscription = requests.get(url,headers=bearerheader)
the network connection is down or my own server is down,
You don't have to think like this.
Client knows own's consume product. so, client can send all tokens back to the server.
Just re-check token with produce id and transaction id.
And Server checks consume product.
if you fail check
make UI button client can re-send token.
server re-check token for items.
It's done.

android get new token from google

I have a app in android which works with the google sheets API and write/reads from a spreadheet.
First time I run the app its all good - I get a token from the GoogleAuthUtil fetchToken method and I can make API calls (followed this page - http://developer.android.com/google/auth/http-auth.html).
After one hour, the token expires and I need to get a new one, and I read that it should be really easy with the google play services, since it handles the refreshing of the token.
The problem is - I don't know how to check if the token is valid, and if its not valid, how to get a new one.
I can't just get a new one, because I don't know if an hour passed since the last time I used the app, and I don't think I should try to get a new token everytime I launch the app.
If someone have any experience working with this, I would appreciate any help.
Been struggling with this for a while. just want to know how to check if token is valid, and if its not valid - how to get a new one!
thanks!

Android In-app purchase: how to consume?

I've implemented Google In-App Billing V3 in my app and i did my first test purchase. Now, as seen that i want it consumable, but if i click the "Purchase" button again i receive an error, i'm wondering how and where to insert "consumePurchase". I've been all day long on my computer searching on every thread, but i'm making confusion with old versions of the same. From what i saw, i need to call consumePurchase after the successfully purchased item AND when the activity is created, but i can't figure out how to do it.
Is this the one and only line of code?
int response = mService.consumePurchase(3, getPackageName(), token);
If so, what is "token"?
P.s. the consumable items are: 50, 150 and 300 coins that the user can buy to take a little advantage in the game.
Aaah, so confusing for me :/
As stated in the official documentetion: https://developer.android.com/google/play/billing/billing_reference.html
The response intent to the purchase includes several fields, one of them being:
INAPP_PURCHASE_DATA A String in JSON format that contains details
about the purchase order. See table 4 for a description of the JSON
fields.
Inside that JSON, you have several fields, also explained in that page, the one you are looking for is:
purchaseToken A token that uniquely identifies a purchase for a given
item and user pair.
All these is quite easy to follow from the official sample application, which I recommend you to download and try out, also to check the code.
Ok, i solved. Instead of using:
int response = mService.consumePurchase(3, getPackageName(), token);
follow this thread:
mService.consumePurchase(3, packageName, purchaseToken) always returns RESULT_DEVELOPER_ERROR = 5 - invalid arguments provided to the API

Categories

Resources