Java for wechat interface development -- authorizing web pages to obtain user information

Background: Recently, the company's business is related to wechat official account and is oriented to wechat interface development

Original address:

1. The development language uses Java
2. Use wechat interface test account for local test
3. use natapp (original ngrok) to map local address to Internet address to realize local debugging of wechat official account

Apply for wechat public platform interface test account

Click here to apply for wechat public platform interface test account

After opening the above link address, you can directly log in by scanning your wechat.  
After successful login, it will be displayed as follows:



Preparation before public network configuration

In our local test, we need to map our local address to the public network. We use a free and very convenient tool: natapp. The following address is the official website of natapp and the tutorial of using natapp:
natapp official website 
NATAPP 1-minute quick novice graphic tutorial 
You can do it step by step according to the above tutorial, and I will introduce it again later (because I encountered some small problems for my own reasons when I followed the tutorial on the official website).


Free tunnel configuration

Register first and log in after successful registration.  






Note the figure above: the local port must be filled with 8080 (this can also be modified after purchase), because the call of wechat public platform interface only supports 80. Recommended reading between developers Technical documents of wechat public platform.  
After the tunnel is purchased successfully, you can see the owned tunnels in my tunnel:


Client download

We visit the natapp client to download. Download the natapp client:





After downloading and decompressing, there will be a natapp Exe file.

Run natapp

Before running natapp, you need to configure it. For detailed tutorials, refer to: Use the local configuration file config ini . config.ini content:



Under the directories of these two files, open the cmd command window and enter:


natapp -authtoken=Yours authtoken

Press enter. After successful operation, the following interface appears:


-Tunnel Status Online means the link is successful
-Version is the current client version. If there is a new version, you will be prompted
-Forwarding currently penetrates the web address or port
-Web Interface is a local web management interface, which can be turned on or off in tunnel configuration. It is only used for web development and testing
-Total Connections total connections
-Avg Conn Time 0.00ms here does not mean, does not mean, does not mean delay, need to pay attention!  

These two are accessible. The difference is that using natapp maps the local area to the public network. Others can access it, but others can't access your

Note: use When accessing, the cmd window of natapp should be open, that is, natapp must be running, otherwise the public network mapping cannot be found.

In this way, our wechat local development and debugging environment is ready.  

Premise: wechat official account that needs to apply for certification; Obtain the corresponding APPID and APPSECRET; In addition, you also need to obtain the user information permission (click "modify" to add the domain name and address of the server). Take the installation and test account of preliminary work as an example to show you:

1) Public test account acquisition

Access the above connection and select "interface test number application" to open it directly You can log in by scanning the code on wechat client.

After logging in, you can get the information of a test public account. There are mainly appId and appsecret parameters, which will uniquely identify a official account, and they need to be used as parameters to obtain user information.

2) Pay attention to official account

Only after paying attention to the official account can users authorize a third party to log in and obtain user information by opening the link with official account information. Therefore, we also need to use our wechat to pay attention to wechat signals. The operations are as follows:

We can see that there is a two-dimensional code on this page. We can scan the two-dimensional code to pay attention to it. The "user list" on the right will have one more user's information. As shown in the figure below:




3) Configure callback function

When we visit a third-party Web page (i.e. our own web page) on the wechat client, we can use the wechat web page authorization mechanism. We need not only the appid and appsecret obtained earlier, but also the domain name setting recalled after the user authorization, that is, where the page will jump after the user authorization. The specific configuration is as follows:

Still on the page just now, there is a "web page authorization to obtain basic user information", click the following modification


Fill in the callback domain name:


If your website has not been blacklisted, it will appear at the top


Then, the domain name configuration is successful! Ready for development.



One. Authorization development process (for details, please refer to the official website, which will not be discussed here): specifically, the web page authorization process is divided into four steps:


1. Guide the user to the authorization page, agree to the authorization and obtain the code

2. Exchange code for web access authorization_ Token (different from access_token in basic support)

3. If necessary, developers can refresh the web page and authorize access_token to avoid expiration

4. Authorize access through web pages_ Obtain basic user information through token and openid (UnionID mechanism is supported)

II According to the above process, I won't say more nonsense and paste the code directly for your reference. Please give me more advice (all appids and APPSECRET in the code use the official website to provide test accounts)

