Right you read that right, not the clicker, really just three lines of code, the conclusion code first:

  1. In Application onCreate write:
    // GeneralAppliction.java
    public static IWXAPI sApi;
    @Override
    public void onCreate() {
     super.onCreate();
     sApi = WXEntryActivity.initWeiXin(this, AppConst.WEIXIN_APP_ID);
    }Copy the code
  2. Add where you need to log in:
    // MainActivity.java
    WXEntryActivity.loginWeixin(MainActivity.this, GeneralAppliction.sApi);Copy the code

The specific integration steps are described in detail below.

Integration steps:

  1. Register and create applications on an open platform and apply for login permission
  2. Download the SDK and copy related files to the project directory
  3. Initialize the wechat component globally
  4. Request authorization to log in and obtain the code
  5. Obtain the authorization password access_token by code
  6. Determine whether the access_token exists and expires in step 5
  7. If the access_token is expired and invalid, refresh_token is used to refresh
  8. Obtain user information using access_token

1. Register and create applications on an open platform and apply for login permission

In fact, this step is not how to say, is to register an account on the wechat open platform, and then create a mobile application.




Paste_Image.png

Note the following: apply the signature part




Paste_Image.png

Here I use THE MD5 of the online key for the application signature. For this problem, you can see my other article: Android signature summary

2. Download the SDK and copy related files to the project directory

  • Download of development kit (SDK) : libraries and files required by functions such as sharing, login, favorites and payment can be used in wechat
  • The sample Demo

Copy the libammsdk.jar file to the libs directory of the AS project, and copy the wxapi file from the source directory of the AS project to the root package of the SRC project:




The correct location of the wechat directory. PNG

If you place the folder wxAPI in the wrong position, you will not be able to log in, and wechat SDK will not be able to find the Activity authorization function for logging in. Then add the following to manifest.xml:

Copy the code

3. Initialize the wechat component globally

Initialize the wechat component globally, of course, in the Application onCreate (of course, the Activity onCreate is also available, in order to use the wechat API object globally for easy operation) :

