Article From:https://www.cnblogs.com/kenshinobiy/p/9217442.html
  1. 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);
}
  1. Add in the place where you need to log in:
// MainActivity.java
WXEntryActivity.loginWeixin(MainActivity.this, GeneralAppliction.sApi);

The detailed integration steps are described in detail below.

Integration steps:

  1. Create application on open platform registration, apply for login authority
  2. Download SDK, copy related documents to project project directory
  3. Global initialization of WeChat components
  4. Request authorization to log in and get code
  5. Obtain authorization password access_token by code
  6. Determine whether access_token exists and expires in the fifth step
  7. If access_token expires, it will be refreshed with refresh_token.
  8. Using access_token to get user information

1. Create application on open platform registration, apply for login authority

In fact, this step is not to be talked about. It is impossible to register an account on WeChat open platform and create mobile applications.

 
Paste_Image.png

What needs to be noted is: the part of the application of the signature

 

 
Paste_Image.png

Here, I use the signature on the online key MD5, and I need to pay attention to this issue in another article: Android’s signature summary.

 

2. Download SDK, copy related documents to project project directory

  • Download of development kit (SDK): you can use WeChat’s share, login, collection, payment and other functions required libraries and documents.
  • Example Demo

After downloading, copy the libammsdk.jar file to the LIBS directory of the AS project, and copy the whole wxapi directory in the source file directory of the sample Demo to the root package under the SRC of the engineering directory.

 
The correct location of the WeChat directory is.Png

If the location of the wxapi folder is not in the right place and cannot be logged in, WeChat SDK can’t find the Activity authorization function. And then add in the 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 WeChat components

The global initialization of WeChat components, of course, is Application’s onCreate (of course, Activity’s onCreate is also available for the global use of WeChat API objects):

@Override
public void onCreate() {    
    super.onCreate();
    // Initialization of WeChat componentsInitWeiXin ();}public static IWXAPI sApi;
private void initWeiXin() {
    sApi = WXEntryActivity.initWeiXin(this, AppConst.WEIXIN_APP_ID);
}

4. Request authorization to log in and get code

For the single principle of the same business, I have encapsulated WeChat related to wxapi package and WXEntryActivity:

// Implement IWXAPIEventHandler interface to facilitate callback of WeChat event handling.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);
        // WeChat event callback interface registrationGeneralAppliction.sApi.handleIntent (getIntent (),this);
        mGson = new Gson();
    }

    /**
     * WeChat component registration initialization*@param context       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 Can't be empty ", Toast.LENGTH_SHORT).Show ();}IWXAPI API = WXAPIFactory.createWXAPI (context,Weixin_app_id, true);Api.registerApp (weixin_app_id);Return API;}/ * * * * ** login WeChat**@param api WeChat service API* * /public static void loginWeixin(Context context, IWXAPI api) {
        // Determine whether a WeChat client is installedif (!api.isWXAppInstalled()) {  
            Toast.makeText(context.getApplicationContext(), "You have not installed the WeChat client yet! ", Toast.LENGTH_SHORT).Show ();return;    
        }
        // Send the authorization login information to get the codeSendAuth.Req req =new SendAuth.Req();    
        // The scope of application to obtain personal informationReq.scope ="snsapi_userinfo";    
        /**     
        * Used to maintain the state of request and callback, and bring back the original request to the third party after authorization request.* in order to prevent CSRF attacks (Cross Site Request Forgery Attack), the later is changed to random number plus session to check.* * /Req.state ="app_wechat";
        api.sendReq(req);
    }

    // When WeChat sends requests to third party applications, it will callback to this method.@Override
    public void onReq(BaseReq req) {    
        switch (req.getType()) {        
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX: 
              break;        
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
              break;        
            default:            
              break;    
        }
    }
    // The response result of the third party application sent to WeChat's request will be callback to this method.@Override
    public void onResp(BaseResp resp) {
        switch (resp.errCode) {   
            // Send successcase BaseResp.ErrCode.ERR_OK:
                // Get codeString code = ((SendAuth.Resp) RESP).Code;// Obtain authorization password access_token by codeGetAccessToken (code);break;
        }
    }
}

The little partner has a doubt about what code is:
Third parties need to use code to get access_token. The timeout time of code is 10 minutes, and a code can only be successfully replaced by a access_token. The temporary nature of code and once guaranteed the authorized login of WeChat.Full nature. The third party can further enhance the security of its authorized login by using HTTPS and state parameters.

So long as the client uses:

WXEntryActivity.loginWeixin(MainActivity.this, GeneralAppliction.sApi);

5. Obtain authorization password access_token by code

We obtained the code in the callback method of onResp, and then obtained the authorization password access_token through code:

/** 
* Access to authorization passwords* * /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 to access_token for network requestsHttpRequest (URL,new ApiCallback<String>() {        
        @Override        
        public void onSuccess(String response) {            
            Logger.e(response);            
            // If you decide whether to succeed, you will succeed in getting user information, otherwise the prompt will fail.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("Logon failed ");}});}/** 
* Processing the result of the acquired authorization information*@param response  Authorization information result* * /private void processGetAccessTokenResult(String response) {    
    // Verify whether the information returned by the authorization password is successful.if (validateSuccess(response)) {
        // Authorization password information returned with Gson parsingWXAccessTokenInfo tokenInfo = mGson.fromJson (response, WXAccessTok)EnInfo.class);Logger.e (tokenInfo.toString ());// Save information to mobile phone localSaveAccessInfotoLocation (tokenInfo);// Obtaining user informationGetUserInfo (tokenInfo.getAccess_token (), tokenInfo.getOpenid ());}else {
        // Authorization password failed, parse returns error message.WXErrorInfo wxErrorInfo = mGson.fromJson (response, WXErrorInfo.cla)SS);Logger.e (wxErrorInfo.toString ());// Prompt error informationShowMessage ("Error message: "+ wxErrorInfo.getErrmsg ()");}}/** 
* Verify whether it is successful**@param response Return message*@return Whether it is successful or not* * /private boolean validateSuccess(String response) {    
    String errFlag = "errmsg";    
    return (errFlag.contains(response) && !"ok".equals(response))            
            || (!"errcode".contains(response) && !errFlag.contains(response));
}

6. Determine whether access_token exists and expires in the fifth step

After getting the code in the callback onResp method, processing whether access_token has logged in or expired:

// Obtain the authorized password information from the cell phone to determine whether there is access_token, there is no request for access, and it is judged whether it is 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)) {
    // There is access_token, to judge whether the expiration date is validIsExpireAccessToken (accessToken, openid);}else {
    // No access_tokenGetAccessToken (code);}

Whether the authorized password is valid or not:

/** 
* Judge accesstoken is overdue*@param accessToken   token 
* @param openid        Authorized user unique identity* * /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)) {
                // accessTokenNo expired, access to user informationGetUserInfo (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 expires, it will be refreshed with refresh_token.

/**
 * Refresh to get new access_token*/Private void refreshAccessToken () {/ / obtain the stored refresh_token from the localFinalString refreshToken = (String) ShareUtils.getValue (this, WEIXIN_REFRESH_TOKEN_KEY, "");If (TextUtils.isEmpty (refreshToken)) {Return;}/ / / refresh access_token's URL request addressString URL= "https://api.weixin.qq.com/sns/oauth2/refresh_token?" +"Appid=" + AppConst.WEIXIN_APP_ID +"& grant_type=refresh_token" +"& refresh_token=" + refreshToken;/ / request executionHttpRequest (URL, new ApiCallback< String> () {)@Override
        public void onSuccess(String response) {
            Logger.e("refreshAccessToken: " + response);
            // If you decide whether to succeed, you will succeed in getting user information, otherwise the prompt will fail.ProcessGetAccessTokenResult (response);}@Override
        public void onError(int errorCode, final String errorMsg) {
            Logger.e(errorMsg);
            showMessage("Error message: "+ errorMsg";/ / rerequest authorizationLoginWeixin (WXEntryActivity.this.getApplicatiOnContext () (), GeneralAppliction.sApi);}@Override
        public void onFailure(IOException e) {
            Logger.e(e.getMessage());
            showMessage("Logon failed ");/ / rerequest authorizationLoginWeixin (WXEntryActivity.this.getApplicationContext ()).GeneralAppliction.sApi);}});}