1. Design a public network request tool class:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class WXAuthUtil {
    public static final String APPID = "************";
    public static final String APPSECRET = "*************";
    public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
        JSONObject jsonObject = null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // Convert the returned result into JSON object
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSON.parseObject(result);
        return jsonObject;


2. Implementation class of wechat login (including the action to guide and the callback function after confirming login):
import java.text.ParseException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import test.util.WXAuthUtil;
public class WXLoginController {
    private static final Logger logger = Logger.getLogger(WXLoginController.class);
    private HttpServletRequest request;
    private HttpServletResponse response;
     * Official account wechat login authorization
     * @param request
     * @param response
     * @return
     * @throws ParseException
     * @parameter
    @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
    public String wxLogin() throws ParseException {
        // this url The domain name of must be registered and verified in the official account. This address is the callback address after success
        String backUrl = "";
        // Step 1: users agree to authorize and obtain code
        String getCodeUrl = "" + WXAuthUtil.APPID + "&redirect_uri="
                + URLEncoder.encode(backUrl) + "&response_type=code" + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";
"obtain code, getCodeUrl=" + getCodeUrl);
        // response.sendRedirect(url);
        return "redirect:" + getCodeUrl;// Redirection is required, otherwise it cannot succeed
     * Official account wechat login authorization callback function
     * @param modelMap
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     * @parameter
    @RequestMapping(value = "/callBack", method = RequestMethod.GET)
    public String callBack() throws ServletException, IOException {
        String code = request.getParameter("code");
        // Step 2: Pass code In exchange for web authorization access_token
        String getTokenUrl = "" + WXAuthUtil.APPID + "&secret="
                + WXAuthUtil.APPSECRET + "&code=" + code + "&grant_type=authorization_code";"obtain token,getTokenUrl=" + getTokenUrl);
        JSONObject getTokenJson = WXAuthUtil.doGetJson(getTokenUrl);
         * { "access_token":"ACCESS_TOKEN", "expires_in":7200,
         * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
         */"obtain token,getTokenJson=" + getTokenJson.toJSONString());
        String openid = getTokenJson.getString("openid");
        String access_token = getTokenJson.getString("access_token");
        String refresh_token = getTokenJson.getString("refresh_token");
        // Step 5 verification access_token Whether it is invalid; No need to show
        String vlidTokenUrl = "" + access_token + "&openid=" + openid;"verification token,vlidTokenUrl=" + vlidTokenUrl);
        JSONObject validTokenJson = WXAuthUtil.doGetJson(vlidTokenUrl);"verification token,validTokenJson=" + validTokenJson.toJSONString());
        if (!"0".equals(validTokenJson.getString("errcode"))) {
            // Step 3: refresh access_token((if required)-----Not used for the time being,Reference documents,
            String refreshTokenUrl = "" + openid
                    + "&grant_type=refresh_token&refresh_token=" + refresh_token;
  "Refresh token,refreshTokenUrl=" + refreshTokenUrl);
            JSONObject refreshTokenJson = WXAuthUtil.doGetJson(refreshTokenUrl);
             * { "access_token":"ACCESS_TOKEN", "expires_in":7200,
             * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
  "Refresh token,refreshTokenJson=" + refreshTokenJson.toJSONString());
            access_token = refreshTokenJson.getString("access_token");
        // Step 4: pull user information(need scope by snsapi_userinfo)
        String getUserInfoUrl = "" + access_token + "&openid=" + openid
                + "&lang=zh_CN";"Get user information, getUserInfoUrl=" + getUserInfoUrl.toString());
        JSONObject getUserInfoJson = WXAuthUtil.doGetJson(getUserInfoUrl);
         * { "openid":" OPENID", " nickname": NICKNAME, "sex":"1", "province":"PROVINCE"
         * "city":"CITY", "country":"COUNTRY", "headimgurl":
         * "",
         * "privilege":[ "PRIVILEGE1" "PRIVILEGE2" ], "unionid":
         * "o6_bmasdasdsad6_2sgVt7hMZOPfL" }
         */"Get user information, getUserInfoJson=" + getUserInfoJson.toString());
         * end Access to basic information of wechat users
        // After obtaining the user information, you can redirect and follow your own business logic......
        // The incoming logic is your system logic. Please play it freely
        return getUserInfoJson.toString();


Original address:

Tags: Java

Posted by burnside on Wed, 18 May 2022 09:23:25 +0300