Java official account for WeChat development

Keywords: Java

Complex source code (end of article)

catalogue

Official account number and setting

  Explanation of each configuration

Interface configuration information

JS interface security domain name

Test number QR code

Template message interface

How to get the user's openid

Get the basic information explanation of Web authorized users

domain name

Parameter scope

UnionID

Code to get openId, scope=snsapi_base

Step 1: get the code first

Step 2: exchange code for access_token (authentication token)

Step 3: get the user's personal information through openid

Code to get openId, scope=snsapi_userinfo

Too many, just paste the code

Two accesses_ Different tokens

Pit description

Say two words of nonsense

 

Foreword: the official account should be used in the work, for the first time to explore and record notes, so as to avoid being forgotten.

Official account number and setting

          Wechat provides a test and development platform for developers, who can apply for a test number apply ; When I first started developing, I applied for a official account. Now I find it is not necessary at all. Although it can be set up in the official account, it can be developed, but after all, it has also taken some detours. Moreover, many advanced interfaces require permission to be called, or there are times restrictions and no recommendation. The test number applied is shown in the figure below

  Among them, appID, appsecret, these two information, is your official account number; Just bring it when calling the interface

  Explanation of each configuration

  • Interface configuration information

 

At first, it was a stupid configuration and successful. But in the later development, it was found that the configuration of the device was not configured, it doesn't matter, it could call WeChat's interface, such as creating official account menu. Maybe I'm too chicken?

In fact, after repeatedly checking the wechat documents, this interface configuration means this, which is the original words of the wechat official documents; "The server configuration URL filled in by the developer will get the messages and events pushed by the wechat server. The developer can respond according to his own business logic, such as replying to messages."

In one sentence, wechat needs to be used when adjusting our interface; That's it, shit; So we haven't used it in our project (embarrassing);

