Micro-letter third-party login Android Implementation code _android

Source: Internet
Author: User
Tags openid uuid

Record the method by which the micro-credit third party implements the login. It's still quite simple.

I. The necessary preparatory work

1. The first need to register and be audited through the micro-letter open platform account, and then create a mobile application, also need to be audited;

2. Then go to the Resource Centre to download the tools needed to develop the micro-letter;

Download URL: Click on the Open link, there is an SDK, one is the signature generation tool also has an example code.

3. Import the jar file Libammsdk.jar under the SDK folder Lib into Project engineering;

4. Your test phone needs to install a micro-letter client;

5. Add the following permissions in the project's Androidmanifest.xml file:

<uses-permission android:name= "Android.permission.INTERNET"/>  
<uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "/> 
<uses-permission android:name=" android.permission.ACCESS_ Wifi_state "/>  
<uses-permission android:name= android.permission.READ_PHONE_STATE"/>  
< Uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>  

6. Since the micro-mail will return the results to our own application, we need to establish a callback activity according to the following rules

A. Create a new package named Wxapi under the package name (the package name that you want to apply for mobile applications), and then add a wxentryactivity class to the WXAPI package, which needs to inherit from the activity.

Then in this Androidmanifest.xml file, set the Export property of this activity to true, as shown below.

 <activity 
      android:name= ". Wxapi. Wxentryactivity " 
      android:label=" @string/title_activity_wxlogin " 
      android:launchmode=" Singletop 
      " Android:exported= "true" > 
      <intent-filter> 
        <action android:name= "Android.intent.action.MAIN"/ > 
        <category android:name= "Android.intent.category.LAUNCHER"/> 
      </intent-filter> 
</ Activity> 

B. Implement the Iwxapieventhandler interface, the request sent by the micro-mail will be recalled to the Onreq method, and the response sent to the micro-letter request will be recalled to the Onresp method

C. Intent received in wxentryactivity and objects that implement the Iwxapieventhandler interface are passed to the Iwxapi interface Handleintent method, as shown below

 
 

7. Micro-letter Certification sequence diagram

One thing to note here is that the 6th arrow from the top down, that is, through code plus AppID and Appsecret in exchange for Access_token, in fact this step is done on a Third-party application server, because Appsecret and Access_ It is very unsafe for token to be stored directly on the client. After the Android client gets the code, the code is submitted to the application server, the application server holds the Appsecret information, the application server gets the Access_token, and the Access_token to do other work.

Second, the Android code

Add the necessary code to the Wxentryactivity corresponding class file that you added in the previous step, my code is as follows:

Package Com.example.justyoung.logintest.wxapi; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import android.support.v7.app.ActionBarActivity; 
Import Android.view.View; 
Import Android.widget.Button; 
 
Import Android.widget.Toast; 
Import Com.example.justyoung.logintest.HttpsHelper; 
Import COM.EXAMPLE.JUSTYOUNG.LOGINTEST.R; 
Import com.example.justyoung.logintest.fileExplorer.WXConstant; 
Import Com.tencent.mm.sdk.modelbase.BaseReq; 
Import Com.tencent.mm.sdk.modelbase.BaseResp; 
Import Com.tencent.mm.sdk.modelmsg.SendAuth; 
Import Com.tencent.mm.sdk.openapi.IWXAPI; 
Import Com.tencent.mm.sdk.openapi.IWXAPIEventHandler; 
 
Import Com.tencent.mm.sdk.openapi.WXAPIFactory; 
Import java.io.IOException; 
Import java.security.KeyManagementException; 
Import java.security.NoSuchAlgorithmException; 
 