@Override public void onCreate() { super.onCreate(); // Initialize the wechat component initWeiXin(); } public static IWXAPI sApi; private void initWeiXin() { sApi = WXEntryActivity.initWeiXin(this, AppConst.WEIXIN_APP_ID); }Copy the code

4. Request authorization to log in and obtain the code

For the single principle of the same business, I packaged all related wechat into wXAPI package and WXEntryActivity:

// Implement IWXAPIEventHandler interface Public Class WXEntryActivity extends Activity implements IWXAPIEventHandler {private 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); / / registered GeneralAppliction WeChat event callback interface. The sApi. HandleIntent (getIntent (), this); mGson = new Gson(); } /** * wechat component registration initialization * @param context * @param weixin_app_id appID * @return wechat component API object * / public static IWXAPI initWeiXin(Context context, @NonNull String weixin_app_id) { if (TextUtils.isEmpty(weixin_app_id)) { Toast.makeText(context.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; } public static void loginWeixin(Context Context); IWXAPI API) {// Check whether wechat client is installed if (! API. IsWXAppInstalled ()) {Toast. MakeText (context) getApplicationContext (), "you have not install WeChat client!" , Toast.LENGTH_SHORT).show(); return; } // Send authorization login information to get code sendauth.req Req = new sendauth.req (); Scope = "snsapi_userinfo"; req.scope = "snsapi_userinfo"; */ req.state = "app_wechat"; */ req.state = "app_wechat"; api.sendReq(req); } // When wechat sends a request to a third-party application, @override public void onReq(BaseReq) {switch (req.getType()) {case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX: break; case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX: break; default: break; }} // The response result of the request sent by the third-party application to wechat after processing, @Override public void onResp(BaseResp resp) {switch (resp.errcode) {// Sending baserESP.errcode.ERR_OK: // Get code String code = ((sendauth.resp) Resp).code; Access_token getAccessToken(code); break; }}}Copy the code

If a third party uses code to obtain an access_token, the code timeout period is 10 minutes. Each code can be exchanged successfully only once before the access_token becomes invalid. The temporary and one-time code ensures the security of wechat authorized login. A third party can use HTTPS and state parameters to further enhance the security of its own authorized login.

So that the client can use only:

WXEntryActivity.loginWeixin(MainActivity.this, GeneralAppliction.sApi);Copy the code

5. Obtain the authorization password access_token from code

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

/** * 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 + "&grant_type=authorization_code"; Access_token httpRequest(url, new ApiCallback() { @Override public void onSuccess(String response) { Logger.e(response); / / determine whether success, success is to get the user information, otherwise the prompt 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 "); }}); } / * * * * @ param get authorization information processing results response authorization information results * / private void processGetAccessTokenResult (String response) {/ / ValidateSuccess (Response)) {WXAccessTokenInfo tokenInfo = If (validateSuccess(Response)) {WXAccessTokenInfo tokenInfo = mGson.fromJson(response, WXAccessTokenInfo.class); Logger.e(tokenInfo.toString()); // Save information to the local saveAccessInfotoLocation(tokenInfo); GetUserInfo (tokeninfo.getAccess_token (), tokenInfo.getopenid ()); } else {WXErrorInfo WXErrorInfo = mgson.fromjson (response, wxerrorinfo.class); WXErrorInfo = mgson.fromjson (response, wxerrorinfo.class); Logger.e(wxErrorInfo.toString()); ShowMessage (" error message: "+ wxerrorinfo.geterrmsg ()); }} /** * Validation succeeds ** @param Response Returns a message * @return succeeds */ private Boolean validateSuccess(String Response) {String errFlag = "errmsg"; return (errFlag.contains(response) && !" ok".equals(response)) || (!" errcode".contains(response) && ! errFlag.contains(response)); }Copy the code

6. Check whether the access_token exists and expires in Step 5

After getting the code in the onResp method of the callback, handle whether the access_token is logged in or expired:

// Obtain the authorization password information stored locally from the mobile phone, check whether there is access_token, no request to obtain, String accessToken = (String) shareUtils.getValue (this, WEIXIN_ACCESS_TOKEN_KEY, "none"); String openid = (String) ShareUtils.getValue(this, WEIXIN_OPENID_KEY, ""); if (!" None ". Equals (accessToken)) {isExpireAccessToken(accessToken, openID); } else {// No access_token getAccessToken(code); }Copy the code

Determine whether the authorized password is valid:

/** * Check whether accesstoken is expired * @param Accesstoken token * @Param OpenID Unique identifier of an authorized user */ 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() { @Override public void onSuccess(String response) { Logger.e(response); If (validateSuccess(response)) {getUserInfo(accessToken, openId); } else {// expire, use refresh_token to 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 (" login failed "); }}); }Copy the code

7. If the Access_token is expired and invalid, refresh_token is used to refresh

/** * refresh access_token * / private void refreshAccessToken() {// refresh_token final String refreshToken = stored locally (String) ShareUtils.getValue(this, WEIXIN_REFRESH_TOKEN_KEY, ""); if (TextUtils.isEmpty(refreshToken)) { return; } / / assembled refresh access_token request url 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 to execute httpRequest(url, new ApiCallback() { @Override public void onSuccess(String response) { Logger.e("refreshAccessToken: " + response); / / determine whether success, success is to get the user information, otherwise the prompt failure processGetAccessTokenResult (response); } @Override public void onError(int errorCode, final String errorMsg) { Logger.e(errorMsg); ShowMessage (" error message: "+ errorMsg); / / to request authorization loginWeixin (WXEntryActivity. Enclosing getApplicationContext (), GeneralAppliction. SApi); } @Override public void onFailure(IOException e) { Logger.e(e.getMessage()); ShowMessage (" login failed "); / / to request authorization loginWeixin (WXEntryActivity. Enclosing getApplicationContext (), GeneralAppliction. SApi); }}); }Copy the code

8. Use the access_token to obtain user information

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() {@override public void onSuccess(String response) {WXUserInfo userInfo = mGson.fromJson(response, WXUserInfo.class); Logger.e(" userInfo: "+ userinfo.tostring ()); } @override public void onError(int errorCode, String errorMsg) {showMessage(" errormessage: "+ errorMsg); } @override public void onFailure(IOException e) {showMessage(" failed to obtain user information "); }}); }Copy the code

Communication part

private OkHttpClient mHttpClient = new OkHttpClient.Builder().build(); private Handler mCallbackHandler = new Handler(Looper.getMainLooper()); /** * communicate with wechat through Okhttp ** @param URL request address * @throws Exception */ public void httpRequest(String URL, final ApiCallback 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 ! {McAllbackhandler. post(new Runnable() {@override public void run() {// Failed, callback.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() { Callback.onerror (response.code(), response.message())); }}); } else {McAllbackhandler. post(new Runnable() {@override public void run() {try { Callback.onsuccess (response.body().string()); } catch (final IOException e) { McAllbackhandler. post(new Runnable() {@override public void run() {callback.onFailure(e); }}); }}}); }}}}); } public interface ApiCallback {/** * @param response return result */ void onSuccess(T response); /** * @param errorCode errorCode * @param errorMsg error message */ void onError(int errorCode, String errorMsg); /** * request failed */ void onFailure(IOException e); }Copy the code

conclusion

This is the detailed description of the integration. As for the user information obtained, partners should know their subsequent business needs and how to deal with it.