Source location (com.wechat.demo.wxcontroller.WeChatController#wechat)

  • JS interface security domain name

  That is, you can set a domain name (it is impossible to support ip address call anyway) and directly call the JS interface of wechat; For domain names, you can use ngrok for mapping, so it's not wordy;

  • Test number QR code

 

WeChat provides the test public number, using mobile phone WeChat scan code to pay attention to it, and can see the development of official account in real time.

  • Template message interface

I haven't used it. I don't know. After I use it, I'll improve the article;  

  • Experience interface permission table

These lists are all the interfaces provided by wechat; Just develop according to the instructions;   More importantly, the interface of web page authorization to obtain user information in the figure below;

 

When you click Modify, the following figure will be displayed; It means that after the user agrees to authorize, wechat will call the page or interface written by us. Send the code by mail, and then we can exchange the code for access_token;

 

How to get the user's openid

In developing WeChat official account, getting openid that concerns the official account is very important, otherwise you can't tell who is who. Click“ Web page authorization to obtain basic user information ”, check the document and call by interface, but there are many pits; Say, strengthen your memory;

Get the basic information explanation of Web authorized users

I saw this then file After that, it's like saying, what's this? After groping for a week, I figured it out;

domain name

Web page authorization to obtain basic user information  : In this modification, the domain name is filled in without 'http: / /' or 'https: / /'

The authorization callback domain name configuration specification is the full domain name:   redirect_ The URI (callback parameter) is written with http

Parameter scope

scope is snsapi_base: it can be understood that if you click the button in WeChat official account, you can get the authorization of the user.

scope is snsapi_userinfo: it can be understood that a page will pop up and ask you to agree before authorization;

UnionID

It is your company that has 10 official account numbers, and the user has only one of them certified. Other official account can also be operated after it is concerned, so it does not need to repeat authentication.

Code to get openId, scope=snsapi_base

Step 1: get the code first

In the applied test number, let the user click a connection to log in, or click a menu to log in, as shown in the figure below; The automatic recovery function of menu and official account is relatively simple. It's too much to knock; The source code is followed by the source code location (com.wechat.demo.wxcontroller.WeChatController#getUserMsg)

  The login connection is as follows

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxef4d3ff57f4ced1f&redirect_uri=http://9e18-222-94-217-138.ngrok.io/getUserInfoBase&response_type=code&scope=snsapi_base&state=123#wechat_redirect

When we click the connection, we can get the code; Where in url   redirect_ The value of URI parameter, and the callback is our own interface; At this time, we can get the value in code in the interface; among   scope=snsapi_base

The above link can only be opened in wechat or wechat developers;

Step 2: exchange code for access_token (authentication token)

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

Put the code called back in the first step into the url, and replace APPID and SECRET with your own test number information; In fact, in this step, after the interface is called, you can not only obtain access_token; openId can also be obtained; Ha ha ha;

Then get access_ What is the use of an authentication token? In fact, it is useful; If scope is snsapi_userinfo, then this access_ The token (authentication token) is useful, which will be discussed below;

In fact, I already got openId at this time;

Step 3: get the user's personal information through openid

https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

Note: this url is snsapi with scope_ Base's interface for obtaining personal information, its access_ The value passed by token is ordinary access_token; In this way, you can obtain the personal information of the controlled users; Refer to wechat documents for the returned information;

And the following url  

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

The url is scope   snsapi_userinfo's interface for obtaining personal information, its access_ The value of the token is the web page authentication token, also called access_ token; And this access_ How to transfer the value of a token (authentication access_token)? In fact, it is the second step mentioned above;

Fuck or not? It took me several days to figure out the difference between the two. Maybe I'm a vegetable chicken;

/**
     * getUserInfoBase  Exchange accessToken through code, obtain openId through accessToken, and obtain user information through openId
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/getUserInfoBase",method = RequestMethod.GET)
    public Object getUserInfoBase(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        String code = request.getParameter("code");
        System.out.println("code:"+code);

        // Exchange code for the address of accessToken
        String getAccess_token = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        String replace = getAccess_token.replace("APPID", "wxef4d3ff57f4ced1f").replace("SECRET", "e012bfb1fc0bbebc67324112902a2ca6").replace("CODE", code);
        String s = HttpClientTool.doGet(replace, null);

        System.out.println("Obtained accessToken The result is:" + JSONObject.toJSONString(s));

        Object openid = JSONObject.parseObject(s).get("openid");

        // Get the user's basic information. The scope is snsapi_base to silently obtain user information
        String getUserInfo_ = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        // This access_token is the token that calls the interface of the official account, and is the ordinary token (the common token is obtained through the following url: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxef4d3ff57f4ced1f&secret=e012bfb1fc0bbebc67324112902a2ca6 );
        String replace1 = getUserInfo_.replace("ACCESS_TOKEN", "51_YgCgtz8jCQK1szhYiTXEFzKNKMgMcF-2TE412oL8pqdap_qomREO78Sym8PzvaTtEFoiYd4oayt7J2B-2sS89Sgf4FuUhQCyA1Mj9lfe3LuSdYuSGsNJvkfy9Yk7zxq9U3O1OzZoTIUzinlqGOEaAFAQYO").replace("OPENID", openid.toString());
        String s1 = HttpClientTool.doGet(replace1, null);
        String s2 = JSONObject.toJSONString(s1);

        System.out.println("getUserInfoBase The basic information of the user is : " + s2);


        WxUser wxUser1 = JSON.parseObject(s1, WxUser.class);

        model.addAttribute("wxUser",wxUser1);
        return "index";

    }

Code to get openId, scope=snsapi_userinfo

Too many, just paste the code

/**
     * getUserInfo  Exchange accessToken through code, obtain openId through accessToken, and obtain user information through openId
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/getUserInfo",method = RequestMethod.GET)
    public void getUserInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");
        System.out.println("code:"+code);

        // Exchange code for the address of accessToken
        String getAccess_token = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        String replace = getAccess_token.replace("APPID", "wxef4d3ff57f4ced1f").replace("SECRET", "e012bfb1fc0bbebc67324112902a2ca6").replace("CODE", code);
        String s = HttpClientTool.doGet(replace, null);

        System.out.println("Obtained accessToken The result is:" + JSONObject.toJSONString(s));

        Object access_token = JSONObject.parseObject(s).get("access_token");
        Object openid = JSONObject.parseObject(s).get("openid");

        // To obtain the basic information of the user, the scope should be snsapi_userinfo;  This access_ A token is a token that calls user information and needs to be passed, which is a web page authentication token;
        String getUserInfo_snsAPI_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        String replace1 = getUserInfo_snsAPI_userinfo.replace("ACCESS_TOKEN", access_token.toString()).replace("OPENID", openid.toString());
        String s1 = HttpClientTool.doGet(replace1, null);
        String s2 = JSONObject.toJSONString(s1);

        System.out.println("The basic information of the user is : " + s2);

    }

Two accesses_ Different tokens

One access_ A token is an ordinary access_token, this ordinary access_token allows us to adjust wechat interfaces, such as creating menus, querying menus, deleting menus, etc; Just like the login token in our web page;

Web authentication access_token, where the scope is snsapi_ When userinfo, call this url

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

Access in_ token, which is obtained in step 2;

Pit description

1. A code can only be used once;

2. Authorized connection can only be opened in wechat page

3,redirect_ The URL configuration is inconsistent with the background. Just check the configuration carefully;

4. How to get the code in vue is a problem. After getting it, you have to refresh the login page; The experience is not good, and there is no good solution for the time being;

5. Two accesses_ The token thief is funny;

  When free, write a complete (manual dog head) in combination with the front end

Say two words of nonsense

The article says so much, it is impossible to say very clearly; If you don't understand, just calm down and slowly understand; If you don't understand, look at station B Video (I only watch the video of station B) ; And my own Demo; For everyone to exchange and learn;

Link: https://pan.baidu.com/s/1TsEobfHrN7R8PmsOCM65pA

Extraction code: y8yv  

If you think it's good, give it a compliment; awesome

Posted by perezf on Mon, 22 Nov 2021 06:14:01 -0800