java Wechat Public Development (Original Page - Web Page Authorization)

In the previous chapter: java Wechat Public Development (Original Text - Message Management)
Since it is the development of public numbers, of course, it will involve our web side. After learning the previous chapters, the little friends will find that the message sent on public numbers can easily get the openid of the sender's Wechat. Then how can we get it when we jump the web page through the menu or graphic message on public numbers? What about the information of micro-credit users?
Before we start, let's talk about two ways of authorizing the public number:

The explanation of the document is clear, that is to say
With snsapi_base as the web authorization sponsored by scope, users do not need to click authorization manually, and only get the openid of micro-credit users.
Web authorization initiated by snsapi_userinfo for scope requires users to click on authorization manually and obtain basic information of users.
Another thing to note is that access_token in Web authorization is different from the access_token we mentioned in the first two sections.

After a brief understanding, let's have a real fight: (this code is based on the previous section)
This is the dependence used in this project:

        <!-- jackson rely on -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.6</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>

        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- JSONObject Object-dependent jar package -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.2.3</version>
            <classifier>jdk15</classifier><!-- Appoint jdk Edition -->
        </dependency>
        <!-- WeChat httpclient Getting Users openId-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.1</version>
        </dependency>
Step 1: The user agrees to authorize and gets the code

Interface: https://open.weixin.qq.com/connect/oauth2/authorize?Appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
This is the parameter description required for the interface:

Encapsulated the interface URL, WechatConstants.java:

//Web page authorization
    public static final String WEB_AUTHORIZE_URL= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";

    /**
     * Page authorization url obtained by filling in the required parameters
     * @param redirect_uri Callback Link Address Redirected after Authorization
     * @param isSilence Is it a silent way?
     * @param state Optional
     * @return
     */
    public static String getWeb_authorize_url(String redirect_uri,boolean isSilence,String state){
        return WEB_AUTHORIZE_URL.replace("APPID", APPID)
                .replace("REDIRECT_URI",redirect_uri)
                .replace("SCOPE",isSilence?"snsapi_base":"snsapi_userinfo")
                .replace("STATE",state);
    }

Define our controller and create TestController.java

/**
 * Test Public Number
 * @author mage on 2019/9/5
 */
@Controller
@RequestMapping("test")
public class TestController {

    private Logger log = LoggerFactory.getLogger(TestController.class);
    /**
     * Users click on url to jump after authorization
     * @param code The code (code) obtained after successful authorization is used as a ticket in exchange for access_token.
     *             Each user's authorization will have a different code, which can only be used once and will not automatically expire for 5 minutes.)
     * @param state (Optional parameters)
     * @return
     */
    @GetMapping("/authorizeInfo")
    @ResponseBody
    public String authorizeInfo(String code,@RequestParam(value = "state",required = false) String state){
        log.info("[code]:--[{}]",code);
        log.info("[state]:--[{}]",state);
        return "SUCCESS";
    }
}

Open our natapp, penetrate the external network, and modify the docking url of the test number to the url generated by natapp

