I implemented in-app billing in my mobile app. It uses auto renewing subscription. I want to check the subscription expiry date through the app. I found this link to check the subscription details : Purchases.subscriptions:get
The documentation shows that some authorization needed. I have tried but I am not able to get the result. I got client secret.json file but it does not contain client secret Id. So please help me to get the subscription expiry date.
My answer is late, but maybe it helps somebody else. See my answer here: Server side authorization with Google Play Developer API?
And these are the steps when you would do it manually:
1.) Create credentials in your OAuth2 configuration in Google API with the following link: https://developers.google.com/mobile/add?platform=android&cntapi=signin&cnturl=https:%2F%2Fdevelopers.google.com%2Fidentity%2Fsign-in%2Fandroid%2Fsign-in%3Fconfigured%3Dtrue&cntlbl=Continue%20Adding%20Sign-In
2.) Go to your Developer API console. If you have done the first step correct, the result should look like something like that:
3.) Go to Google Play Developer Console -> All Apps -> Settings -> API Access and link the project you defined in Developer API Console (step 2, black bar top left). (If you can't link your project in Google Play, because you didn't find some, you used different google accounts for Google Developer API and Google Play Developer Console.)
4.) Invoke the following link with your callback url:
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_type=code&access_type=offline&redirect_uri=http://www.yourdomain.com/oauth2callback&client_id=[WEBAPPLICATION_ID_FROM_ABOVE.apps.googleusercontent.com]
My /oauth2callback script is a simple php script. (This is not production safe. It's just for illustration):
oauth2callback.php
<?php
print_r($_REQUEST);
?>
5.) After you invoked the url from above, you will be asked for your google account and allowance to access the api. After you confirmed, you will be redirected to your callback url and get a result which looks like this:
4/vPv_eYX-az6YucwdpBzATpJEu8129gN9aYsUIMI3qgQ
6.)ยน Get an oauth2 access token and refresh token by invoking a POST request to https://accounts.google.com/o/oauth2/token with the following headers:
grant_type=authorization_code
code=4/vPv_eYX-az6YucwdpBzATpJEu8129gN9aYsUIMI3qgQ
client_id=[YOUR_WEBAPPLICATIONID.apps.googleusercontent.com]
client_secret=[YOUR CLIENT SECRET OF THIS WEBAPPLICATION ID]
redirect_uri=http://www.yourdomain.com/oauth2callback
(The client secret can be found when you click on the Web Client ID of the OAuth2 client IDs in the Developer Console from step 2)
The result will look like this:
{
"access_token": "ya29.GdsCBbnM584k3SUzoxDgIdaY26pEM_p_AdhkIkFq3tsai8U7x8DuFKq3WEF7KquxkdLO89KHpuUFdJOgkhpGbGyDfxkD32bK1ncnsu2IkA0e_5ZayOEr86u4A1IN",
"expires_in": 3600,
"refresh_token": "1/U5HF1m0nHQwZaF2-X35f_xyFaSOofdw3SEubnkkYUQ0",
"token_type": "Bearer"
}
7.) The access token is needed to invoke the Google Developer API requests, for example: https://www.googleapis.com/androidpublisher/v2/applications/[packageName]/purchases/subscriptions/subscriptionId/tokens/[purchaseToken]?access_token=ya29.GdsCBbnM584k3SUzoxDgIdaY26pEM_p_AdhkIkFq3tsai8U7x8DuFKq3WEF7KquxkdLO89KHpuUFdJOgkhpGbGyDfxkD32bK1ncnsu2IkA0e_5ZayOEr86u4A1IN
8.) The access token expires very quickly. With the refresh you can fetch new access tokens by using the following url and headers:
POST https://accounts.google.com/o/oauth2/token
grant_type=refresh_token
client_secret=[YOUR CLIENT SECRET]
refresh_token=1/U5HF1m0nHQwZaF2-X35f_xyFaSOofdw3SEubnkkYUQ0
client_id=[YOUR_WEBAPPLICATION_ID.apps.googleusercontent.com]
Result:
{
"access_token": "ya29.GlsCBZuN7hYJILi5VaVggIsCIb1_5feGvcjvQFmJRnPYXsnhsi_w3Md87tQwGd_WXmifo4s5739c3IU5INPmby8q64k0LdDFkO2JpNRG13K9sizvU1Sc-3cWzbf8",
"expires_in": 3600,
"token_type": "Bearer"
}
HINT (1): If you don't get a refresh token from the request of step 6, attach the following query params to your request: prompt=consent
I also struggled a bit with this, but at least I found what needs to be done.
Google provides an android library google-api-services-androidpublishe that can be used to access the Purchase.Subscription.Get API.
implementation 'com.google.apis:google-api-services-androidpublisher:v3-rev74-1.25.0'
Here is a Kotlin code example:
import com.google.api.client.http.apache.ApacheHttpTransport
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.androidpublisher.AndroidPublisher
...
fun retrieveSubscriptionInfo(sku: String) {
val packageName = ""
val sku = ""
val purchasedSubscriptionToken = ""
val apacheHttpTransport = ApacheHttpTransport()
val jacksonJsonFactory = JacksonFactory.getDefaultInstance()
val AndroidPublisher.Builder(apbacheHttpTransport, jacksonJsonFactory, null).build()
val request = publisher.Purchases().subscriptions().get(packageName, sku, purchasedSubscriptionToken);
return request.execute()
}
Note that before the above code is executed you must first Authorize the AndroidPublisher. You would have to request the users permission in order to be able to query the Purchase.Subscription.Get
Hope that this is helpful.
Google's documentation here is horrible, no clear examples of implementation. I finally found the answer after a LOT of Googling thanks to #Sabeeh's answer here and lots of other snippets spread out online.
1. First step is to add the dependencies:
implementation "com.google.apis:google-api-services-androidpublisher:v3-rev142-1.25.0" // Update based on latest release
implementation "com.google.auth:google-auth-library-oauth2-http:1.12.1" // Update based on latest release
2. Follow these steps to link the Google Play Console with Google Play Developer API (choose the "Use a service account", not "Use OAuth clients" and follow until "Additional information").
3. Download the services JSON file from your Google Cloud service account (click on the account that you set up in the previous step). You can find/create this file under the "Manage Keys" action or the "Keys" tab. Add the exported JSON file in your assets folder in Android
4. Then you can call the Google Play Developer API to query subscriptions like this (important to call from a Thread, didn't work from the UI thread, not sure why):
new Thread(() -> {
InputStream inputStream = context.getAssets().open("service_account_google_play.json"); // JSON file from step 3
GoogleCredentials credentials = GoogleCredentials.fromStream(inputStream)
.createScoped(AndroidPublisherScopes.ANDROIDPUBLISHER);
AndroidPublisher androidPublisher = new AndroidPublisher(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credentials)
);
SubscriptionPurchase purchase = androidPublisher.purchases().subscriptions().get(
context.getPackageName(), subscriptionId, purchaseToken
).execute();
// Do with the purchase object what you want here
}).start();
At the risk of being overly descriptive, the subscriptionId is the ID of your subscription in the Play Console (e.g. subscription_monthly or whatever you called it), and the purchaseToken is the token you get from the Purchase token after querying the BillingClient (querying subscriptions is explained in detail here).
Let me know if anything is unclear or doesn't work yet. This took me 6 hours to figure out and I'm happy to save others that pain.
Related
I am trying to implement Android Management API in my project where the first step is to create an enterprise:
Post the Callbackurl and ProjectID to the Following URL
https://androidmanagement.googleapis.com/v1/signupUrls
I get the response name and url:
{
"name": "signupUrls/C265d41bc093bdd97",
"url": "https://play.google.com/work/adminsignup?token=someToken"
}
How can I Change this "url" parameter to my own. Do I require to upload my DPC to playstore?
I am out of guesses. please help
Thanks in advance.
The flow is this:
1) Create a Project in Google developer console, enable Android Management API, create credentials and get the project id. (I think you already done that).
2) Create a SignupUrl with signupUrls.create. (What you have done to get that JSON)
3) Keep the SignupUrl Name and redirect the user (or go) to the returned URL (inside the JSON posted).
3) Follow the procedure to create an enterprise.
This will start the creation of an enterprise to the signed Google Account.
4) At the end of the procedure you will be redirected to the callbackUrl specified inside signupUrls.create. Appended to the callbackUrl, as a GET query parameter, will be a token.
5) You must use the appended token to conclude the flow calling the API enterprises.create with these parameters:
The signup url name
The enterprise token returned as parameter
(optional) a request body with some enterprise parameters (logo, name, etc)
At the end of this coming and going between URLs and API calls, you will end with an Enterprise created on the Google Account and the enterprise ID in the form enterprise/<yourID> to interact with the API.
You can check all the Enterprise infos at the created Google Play for Work (or Managed Google Play) at http://play.google.com/work . Left menu "Administration Settings" at check your enterpriseId.
I'm writing an Android application that needs access to Google's Calendar API. I'd like to avoid using the Google API Client Library in favor of a simple Retrofit REST implementation. However, I can't seem to get the right authorization credentials in order to complete Calendar API REST calls. In my app, I sign in successfully with the following options:
GoogleSignInOptions
.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Scope("https://www.googleapis.com/auth/calendar"))
.requestEmail()
.requestIdToken("WEB CLIENT ID HERE")
.build()
And I end up with a GoogleSignInAccount that gives me access to an idToken property. I've tried using this idToken as an OAuth 2.0 Bearer token in the authorization header of my request to the Calendar API, but I get rejected with a 401 every time. There's a lot of documentation around Google's OAuth process that seems to contradict itself or has escaped being updated, but it makes things very confusing. Any ideas about what I need to do in order to be able to use the REST APIs from my Android application?
Thanks, for the answer, I in-between managed to find out how to use the GoogleSignInAccount to authenticate the API-requests.
After you successfully signed in to your account using the google_sign_in plugin
(see the example for help) you can get the authentication headers that are required for the authentication of your api-request directly from the GoogleSignInAccount.
See:
GoogleSignInAccount _currentUser;
Future<Map<String, dynamic>> _getLabels() await {
http.Response _response = await http.get(
'https://www.googleapis.com/gmail/v1/users/'+_currentUser.id+'/labels',
headers: await currentUser.authHeaders,
);
return jsonDecode(_response);
}
authHeaders is implemented in Dart only, the source can be checked at https://pub.dev/documentation/google_sign_in/latest/google_sign_in/GoogleSignInAccount-class.html .
So the authHeaders are as follows:
"Authorization": "Bearer $accessToken",
"X-Goog-AuthUser": "0",
Now how can I obtain accessToken? Dart is calling GoogleSignInPlatform.instance.getTokens(email, shouldRecoverAuth: true); the impl of that method can be found here: https://github.com/flutter/plugins/blob/master/packages/google_sign_in/google_sign_in_platform_interface/lib/src/method_channel_google_sign_in.dart#L50
Aaaaand I'm giving up on this Google crap:
There is this magical chapter Obtain an access token from the Google Authorization Server. which says absolutely nothing on how to obtain access token. A prime example of shitty chatty useless doc that Google produces en masse.
The docu further sends me to https://developers.google.com/identity/sign-in/android/ which still doesn't explain how to get the accessToken.
That doc portal sends me to https://developers.google.com/identity/sign-in/android/start?authuser=2 which again talks web client instead of Android client, and I'm powerless. My limbs stop to move, my brain melts, my mouth opened in an endless silent scream of horror. This is how hell must look like. Reading Google docs is how hell must look like.
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.
I need to verify on my server each Android purchase that was made before by user in my Android APP.
I though that working with google-api-php-client it would be easy the authentication and managing of the token in server. But there aren't any sample, and yesterday Google published new version 0.6.3 providing in-app-purchases service.
I followed -> *code.google.com/p/google-api-php-client/wiki/OAuth2#Service_Accounts*
On my code.google.com/apis/console/ I pushed on, "Google Play Android Developer API" and I configured the "service account" in API Access.
From Android client APP, server recives the PACKAGE_NAME, PRODUCT_ID and purchase TOKEN.
My server code is the following:
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_AndroidpublisherService.php';
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'asdf.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = 'asdf#developer.gserviceaccount.com';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '../../asdf/privatekey.p12';;
$client = new Google_Client();
$client->setApplicationName({APP_PACKAGE_NAME});
// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/androidpublisher'),
$key)
);
$client->setClientId(CLIENT_ID);
$service = new Google_AndroidPublisherService($client);
$res = $service->inapppurchases->get({APP_PACKAGE_NAME},{APP_PACKAGE_NAME.PRODUCT_ID}, {PURCHASE_TOKEN});
var_dump($res);
The error showed is:
Google_ServiceException: Error calling GET https://www.googleapis.com/androidpublisher
/v1.1/applications/{APP_PACKAGE_NAME}/inapp/{APP_PACKAGE_NAME.PRODUCT_ID}/purchases
/{PURCHASE_TOKEN}: (401) This developer account does not own the application. in
/.../google-api-php-client/src/io/Google_REST.php on line 66 Call Stack: 0.0201
266376 1. {main}() ............
Token is correct, and I'm working with the same account in Google API Console(https://code.google.com/apis/console) and Google Developer Console (https://play.google.com/apps/publish/). I'm only using Service account api, and don't working with Client ID for web applications, and Simple API Access. For security I changed here some code values.
Could somebody help me to know what's wrong on my purchase server verification using Google API please?How I know the owner of my app? Have something to do with Google Apis new project, project domain, project number, project ID, etc...?
I think my problem was because I was trying to use Service Accounts with a Google Apps Gmail own account ( non #gmail.com account ).
I had to delegate domain-wide authority to my service account.
And I had to instantiate a Android Publisher Service as follows: ( only founded in Google Api Drive documentation ).
I added "sub" parameter programmatically in Google_AssertionCredentials like follows:
$auth = new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
'https://www.googleapis.com/auth/androidpublisher',
$key);
$auth->sub = "myown#email.com";
$client->setAssertionCredentials($auth);
The documentation in Google Play Android Developer API is very poor, and Google Support doesn't help, they redirects you to documentation. Google PHP developers even don't know how Service Accounts works.
In spite of having found the answer by myself, Google needs to improve all new Google Play In-app Billing API version 3.
I am making an app that does not require a user account/login, and allows the user to purchase a subscription. I want to use the Google Play Developer API to verify whether or not a user has a purchased/active subscription. From all of the documentation, I've gathered the following steps.
Are they correct, and could you answer the two questions in them?
Create a Service Account in the Google APIs Console.
Save the private key that is given to me (where? surely not in my code/on the device as this sample code suggests)
Use Google APIs Client Library for Java to create and sign a JWT with the private key (how? the docs give me this, but that is not Java code... What do I do with it?)
Construct an access token request, and get access to the API
Application can now send a GET request to the API to find out whether or not the
user has a subscription
When the access token expires, go back to step 3.
Also, I have a web service, though I know nothing about web services or web service programming... I only know enough to be aware that it is probably necessary to use here.
EDIT: These steps were not correct. See my answer below for the correct steps. However, note that this only applies to using a service account (because I did not want to require a user to have to explicitly allow API access)
As it turns out, my steps were not correct. It took me weeks to figure this out and it doesn't seem to be documented anywhere else. You're welcome:
Create a Web Application account in the Google APIs Console. Put any website as a "redirect URI"; it doesn't matter since you will not really be using it. You will get a client id and client secret when you create the account.
In a browser on your computer go to https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_type=code&access_type=offline&redirect_uri=[YOUR REDIRECT URI]&client_id=[YOUR CLIENT ID] and allow access when prompted.
Look in the address bar. At the end of the URI you entered originally will be your refresh token. It looks like 1/.... You will need this "code" in the next step. The refresh token never expires.
Convert this "code" to a "refresh token" by going to https://accounts.google.com/o/oauth2/token?client_id=[YOUR CLIENT ID]&client_secret=[YOUR CLIENT SECRET]&code=[CODE FROM PREVIOUS STEP]&grant_type=authorization_code&redirect_uri=[YOUR REDIRECT URI]. You can save the resulting value right in your program; it never expires unless explicitly revoked. (this step inserted by #BrianWhite -- see comments)
Make sure you are using POST.(inserted by Gintas)
In your code, send an HttpPost request to https://accounts.google.com/o/oauth2/token with the BasicNameValuePairs "grant_type","refresh_token", "client_id",[YOUR CLIENT ID], "client_secret",[YOUR CLIENT SECRET], "refresh_token",[YOUR REFRESH TOKEN]. For an example look here. You will need to do this in a separate thread, probably using AsyncTask. This will return a JSONObject.
Get the access token from the returned JSONObject. For an example look here. You will need to get the string "access_token". The access token expires in 1 hour.
In your code, send an HttpGet request to https://www.googleapis.com/androidpublisher/v1/applications/[YOUR APP'S PACKAGE NAME]/subscriptions/[THE ID OF YOUR PUBLISHED SUBSCRIPTION FROM YOUR ANDROID DEVELOPER CONSOLE]/purchases/[THE PURCHASE TOKEN THE USER RECEIVES UPON PURCHASING THE SUBSCRIPTION]?accesstoken="[THE ACCESS TOKEN FROM STEP 4]". For an example look here.
.NET Users: I hope this answer saves someone a ton of grief.
As #Christophe Fondacci noted on 2015, the accepted solution worked great a few years ago.
Now it's 2017 2020 and the process is far easier and faster.
My use case is to validate in-app subscriptions, where my mobile app sends subscription purchase information to my RESTful server, which in turn contacts Google to validate a subscription purchase.
The strategy is to create a Service Account that will operate on your behalf.
Sign into your Google Play Dev Console and click the app you're setting up.
Visit Settings->API access
Under Service Accounts, hit the Create Service Account button.
As of Jan 2017 a dialog with directions on setting up a service account appears. The dialog takes you to the Google API Console; from there,
A) Click Create Service Account
B) Create the service account name that makes sense. Since we're interested in accessing Android Publisher Services, I chose "publisher".
C) For Role, just choose something - you can change this later.
D) Choose "Furnish New private key" and choose P12 for .Net implementations. Don't lose this file!
Now you're done with #4, you'll see your new Service Account listed; click "Grant Access" to enable it.
Tap on the link to "View permissions". You should modify permissions based on your needs and API.
To validate in-app purchases, visit the Cog->Change Permissions and enable the GLOBAL "Visibility" and "Manage Orders" permissions.
OK at this point you have configured everything on Google's end. Now to setup your server to server stuff. I recommend creating
a .Net Console App to test out your implementation then offload it where needed.
Add the Android Publisher Client Library from Nuget[1]
PM> Install-Package Google.Apis.AndroidPublisher.v3
Add the P12 file to your project root
Change the P12 Properties so "Build Action" is "Content" and "Copy To Output Directory" to "Copy if newer".
Implement something like this to test your access and fine tune [1] .
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Services;
using Google.Apis.Auth.OAuth2;
using Google.Apis.AndroidPublisher.v3;
...
public Task<SubscriptionPurchase> GetSubscriptionPurchase(string packageName, string productId, string purchaseToken)
{
var certificate = new X509Certificate2(
"{{your p12 file name}}",
"{{ your p12 secret }}",
X509KeyStorageFlags.Exportable
);
var credentials = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer("{{ your service account email }}")
{
Scopes = new[] { AndroidPublisherService.Scope.Androidpublisher }
}.FromCertificate(certificate));
var service = new AndroidPublisherService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "my server app name",
});
return service.Purchases.Subscriptions.Get(packageName, productId, purchaseToken).ExecuteAsync();
}
Good luck, hope this helps someone.
Sources:
Using OAuth 2.0 for Server to Server Applications
.Net Client Library for Google.Apis.AndroidPublisher.v3[1]
1 Updated 04/11/2020 - Google.Apis.AndroidPublisher.v2 EOL'd, use Google.Apis.AndroidPublisher.v3.
If you are like me, and want to do this in PHP, here is the procedure how to do it... Thanks to Kalina's answer it took me only three days to work out how it works :).
Here goes:
go to google developers console https://console.developers.google.com/ and create a web app. Put 'developers.google.com/oauthplayground'as a "redirect URI"; You will use it in step 2. You will get a client id and client secret when you create the account. Make sure you have the Google Play Android Developer API added.
go to the Google oauth2 playground https://developers.google.com/oauthplayground/. This great tool is your best friend for the next few days.
Now go to settings : make sure Use your own OAuth credentials is set. Only then you can fill in your client ID and client secret in the form below.
In Google oauth2 playground go to step 1 Select & authorize APIs fill in the scope in the input field https://www.googleapis.com/auth/androidpublisher. I couldnt find the Google Play Android Developer API in the list, maybe they will add some time later. Hit AUTORIZE APIS. Do the authorisation thing that follows.
In Google oauth2 playground go to step 2 Exchange authorization code for tokens. If all went well you will see a authorization code starting with /4. If something didnt go well check the error message on the right. Now you hit 'refresh access token'. Copy the Refresh token... it will start with /1...
Now you can always get an access token! here is how:
$url ="https://accounts.google.com/o/oauth2/token";
$fields = array(
"client_id"=>"{your client id}",
"client_secret"=>"{your client secret}",
"refresh_token"=>"{your refresh token 1/.....}",
"grant_type"=>"refresh_token"
);
$ch = curl_init($url);
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_POST,count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post
$lResponse_json = curl_exec($ch);
//close connection
curl_close($ch);
Now you have an ACCESS TOKEN hooray... the JSON will look like this:
"access_token" : "{the access token}", "token_type" : "Bearer", "expires_in" : 3600
Finally you're ready to ask google something! Here is how to do it:
$lAccessToken = "{The access token you got in}" ;
$lPackageNameStr = "{your apps package name com.something.something}";
$lURLStr = "https://www.googleapis.com/androidpublisher/v1.1/applications/$lPackageNameStr/subscriptions/$pProductIdStr/purchases/$pReceiptStr";
$curl = curl_init($lURLStr);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curlheader[0] = "Authorization: Bearer " . $lAccessToken;
curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader);
$json_response = curl_exec($curl);
curl_close($curl);
$responseObj = json_decode($json_response,true);
The JSON returned will contain two timestamps, the initiationTimestampMsec and validUntilTimestampMsec the time the subscription is valid. Both are the nr of millisecs to add to the date 1/1/1970!
I don't know in 2012, but in 2015 you should not do any of these steps manually. I had a very hard time to find the documentation so I am posting here in case it helps anyone.
You should only query in-app purchases from your server for security reasons as otherwise you can trust none of the 2 ends of the purchase process.
Now on the server side (I think you could still use the same code from your app if you absolutely need to), include the google-api-services-androidpublisher client library to your project (see https://developers.google.com/api-client-library/java/apis/androidpublisher/v1)
As you mentioned, you need a service account with a P12 file (the client library only accept P12 file).
Then the following code will authenticate and get purchase information nicely:
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = new JacksonFactory();
List<String> scopes = new ArrayList<String>();
scopes.add(AndroidPublisherScopes.ANDROIDPUBLISHER);
Credential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
.setServiceAccountId(googleServiceAccountId)
.setServiceAccountPrivateKeyFromP12File(new File(googleServicePrivateKeyPath))
.setServiceAccountScopes(scopes).build();
AndroidPublisher publisher = new AndroidPublisher.Builder(httpTransport, jsonFactory, credential).build();
AndroidPublisher.Purchases purchases = publisher.purchases();
final Get request = purchases.get(packageName, productId, token);
final SubscriptionPurchase purchase = request.execute();
// Do whatever you want with the purchase bean
Information on Java client authentication can be found here:
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
I may misunderstand your question, but I don't see a reason for you to be using the links you're referencing to get In-App Billing for an Android app working. This page is much more helpful:
http://developer.android.com/guide/google/play/billing/index.html
You can try out the demo application they include (Dungeons -- http://developer.android.com/guide/google/play/billing/billing_integrate.html#billing-download). That uses products (one-time purchases) rather than subscriptions, but you should be able to modify to test for what you want.
I think the key, for you, would be the restoreTransactions method they provide in the sample to see if the Google Play account has any subscriptions for your app:
#Override
public void onRestoreTransactionsResponse(RestoreTransactions request, int responseCode) {
if (responseCode == BillingVars.OK) {
// Update the shared preferences so that we don't perform a RestoreTransactions again.
// This is also where you could save any existing subscriptions/purchases the user may have.
SharedPreferences prefs = getSharedPreferences(my_prefs_file, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(DB_INITIALIZED, true);
edit.commit();
} else {
Log.e(TAG, "RestoreTransactions error: " + responseCode);
}
}
If anyone is having issues with the accepted posts final step (#7), i found ?access_token= to work instead of ?accessToken=
Too bad stack overflow won't let me make that comment directly to the thread...
As you have a web service which your app can call, I would recommend storing your private key securely on your server. You should look to moving as much of the in-app stuff to service calls, as possible, see this link. I've implemented in-app subscription, but it was before this part of the API was out. I had to do my own registration and security verification but it looks like this API does most of that for you, using OAuth, although it looks like you are still responsible for storing the subscription request/verification.
Where it talks about signing your JWT's with an existing library, they do appear to provide you with links to a java library, a Python library and a PHP library - it depends what your web service or server component is written in (mine is C#, so I'm using RSACryptoServiceProvider) to verify signed purchases. They're using JSON objects for the actual transfer of data.