"Instance text" OAuth 2.0 for Web Server applications

Source: Internet
Author: User
Tags auth oauth readline response code stringbuffer

OAuth 2.0 for Web Server applications, verifying a user ' s Android In-app subscription


Before writing this article, let's say some digression. Some time ago game rush in Gooleplay on-line, Do you know if it's not safe to add a Auth2.0 check, or do you skip this step for a while, sure enough, a few days to find backstage records and players actually pay is not too consistent, suspect that there are players to steal brush games, and so on, and really walked through the googleplay of all the payment process to complete the redemption, time a long severity can be imagined. After consulting a large number of Google official documents to fill up the code, and record the use of OAuth 2.0 here, Google offers several uses of OAuth2.0, each using a different method, you can see this blog. Here only write OAuth 2.0 for Web Server applications, involving the acquisition and use of Refresh_token, Access_token, and how to send a get and post request to Google, Finally completes the user to pay the purchase information in the Android application the verification.

Google's official original text of the interpretation of the using OAuth 2.0 for Web Server applications is posted first:

The authorization sequence begins when your application redirects a browser to a Google URL; The URL includes query parameters that indicate the type of access being requested. As in the other scenarios, Google handles user authentication, session selection, and user consent. The result is a authorization code that which Google returns to your application in a query string.
After receiving the authorization code, your application can exchange the code (along with a client ID and client secret) For this access token and, in some cases, a refresh token.
The application can then use the access token to access a Google API.
If A refresh token is present in the authorization Code exchange, then it can be used to obtain new access tokens at any T Ime. This is called offline access, because the user does not have to be present at the browser when the application obtains a New access token.

Through the original and the illustrations we can know such a process (detailed below):

A. Create a WEB application account in Google Developer console, get Client_id,client_secret and Redirect_uri, which are commonly used in the following steps (this is the premise).

Two. Get Authorization code

Three. Using code to obtain Access_token,refresh_token

Four. Further use of Refresh_token to acquire new Access_token

Five. Use Access_token to invoke Google API to achieve the ultimate goal (if Access_token obsolete, go back to step fourth)

Note: In the third step, when we first use code to obtain Access_token, Google will return to you at the same time Refresh_token, later again with the code to get Access_token operation will not see Refresh_token , so be sure to save it. This refresh_token is long-term effective, if there is no clear application Manager revocation is not expired, and Access_token is only 3,600 seconds of time, that is 1 hours, then the problem, Access_token and Refresh_ Token what is the relationship. Obviously, we are going to use Access_token to invoke Google API, and Access_token has limitation, so when Access_token expires, we can use a long lasting refresh_token to get Access_ token, and can be acquired at any time, without limitation of number of times. In fact, when we get Refresh_token, it's a turning point.

The following detailed decomposition steps:

First, create a Web application account in Google Developer console

(Here is a new version of the Google Developer console page, which can be set in the account settings to display in Chinese ~)

4 of them are free to fill in. After the creation is complete, you can look at the following image:



Here we get 3 key parameters: Client_id,client_secret,redirect_uris, in the bottom step.

There may be some doubt as to how the project created at Google Developer Console is linked to Android apps on the GooglePlay line. Why you can use these parameters to Access_token to invoke the Google API. In fact, when GooglePlay publish the application on the operation of Associated project, then the person who created project can give other Google account authorization, so that other Google accounts can be on their own developer console page directly see the project and the following Web Application and so on, and in the next step in the operation of their Google account to obtain code.


two. Get Authorization Code

Https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher
& Response_type=code
&access_type=offline
&redirect_uri={redirect_uris}
&client_id={ CLIENT_ID}

We need to open this URL in the form of a browser, and you will be prompted to sign in with your Google accounts, and then log on with project-authorized Google Account, and the address bar will appear with the code we need. For example: https://www.example.com/oauth2callback?code=4/CpVOd8CljO_ Gxtre1m5jtwefwf8grd44vrmkndi4gss.kr-ghused-ozenp6uadfxm0e0md3flai