Then we put our interface url into one of the menu options in the custom menu (if it's a buddy who watches the inserts, please refer to it). java Wechat Public Development (Original - Custom Menu)

And run the main method to recreate the new menu.
Don't forget the most important step: open our test number and drop down to find the web account of the web service. Click here to modify it.
Put the url on our natapp. Note: Don't bring http:.//

Everything is OK, but it's OK. Re-focus our test public number. Click on the menu containing our authorized url. Log results:

But there is a problem here. The ideal authorization confirmation page did not appear, but directly jumped to the original controller. Is it too long since Wechat Public Number was developed and the official update was made? Looking at the document, I found that:

The original api is silent authorization for users who have paid attention to the public number, but it can also normally get the code parameter. If you want to experience the user clicking on the authorized page, you can redirect it to the authorized URL using HttpServletResponse, by adding URL to the menu or graphic message on the public number. Ordinary Controller, Controller uses HttpServletResponse to redirect to the authorization URL to understand the manual authorization page, the specific code implementation is not done, this is not the focus.
The purpose of Web authorization is to get the basic information of micro-credit users, how to get it or not, to achieve the goal.

Step 2: Exchange code for web page authorization access_token

After getting the code, we also need to get access_token through code, step by step, to get the api interface of access_token:

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


Not only can access_token be obtained, but also the openid of microcredit users, which is the most critical.

Encapsulating URL s

//Web Authorization code Gets the url of access_token
    public static final String WEB_AUTHORIZE_CODE_URL =  "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    /**
     * The url that fills in the code after the page authorizes to get the code
     * @param code
     * @return
     */
    public static String getWeb_authorize_code_url(String code){
        return WEB_AUTHORIZE_CODE_URL.replace("APPID", APPID)
                .replace("SECRET",APPSECRET)
                .replace("CODE",code);
    }
	

Controller TestController.java plus code

      JSONObject get = WeixinUtil.httpRequest(WechatConstants.getWeb_authorize_code_url(code), "GET", null);
      String access_token = get.getString("access_token");
      String openid = get.getString("openid");
      log.info("[Web page authorization access_token]: --[{}]",access_token);
      log.info("[Micro Credit Users openid]: --[{}]",openid);

Test and test, look at the log

Step 4: Pull User Information

Now that access_token and openid are available, the next step is to get the user information we need, but the premise of this interface is to authorize the scope in the URL to be snsapi_userinfo.
Pull user information api interface:

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


The parameter description is not screenshot, you can go to the official website to check if you need it.

Encapsulating URL s

	//access_token User Basic Information for Web Authorization
    public static final String WEB_AUTHORIZE_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    /**
     * Web page authorization obtains access_token and openid and then fills in url
     * @param access_token Web page authorization access_token (different from basic access_token)
     * @param openid (User Unique ID openid)
     * @return
     */
    public static String getWeb_authorize_access_token_url(String access_token,String openid){
        return WEB_AUTHORIZE_ACCESS_TOKEN_URL.replace("ACCESS_TOKEN",access_token)
                .replace("OPENID",openid);
    }

TestController.java complete code

/**
 * Test Public Number
 * @author mage on 2019/9/5
 */
@Controller
@RequestMapping("test")
public class TestController {

    private Logger log = LoggerFactory.getLogger(TestController.class);
    /**
     * Users click on url to jump after authorization
     * @param code The code (code) obtained after successful authorization is used as a ticket in exchange for access_token.
     *             Each user's authorization will have a different code, which can only be used once and will not automatically expire for 5 minutes.)
     * @param state (Optional parameters)
     * @return
     */
    @GetMapping("/authorizeInfo")
    @ResponseBody
    public String authorizeInfo(String code,@RequestParam(value = "state",required = false) String state){
        log.info("[code]:--[{}]",code);
        log.info("[state]:--[{}]",state);
        JSONObject get = WeixinUtil.httpRequest(WechatConstants.getWeb_authorize_code_url(code), "GET", null);
        String access_token = get.getString("access_token");
        String openid = get.getString("openid");
        log.info("[Web page authorization access_token]: --[{}]",access_token);
        log.info("[Micro Credit Users openid]: --[{}]",openid);
        JSONObject userInfo = WeixinUtil.httpRequest(WechatConstants.getWeb_authorize_access_token_url(access_token,openid), "GET", null);
        log.info("[User Basic Information]: --[{}]",userInfo);
        return "SUCCESS";
    }
}

Test and test, look at the log

Be accomplished.
Summary: The purpose of Wechat Web page authorization is obvious, which is to make it easy for our Java Web to get the basic information of Weichat users. That is to say, the usual business system is bound to Wechat public number. In fact, it is to use the business data in the project and the openid of Weichat users (because openid is the only user standard). Understanding) Data binding, so that users can access user information when they enter the public number web pages to match database business data and obtain the user's business data. Of course, it's not just these functions. More uses should be explored slowly by all of you. (It may not be good enough, I hope you can point out the shortcomings.)
At the end of this chapter, if you have questions or suggestions, you can leave a message in the comments section below.
git Source Sharing: --" Poke here

Keywords: Java JSON JDK Apache

Added by fishown on Sat, 07 Sep 2019 15:00:41 +0300