Android Integrated micro-Letter login steps Detailed _android

Source: Internet
Author: User
Tags getmessage openid sapi unique id csrf attack

First, write in the OnCreate of application:

Generalappliction.java public
static Iwxapi SApi;
@Override public
void OnCreate () {
 super.oncreate ();
 SApi = Wxentryactivity.initweixin (this, appconst.weixin_app_id);
}

Add in places where you need to sign in:

Mainactivity.java
wxentryactivity.loginweixin (Mainactivity.this, GENERALAPPLICTION.SAPI);

Three, the following specific integration steps to do a detailed description.

Integration steps:

1, in the open platform registration to create applications, apply for login rights

2, download the SDK, copy the relevant documents to the project engineering directory

3, global initialization of micro-trust components

4. Request authorization to login, get code

5, through the code to obtain authorization password Access_token

6, in the 5th step to determine whether the existence and expiration of Access_token

7, if the Access_token expiration is invalid, uses the Refresh_token to refresh

8, using Access_token to obtain user information

1. Register to create applications on open platform, apply for logon rights

In fact, this step is not how to say, can not be on the micro-trust open platform to register an account, and then create mobile applications.

You need to be aware that the part that applies the signature

To apply the signature here I am using the MD5 of the key on the line, and I can look at the problem that needs to be noticed: The signature summary of Android

2. Download SDK, copy related files to Project engineering catalogue

Development Kit (SDK) Downloads: libraries and files that can be used to share, login, collect, pay, etc.

Sample Demo

Download the Libammsdk.jar file to the AS Project Libs directory, and the example demo in the source file directory of the Wxapi directory of the entire copy into the Engineering directory of SRC under the root package:

If the Wxapi folder is not in the right place to log in, the micro-mail SDK cannot find the activity authorization feature for the login. Then add in Manifest.xml:

<activity 
 android:name= ". Wxapi. Wxentryactivity " 
 android:theme=" @android: Style/theme.translucent.notitlebar "
 android:configchanges=" Keyboardhidden|orientation|screensize "
 android:exported=" true "
 android:screenorientation=" Portrait "/ >

3. Global initialization of micro-trust components

Global initialization of micro-trust components, of course, is application OnCreate (of course, the activity of the oncreate is also possible, in order to use the micro-trust API to facilitate the global operation):