8. Using access_token to get user information

/**
 * Obtaining 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< String> () {)@Override
        public void onSuccess(String response) {
            // Parsing the acquired user informationWXUserInfo userInfo = mGson.fromJson (response, WXUserInfo.class);Logger.e ("user information acquisition result:" + userInfo.toString ());}@Override
        public void onError(int errorCode, String errorMsg) {
            showMessage("Error message: "+ errorMsg";}@Override
        public void onFailure(IOException e) {
            showMessage("Access to user information failure ");}});}

Communication part

private OkHttpClient mHttpClient = new OkHttpClient.Builder().build();
private Handler mCallbackHandler = new Handler(Looper.getMainLooper());
/**
 * Communication with WeChat through Okhttp* *@param url Request address*@throws Exception
 */
public void httpRequest(String url, final ApiCallback<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 failure, master thread callbackCallback.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 callbackCallback.onError (response.code (), response.message ());}});}else {
                    mCallbackHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                // Request success, the main thread returns the request resultCallback.onSuccess (response.body ().String ());}catch (final IOException e) {
                                // Exception error, main thread callbackMCallbackHandler.post (new Runnable() {
                                    @Override
                                    public void run() {
                                        callback.onFailure(e);
                                    }
                                });
                            }
                        }
                    });
                }
            }
        }
    });
}

// ApiCommunication callback interfacepublic interface ApiCallback<T> {
    /**
     * Request success**@param response Return to the result* * /void onSuccess(T response);
    /**
     * Request an error**@param errorCode Error code*@param errorMsg  error message* * /void onError(int errorCode, String errorMsg);
    /**
     * request was aborted* * /void onFailure(IOException e);
}

summary

The detailed description of integration is that, as for the acquired user information, small partners should know the needs of subsequent businesses and how to deal with them.

Author: JerryloveEmily
Link: https://www.jianshu.com/p/d95e4343e231
Source: Jane book
The copyright of the book is owned by the author. Any form is reproduced. Please contact the author for authorization and indicate the source.

Leave a Reply

Your email address will not be published. Required fields are marked *