Import Java.util.UUID; 
  public class Wxentryactivity extends actionbaractivity implements iwxapieventhandler{private Button wxlogin; 
  Private IWXAPI API; Private STATic String uuid; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.activity_wxlogin); 
    Wxlogin = (Button) Findviewbyid (R.id.wx_login_button); 
    Wxlogin.setonclicklistener (New Wxloginevent ()); 
    API = Wxapifactory.createwxapi (this, wxconstant.appid); 
    Api.registerapp (WXCONSTANT.APPID); 
  Api.handleintent (Getintent (), this);  @Override public void Onreq (Basereq basereq) {} @Override public void Onnewintent (Intent Intent) 
    {super.onnewintent (intent); 
    Setintent (Intent); 
  Api.handleintent (Intent, this); 
    @Override public void Onresp (Baseresp resp) {String result; 
        Switch (resp.errcode) {Case BaseResp.ErrCode.ERR_OK:result = "OK"; 
        Sendauth.resp Regresp = (SENDAUTH.RESP) Resp; 
        if (!regresp.state.equals (UUID)) return; 
        String code = Regresp.code; New WxloginthreaD ("https://192.168.2.133:8443/CloudStorageServer/wechat/login?code=" + code). Start (); 
      Break 
        Case BaseResp.ErrCode.ERR_USER_CANCEL:result = "User_cancel"; 
      Break 
        Case BaseResp.ErrCode.ERR_AUTH_DENIED:result = "err_auth_denied"; 
      Break 
        Default:result = "Errcode_unknown"; 
    Break 
 
  } toast.maketext (this, result, Toast.length_long). Show (); Class Wxloginevent implements View.onclicklistener {@Override public void OnClick (View v) {UUID 
      = Uuid.randomuuid (). toString (); 
      Final Sendauth.req Req = new Sendauth.req (); 
      Req.scope = "Snsapi_userinfo"; 
      Req.state = UUID; 
    Api.sendreq (req); 
 
    } private class Wxloginthread extends Thread {private String URL; 
    Public wxloginthread (String url) {this.url = URL; 
      @Override public void Run () {Httpshelper httpshelper = new Httpshelper (); try {
        Httpshelper.preparehttpsconnection (URL); 
      String response = Httpshelper.connect (); 
      catch (Keymanagementexception e) {e.printstacktrace (); 
      catch (NoSuchAlgorithmException e) {e.printstacktrace (); 
      catch (IOException e) {e.printstacktrace (); 
 } 
    } 
  } 
}

The following fragment in the code is used to pull up the micro-letter authentication interface. Here I use the UUID as the state parameter, which can be used to prevent CSRF attacks (cross-station request forgery attacks), it is recommended that a third party with this parameter, can be set to a simple random number plus session for the checksum.

UUID = Uuid.randomuuid (). toString (); 
Final Sendauth.req Req = new Sendauth.req (); 
Req.scope = "Snsapi_userinfo"; 
Req.state = UUID; 

After the user accepts the authentication, the micro-credit application will callback the Onresp method of the Iwxapieventhandler interface. In this method, the state is judged first, and then the code value is obtained from the RESP, if it is the normal state of the returned RESP. The client then completes its work.

Because the client retains Appsecret and Access_token is very insecure, the acquisition of the remaining information should be placed on our application server.

Third, Application server code

After the Anroid client gets the code, it can be submitted to our own application server, and then code is used in our application server to get user information such as Access_token,openid.

1. The method of obtaining Access_token,openid by code is to request the micro-interface in the following manner using a GET request:

Https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type= Authorization_code;

2. The way to obtain some information about a user through Access_token is to use a micro-letter interface through a GET request:

Https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID

Here's the code I'm using:

 private void handle (HttpServletRequest request, httpservletresponse response) throws Se 
    Rvletexception, IOException {String code = getparameter (Request, "code"); 
      if (Isargumentnullorempty (code)) {Log.logger.info ("code is empty"); 
    Return 
    } Log.logger.info ("Received code:" + code); 
      try {accesstoken Accesstoken = new Accesstoken ("/sns/oauth2/access_token", "Authorization_code", code); 
      Accesstoken.userdata UserData = Accesstoken.getmetadata (). GetUserInfo (); 
    ...//UserData is the user information we get through Access_token. 
      catch (Weixinexception e) {log.logexception (e); 
      Writemessage (response, E.getmessage ()); 
    Return 
      catch (Exception e) {log.logexception (e); 
      Writemessage (response, "Login error"); 
    Return } 
  } 
Package com.cyber_space.thirdparty.weixin; 
Import java.io.IOException; 
Import Java.lang.reflect.Field; 
Import Java.net.URI; 
 
Import java.net.URISyntaxException; 
Import org.apache.http.HttpEntity; 
Import org.apache.http.client.ClientProtocolException; 
Import Org.apache.http.client.methods.CloseableHttpResponse; 
Import Org.apache.http.client.methods.HttpGet; 
Import Org.apache.http.client.utils.URIBuilder; 
Import org.apache.http.entity.BufferedHttpEntity; 
Import org.apache.http.impl.client.CloseableHttpClient; 
Import org.apache.http.impl.client.HttpClients; 
 
Import Org.apache.http.util.EntityUtils; 
 
Import Com.cyber_space.util.JsonUtil; 
  public class Accesstoken {closeablehttpclient httpclient; 
  HttpGet HttpGet; 
  URI Uri; 
 
  String Code; /** * Used for public number * * * @throws urisyntaxexception * * () throws URISyntaxException {u 
 RI = new UriBuilder (). SetScheme ("https"). Sethost ("api.weixin.qq.com"). SetPath ("/cgi-bin/token")       . Setparameter ("Grant_type", "client_credential"). Setparameter ("AppID", weixinconfig.app_id). Setparameter ( 
    "Secret", Weixinconfig.app_secret). Build (); 
    HttpClient = Httpclients.createdefault (); 
  HttpGet = new HttpGet (URI); Public Accesstoken (string path, string Granttype, String code) throws URISyntaxException {uri = new Uribuilde R (). SetScheme ("https"). Sethost ("api.weixin.qq.com"). SetPath (Path). Setparameter ("Grant_type", Granttype). Setpara Meter ("AppID", weixinconfig.app_id). Setparameter ("secret", Weixinconfig.app_secret). Setparameter ("code", code). b 
    Uild (); 
    HttpClient = Httpclients.createdefault (); 
  HttpGet = new HttpGet (URI); Public String Getaccesstoken () throws Clientprotocolexception, IOException {closeablehttpresponse response = 
    Null 
      try {response = Httpclient.execute (HttpGet); 
      Httpentity httpentity = response.getentity (); 
  if (httpentity = null) return null;    httpentity = new Bufferedhttpentity (httpentity); 
      String returnstring = entityutils.tostring (httpentity); 
      String Accesstoken = Com.cyber_space.util.JsonUtil.getAttribute (returnstring, "Access_token"); 
    return accesstoken; 
    finally {response.close (); }/** * Obtains user metadata information, including OpenID and Access_token * * @return * @throws clientprotocolexception * @t Hrows IOException * @throws weixinexception * * Public UserData GetMetaData () throws Clientprotocolexception, IO 
    Exception, weixinexception {closeablehttpresponse response = null; 
      try {response = Httpclient.execute (HttpGet); 
      Httpentity httpentity = response.getentity (); 
      if (httpentity = null) return null; 
      httpentity = new Bufferedhttpentity (httpentity); 
      String returnstring = entityutils.tostring (httpentity); 
      Jsonutil jutil = new Jsonutil (returnstring, jsonutil.jsonobject); 
      String error = NULL;try {error = Jutil.getattribute ("Errcode"); catch (Exception e) {} if (Error!= null &&!error.equals (")) {throw new Weixinexcepti 
      On (Weixinexception.invalid_openid); 
      String OpenID = Jutil.getattribute ("OpenID"); 
      String Accesstoken = Jutil.getattribute ("Access_token"); 
      UserData uData = new UserData (OpenID, Accesstoken); 
    return uData; 
    finally {response.close (); 
    } public class UserData {public String OpenID; 
    Public String Accesstoken; 
    Public String nickname; 
    public String sex; 
    Public String Province; 
    public, String City; 
    Public String country; 
    Public String Headimgurl; 
    public String privilege; 
 
    Public String Unionid; 
      Public UserData (String OpenID, String accesstoken) {This.openid = OpenID; 
    This.accesstoken = Accesstoken; Public UserData GetUserInfo () throws IOException, IllegalaRgumentexception, Illegalaccessexception, URISyntaxException, weixinexception {uri uri = new UriBuilder (). SetSchem E ("https"). Sethost ("api.weixin.qq.com"). SetPath ("/sns/userinfo"). Setparameter ("Access_token", This.accesstoken 
      ). Setparameter ("OpenID", This.openid). Build (); 
      HttpGet httpget = new HttpGet (URI); 
      Closeablehttpresponse response = null; 
        try {response = Httpclient.execute (HttpGet); 
        Httpentity httpentity = response.getentity (); 
        if (httpentity = = null) throw null; 
        httpentity = new Bufferedhttpentity (httpentity); 
        String jsonstring = entityutils.tostring (httpentity); 
        Jsonutil jutil = new Jsonutil (jsonstring, jsonutil.jsonobject); 
        String errcode = null; 
        try {errcode = Jutil.getattribute ("Errcode"); The catch (Exception e) {}//is assigned through the reflection loop if (Errcode = null | | errcode.equals ("")) {F or (Field I:getclass (). GetFields ()) {if (!i.getname (). Equals ("Accesstoken")) I.set (This, Jutil.getattribute (I.GETN 
          Ame ())); 
        return to this; 
        else {throw new weixinexception (Weixinexception.invalid_accesstoken); 
      finally {response.close ();  } 
    } 
  } 
 
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.