@Override public
void OnCreate () { 
 super.oncreate ();
 Initialize the micro-component
 initweixin ();

public static Iwxapi SApi;
private void Initweixin () {
 SApi = Wxentryactivity.initweixin (this, appconst.weixin_app_id);
}

4. Request authorization login, get code

For the single principle of the same business, I have encapsulated all of the micro-letters into the WXAPI package and the wxentryactivity:

Implement the Iwxapieventhandler interface to facilitate the callback of the micro-event handler public class Wxentryactivity extends the activity implements Iwxapieventhandler {p
 Rivate static final String Weixin_access_token_key = "Wx_access_token_key";
 private static final String Weixin_openid_key = "Wx_openid_key";

 private static final String Weixin_refresh_token_key = "Wx_refresh_token_key";
 Private Gson Mgson;
 @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Micro-credit Event callback Interface Registration GeneralAppliction.sApi.handleIntent (Getintent (), this);
 Mgson = new Gson (); /** * Micro-Letter Component Registration Initialization * @param context * @param weixin_app_id AppID * @return Micro-Component API Object */public static IWXAPI Initweixin (context context, @NonNull String weixin_app_id) {if (Textutils.isempty (weixin_app_id)) {Toast.maketext (con
 Text.getapplicationcontext (), "app_id cannot be Empty", Toast.length_short). Show ();
 } Iwxapi API = Wxapifactory.createwxapi (context, weixin_app_id, true);
 Api.registerapp (weixin_app_id);
 return API; }

 /* * Login Micro-Letter * * @param API Micro-service API/public static void Loginweixin (context context, Iwxapi API) {//To determine if a micro-credit client is installed End if (!api.iswxappinstalled ()) {Toast.maketext (Context.getapplicationcontext), "You have not installed the micro-client!" 
 ", Toast.length_short). Show (); 
 Return 
 //Send authorization login information to get code sendauth.req REQ = new Sendauth.req (); 
 The application scope, obtains the personal information Req.scope = "Snsapi_userinfo";
 /** * Used to maintain the status of the request and callback, the authorization request is brought back to the third party as is to prevent CSRF attack (cross-station request forgery attack), later changed to random number plus session to verify * * * req.state = "App_wechat";
 Api.sendreq (req); //micro-letter send request to a third party application, callback to the method @Override public void Onreq (Basereq req) {switch (Req.gettype ()) {case CONSTANTSAPI.C 
 Ommand_getmessage_from_wx:break; 
 Case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:break; 
 Default:break; 
 }//Third party application response results sent to the micro-letter request will be recalled to the method @Override public void Onresp (Baseresp resp) {switch (Resp.errcode) {//Send successfully
 Case BaseResp.ErrCode.ERR_OK://Get code String Code = ((SENDAUTH.RESP) Resp). Code; Get authorization password via code Access_token Getaccesstoken (code);
 Break }
 }
}

Little Buddy has questions about what code is:

Third party through the code to obtain Access_token need to use, the code timeout is 10 minutes, a code can only be successful in exchange for a access_token that is invalid. The code's temporary and one-time guarantees the security of the micro-letter authorization login. Third parties can further enhance the security of their own authorized logins by using HTTPS and state parameters.

This allows the client to use the place as long as:

Wxentryactivity.loginweixin (Mainactivity.this, GENERALAPPLICTION.SAPI);

5. Obtain authorization password by code Access_token

We get code in the Onresp callback method, and then get the authorization password via code access_token:

/** * Obtain authorization password/private void Getaccesstoken (string code) {String url = "Https://api.weixin.qq.com/sns/oauth2/access_ Token? "+" appid= "+ appconst.weixin_app_id +" &secret= "+ Appconst.weixin_app_secret +" &code= "+ code +" &am 
 P;grant_type=authorization_code "; The network request gets Access_token HttpRequest (URL, new apicallback<string> () {@Override public void onsuccess (String resp 
 Onse) {LOGGER.E (response); 
 Determine whether to obtain success, success is to obtain user information, otherwise prompted failure Processgetaccesstokenresult (response); 
 @Override public void OnError (int errorcode, final String errormsg) {LOGGER.E (errormsg); 
 ShowMessage ("error message:" + errormsg); 
 @Override public void OnFailure (IOException e) {LOGGER.E (E.getmessage ()); 
 ShowMessage ("Login Failed");
} 
 }); /** * Processing acquired authorization information results * @param response Authorization Information result * * private void Processgetaccesstokenresult (String response) {//Authentication acquisition grant Whether the information returned by the power password is successful if (validatesuccess (response)) {//Use Gson to resolve the returned authorization password information wxaccesstokeninfo tokeninfo = Mgson.fromjson (respoNSE, Wxaccesstokeninfo.class);
 LOGGER.E (Tokeninfo.tostring ());
 Save information to mobile phone local saveaccessinfotolocation (tokeninfo); 
 Get user Information GetUserInfo (Tokeninfo.getaccess_token (), Tokeninfo.getopenid ()); 
 else {//Authorization password acquisition failed, parse returns error message Wxerrorinfo Wxerrorinfo = Mgson.fromjson (response, Wxerrorinfo.class); 
 LOGGER.E (Wxerrorinfo.tostring ()); 
 Prompt for error message showmessage ("error message:" + wxerrorinfo.geterrmsg ()); }/** * Verify success * * @param response return message * @return Successful/private Boolean validatesuccess (String response) {STR 
 ing errflag = "errmsg"; Return (Errflag.contains (response) &&! " Ok ". Equals (response) | | (!"
Errcode ". Contains (response) &&!errflag.contains (response)); }

6. In step 5th to determine whether Access_token exists and expires

After obtaining the code in the callback's Onresp method, handle the issue of whether the Access_token has logged in or expired:

Obtain the stored authorization password information from the mobile phone locally, judge whether there is a access_token, there is no request to obtain, existence is to judge whether expired
string accesstoken = (string) Shareutils.getvalue (this , Weixin_access_token_key, "none");
String OpenID = (string) shareutils.getvalue (this, Weixin_openid_key, "");
if (!) None ". Equals (Accesstoken)) {
 //has access_token to determine whether expiration is valid
 Isexpireaccesstoken (Accesstoken, OpenID);
} else {
 //no Access_token
 Getaccesstoken (code);
}

To determine whether the authorization password is valid:

/** 
* Judge Accesstoken is expired 
* @param accesstoken token 
* @param OpenID authorized user Unique ID */
private void Isexpireaccesstoken (Final string accesstoken, final string OpenID) {
 string url = ' https://api.weixin.qq.com/sns/ Auth? "+ 
 " + "access_token=" + Accesstoken + 
 "&openid=" + OpenID;
 HttpRequest (URL, new apicallback<string> () {
 @Override public
 void onsuccess (String response) {
 LOGGER.E (response);
 if (validatesuccess (response)) {
 //Accesstoken does not expire, get user information
 GetUserInfo (Accesstoken, OpenID);
 } else {
 //Expired, use Refresh_token to refresh Accesstoken
 Refreshaccesstoken ();
 }
 @Override public
 void onError (int errorcode, final String errormsg) {
 logger.e (errormsg);
 ShowMessage ("error message:" + errormsg);
 }
 @Override public
 void OnFailure (IOException e) {
 logger.e (e.getmessage ());
 ShowMessage ("Logon Failed");
 }
 );

7. If Access_token expiration is invalid, use Refresh_token to refresh

/** * Refresh gets new Access_token */private void Refreshaccesstoken () {//from locally fetched to store Refresh_token final String Refreshtoken
 = (String) shareutils.getvalue (this, Weixin_refresh_token_key, "");
 if (Textutils.isempty (Refreshtoken)) {return; ///Assemble Refresh Access_token URL request address String URL = "Https://api.weixin.qq.com/sns/oauth2/refresh_token?" + "appid=" + appconst.
 weixin_app_id + "&grant_type=refresh_token" + "&refresh_token=" + refreshtoken; Request execution HttpRequest (URL, new apicallback<string> () {@Override public void onsuccess (String response) {LOGGER.E
 ("Refreshaccesstoken:" + response);
 Determine whether to obtain success, success is to obtain user information, otherwise prompted failure Processgetaccesstokenresult (response);
 @Override public void OnError (int errorcode, final String errormsg) {LOGGER.E (errormsg);
 ShowMessage ("error message:" + errormsg);
 Re-Request Authorization Loginweixin (WXEntryActivity.this.getApplicationContext (), GENERALAPPLICTION.SAPI);
 @Override public void OnFailure (IOException e) {LOGGER.E (E.getmessage ()); ShowmessaGE ("Login Failed");
 Re-Request Authorization Loginweixin (WXEntryActivity.this.getApplicationContext (), GENERALAPPLICTION.SAPI);
}
 }); }

8. Use Access_token to get user information

/**
 * Get user info
 *
/
private void GetUserInfo (String access_token, String OpenID) {
 string url = ' HTTPS ://api.weixin.qq.com/sns/userinfo? "+
 " access_token= "+ Access_token +
 " &openid= "+ OpenID;
 HttpRequest (URL, new apicallback<string> () {
 @Override public
 void onsuccess (String response) {
 Parse-Get user information
 wxuserinfo userInfo = Mgson.fromjson (response, wxuserinfo.class);
 LOGGER.E ("User information obtain result:" + userinfo.tostring ());
 @Override public
 void onError (int errorcode, String errormsg) {
 showmessage ("error message:" + errormsg);
 }
 @Override public
 void OnFailure (IOException e) {
 showmessage ("Get user information failed");
 }

Communication section

Private Okhttpclient mhttpclient = new Okhttpclient.builder (). build ();
Private Handler Mcallbackhandler = new Handler (Looper.getmainlooper ()); /** * through okhttp and micro-letter communication * * @param URL Request address * @throws Exception/public void HttpRequest (String URL, final APICALLBACK&L T
 String> callback) {logger.e ("URL:%s", url);
 Final Request request = new Request.builder (). URL (URL). Get (). build ();
 Mhttpclient.newcall (Request). Enqueue (New Callback () {@Override public void onfailure (call call, Final IOException e) { if (callback!= null) {Mcallbackhandler.post (new Runnable () {@Override public void run () {//request failed, main thread callback CALLB
  Ack.onfailure (e);
 }
 });
 @Override public void Onresponse (call call, Final Response Response) throws IOException {if (callback!= null) { if (!response.issuccessful ()) {Mcallbackhandler.post (new Runnable () {@Override public void run () {//Request error, main thread back
  Tune Callback.onerror (Response.code (), Response.message ());
 }
  }); else {McallbaCkhandler.post (New Runnable () {@Override public void run () {try {///request succeeded, the main thread returns the request result Callback.onsuccess (respons
  E.body (). String ());  catch (Final IOException e) {//exception error, main thread callback Mcallbackhandler.post (new Runnable () {@Override public void run ()
   {callback.onfailure (e);
  }
  });
 }
  }
  });
}
 }
 }
 }); }//API communication callback interface public interface Apicallback<t> {/** * Request succeeded * * @param response return result/void onsuccess (T resp
 Onse);
 /** * Request Error * * @param errorcode error code * @param errormsg error message/void OnError (int errorcode, String errormsg);
/** * Request failed/void OnFailure (IOException e); }

Summarize

Detailed description of the integration in this way, as far as the user information is obtained, the small partners should know what to do with the needs of their business. The above is the entire content of this article, I hope to be able to learn or work to bring certain help, if there is doubt you can message exchange.

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.