Three. Using code to obtain Access_token,refresh_token

Https://accounts.google.com/o/oauth2/token?
Code={code}
&client_id={client_id}
&client_secret={client_secret}
&redirect_uri={ REDIRECT}
&grant_type=authorization_code

Our goal in this step is to obtain refresh_token, as long as this long-lasting Token,access_token is readily available, the first request of the JSON string is as follows, the next request will no longer appear refresh_token, to save. Expires_in refers to the prescription of Access_token, which is 3,600 seconds.

{"
    access_token": " Ya29.3gc2jw5vm77ypkylq0h5spjejjdhx93kq8qzhrjamlknwj85595emogl300xkdoei7zisdefepy6zg ", 
    " Token_ Type ":" Bearer ", 
    " expires_in ": 3600, 
    " Refresh_token ":" 1/ Fbqd448cddpfdedpcy4gj_m3wdr_m0u5wupquxl_o "
}

Four. Further use of Refresh_token to acquire new Access_token

Https://accounts.google.com/o/oauth2/token?
Grant_type=refresh_token
&client_id={client_id}
&client_secret={client_secret}
& Refresh_token={refresh_token}

Here we want to launch a POST request to Google, the Java code is as follows:

	/** get Access_token **/private static map<string,string> Getaccesstoken () {final String client_id = "Fill in your Client_
		ID ";
		Final String Client_secret = "Fill in your Client_secret";
		Final String Refresh_token = "Fill in the Refresh_token obtained in the previous step";
		Map<string,string> map = null; try {/** * https://accounts.google.com/o/oauth2/token?refresh_token={refresh_token} * &client_id= {client_id}&client_secret={client_secret}&grant_type=refresh_token */url urlgettoken = new URL ("http
		    S://accounts.google.com/o/oauth2/token ");
		    HttpURLConnection Connectiongettoken = (httpurlconnection) urlgettoken.openconnection ();
		    Connectiongettoken.setrequestmethod ("POST");
		    Connectiongettoken.setdooutput (TRUE);
		    Start transfer parameter OutputStreamWriter writer = new OutputStreamWriter (Connectiongettoken.getoutputstream ());
		    Writer.write ("refresh_token=" +refresh_token+ "&"); 
		    Writer.write ("client_id=" +client_id+ "&"); Writer.write ("clIent_secret= "+client_secret+" ("&"); 
		    Writer.write ("Grant_type=refresh_token");
		    Writer.close (); If the response code is 200, the request succeeds if (connectiongettoken.getresponsecode () = = HTTPURLCONNECTION.HTTP_OK) {StringBuilder SB = n
		    	EW StringBuilder (); 
		    	BufferedReader reader = new BufferedReader (New InputStreamReader (Connectiongettoken.getinputstream (), "Utf-8"));
		    	String strLine = "";
		    	while ((StrLine = Reader.readline ())!= null) {sb.append (strLine);
		    	//Get Google Feedback (JSON format) jsonobject Jo = Jsonobject.fromobject (sb.tostring ()); 
		    	String Access_token = jo.getstring ("Access_token");
		    	Integer expires_in = Jo.getint ("expires_in");
		    	Map = new hashmap<string,string> ();
		    	Map.put ("Access_token", Access_token);
		    	Map.put ("Expires_in", String.valueof (expires_in));
		    	The creation time brought into the Access_token, used to determine whether or not to be invalidated map.put ("Create_time", String.valueof (New Date (). GetTime ())/1000); Logger.info ("containsThe JSON information for Access_token is: "+jo";
			The catch (Malformedurlexception e) {logger.error ("Get Access_token failed because:" +e);
		E.printstacktrace ();
			catch (IOException e) {logger.error ("Get Access_token failed because:" +e);
		E.printstacktrace ();
	} return map; }

Five. Use Access_token to invoke Google API to achieve the ultimate goal (if Access_token obsolete, go back to step fourth)

What I need to get here is the purchase information I paid to GooglePlay in the application, which contains the following attributes: (refer to Purchases.products under Google Play Developer API)

A productpurchase resource indicates the status of a user ' s Inapp product purchase.

{
"kind": "Androidpublisher#productpurchase", "
purchasetimemillis": Long,
"purchasestate": Integer, ( purchased:0  Cancelled:1, we are relying on this judgment to purchase information)
"consumptionstate": Integer,
"Developerpayload": String
}
To initiate a GET request to GOOGLEAPI with the Access_token parameter, the Java code is as follows:

	private static map<string,string> Cachetoken = null;//Set static variable to determine if Access_token expires public static googleplaybuyent
			ity getinfofromgoogleplayserver (String packagename,string productId, string purchasetoken) {if (null!= cachetoken) { Long expires_in = long.valueof (Cachetoken.get ("expires_in")); Effective time Long create_time = long.valueof (Cachetoken.get ("Create_time"));
			Access_token was created long now_time = (new Date (). GetTime ())/1000;
			if (Now_time > (create_time + expires_in-300)) {//Five minutes in advance to regain access_token Cachetoken = Getaccesstoken ();
		}}else{Cachetoken = Getaccesstoken ();
		String Access_token = Cachetoken.get ("Access_token");
		Googleplaybuyentity buyentity = null;
			 Try {/** This is the latest API,V2 version of the time when this blog was written. * Https://www.googleapis.com/androidpublisher/v2/applications/{packagename} */purchases/products/{productid}/ Tokens/{purchasetoken}?access_token={access_token} */String URL = "https://www.googleapis.com/androidpublisher/v2/ AppliCations ";
			StringBuffer GetURL = new StringBuffer ();
			Geturl.append (URL);
			Geturl.append ("/" + PackageName);
			Geturl.append ("/purchases/products");
			Geturl.append ("/" + productId);
			Geturl.append ("/tokens/" + Purchasetoken);
			Geturl.append ("? access_token=" + Access_token);
			URL urlobtainorder = new URL (geturl.tostring ());
			HttpURLConnection Connectionobtainorder = (httpurlconnection) urlobtainorder.openconnection ();
			Connectionobtainorder.setrequestmethod ("get");
		    Connectionobtainorder.setdooutput (TRUE); If the authentication succeeds if (connectionobtainorder.getresponsecode () = = HTTPURLCONNECTION.HTTP_OK) {StringBuilder sblines = NE
				W StringBuilder (""); 
				BufferedReader reader = new BufferedReader (New InputStreamReader (Connectionobtainorder.getinputstream (), "Utf-8"));
				String strLine = "";
				while ((StrLine = Reader.readline ())!= null) {sblines.append (strLine); //Put the information retrieved above into Jsonobject to facilitate our direct access to the desired parameters jsonobject Jo = Jsonobject.Fromobject (Sblines.tostring ());
				Integer status = Jo.getint ("Purchasestate");
					if (status = = 0) {//verify success buyentity = new Googleplaybuyentity ();
					Buyentity.setconsumptionstate (Jo.getint ("consumptionstate"));
					Buyentity.setdeveloperpayload (jo.getstring ("Developerpayload"));
					Buyentity.setkind (jo.getstring ("kind"));
					Buyentity.setpurchasestate (status);
				Buyentity.setpurchasetimemillis (Jo.getlong ("Purchasetimemillis"));
					}else{//Purchase Invalid buyentity = new googleplaybuyentity ();
					Buyentity.setpurchasestate (status);
				Logger.info ("Check failure from GooglePlay bill, because Purchasestatus is" + status);
			A catch (Exception e) {e.printstacktrace ());
			buyentity = new Googleplaybuyentity ();
		Buyentity.setpurchasestate (-1);
	return buyentity; }

It's finished here, if you have any questions, you can leave a message.

In addition, iOS apps are paid in, Apple Stores store app purchase information check blog here:http://blog.csdn.net/hjun01/article/details/44039939




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.