SpringBoot micro-channel users in obtaining information has never been easier!

Foreword

I do not know if you ever fight a lot on the micro-letter friends to invite bargain feature, which achieved first need to consider is to gather information micro-channel users. Obtain user information is to gather information at the user's micro-channel public number, today I will say something about how to obtain user information from the micro-channel public number.

Need to declare that it is important to obtain user information in the public micro-channel service number is the number of rights only, not the individual subscription number is right.

Obtain public information actual number of users

The first step you need to apply for web interface test number and authorization settings

Visit the following links interface testing To apply.

https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Requesting_an_API_Test_Account.html

Test selection interface application number, as shown below:Here Insert Picture Description

Here Insert Picture Description
Click Sign In to log scan code, as shown below:
Here Insert Picture Description
After logging in as shown below:
Here Insert Picture Description
In the following pages the account column add pages authorized IP or domain name.
Here Insert Picture Description
Here Insert Picture Description

For testing purposes I set here becomes loopback address, it is best to set a specific IP address or domain name information. Domain names and IP addresses do not add http or https. Here IP and domain name can be a network address.

Authorization to set up the page here!

The second step is to download the micro-letter web developer tools, can be tested in a PC.
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Web_Developer_Tools.html
Here Insert Picture Description
fool step by step installation.

The third step is to see micro-channel and complete the operation code for tutorial

The next section of code is written, before developing first need to look for tutorials micro-channel public number user information:
by visiting: https: //developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html. Specific micro-channel user information acquiring operation following 4 steps.
Here Insert Picture Description
The first step: user consent, access code

Operation is spliced ​​codes guide the user through micro-channel authorization address, and then redirected to the micro-channel services, micro-channel service in redirected to our server based on the URL redirection and carry code. This step needs to be configured and have a public number appid redirect_uri.

Note that the address needs to encode the redirection, the specific operation as shown in the following code:

String url = URLEncoder.encode(request.getRequestURL().toString());

Specific address as shown below: the red frame in our public needs to be changed and redirect_uri number appid information, other contents do not change.
Here Insert Picture Description
After the program address will redirect the user to authorize, as shown below:
Here Insert Picture Description
When a user clicks consent, micro-channel service will be redirected back to the redirection address in accordance with our services and carry code.

The second step is to obtain the code page under the authority access_token and openid.

As shown in the following micro-channel calls the API, replacing red frame code acquired code, other content without making any changes.
Here Insert Picture Description
The third step: to refresh access_token (if needed)

access_token valid for 7200s, when the access_token expires, you can use refresh_token refreshed, refresh_token valid for 30 days, after refresh_token failure, requiring users to re-authorize. Do can not do this step, we are here to bypass this step.

The fourth step: pulling the user information (as required scope snsapi_userinfo)

Two pages on the difference between authorized scope of instructions

1 to snsapi_base authorized scope for web-initiated, is used to get openid enter the user's page, and is silent authorized and automatically jump to the page callback. It is perceived by the user directly into the callback page (often a business page)

2, pages mandate to snsapi_userinfo as the scope initiated, is used to obtain the basic information of the user. However, this requires the user to manually authorize consent, and because the user agrees, so I do not need attention, you can get the basic information of the user after authorization.

Obtaining information according to a user access_token micro-channel and the second step opendId acquired. API calls micro-channel shown in FIG. Follows, and the obtained access_token opendId replaced in the red frame follows the drawings, the other without any changes. Json returned information is the user information of the public good numbers.
Here Insert Picture Description

Finished operating procedures, the next step is code. Specific micro-channel user information acquiring Controller as follows:

@RestController
@RequestMapping("/weixin")
public class WeiXinDemoController {
    @Autowired
    private WeiXinService weiXinService;

    @RequestMapping("/getWeiXinUserInfo")
    public String getWeiXinUserInfo(String code,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IOException{
        //第一步:用户同意授权,获取code
        if (code == null) {
            String url = URLEncoder.encode(request.getRequestURL().toString());
            String authorizeUrl = weiXinService.buildAuthorizeURL(url);
            response.sendRedirect(authorizeUrl);
            return null;
        }
        //第二步:通过code换取网页授权access_token和openid
        String htmlInfo = "";
        Map<String, Object> openIdInfo = weiXinService.getOpenIdInfo(code);
        String errcode = (String)openIdInfo.get("errcode");
        if(StringUtils.isEmpty(errcode)){
            //第四步:拉取用户信息(需scope为 snsapi_userinfo)根据access_token和OpenId
            Map<String, Object> weiXinUserInfo = weiXinService.getWeiXinUserInfo(openIdInfo);
            String userInfohtml = createUserInfoHtml(weiXinUserInfo);
            return userInfohtml;
        }
        return htmlInfo;
    }
@Component
@ConfigurationProperties(prefix="wx")
public class WeiXinConfig {
    
    private String appID;
    private String mchID;
    private String appsecret;
    private String key;
    
    //省略getter and setter
}

application.properties arranged as follows:
Here Insert Picture Description
micro-channel processing in WeiXinService the core, when implemented by a micro channel RestTemplate interface call.

Splicing guide the user address micro-channel authorization code is as follows:

    /**
     * 拼接用户授权重定向的URL
     * @param url
     * @return
     */
    public String buildAuthorizeURL(String url){
        
        return concatAuthorizeURL(url);
    }
        private String concatAuthorizeURL(String url) {
        StringBuilder authorizeUrl = new StringBuilder(AUTHORIZEURL);
        authorizeUrl.append("?appid=").append(weiXinConfig.getAppID());
        authorizeUrl.append("&redirect_uri=").append(url);
        authorizeUrl.append("&response_type=code");
         //snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),
         //snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
        authorizeUrl.append("&scope=snsapi_userinfo");
        authorizeUrl.append("&state=").append("STATE");
        authorizeUrl.append("#wechat_redirect");
        return authorizeUrl.toString();
    }

According to obtain authorization code pages and access_token openid code is as follows:

    /**
     * 获取 access_token 和 openid
     * @param code
     * @return
     */
    public Map<String,Object> getOpenIdInfo(String code){
        
        String getAccessTokenUrl = concatGetOpenIdInfoURL(code);
        String json = postRequestForWechat(getAccessTokenUrl);
        Map<String,Object> map = jsonToMap(json);
        
        return map;
    }
    private String concatGetOpenIdInfoURL(String code) {
        StringBuilder getAccessTokenUrl = new StringBuilder(GE_TACCESSTOKEN_URL);
        getAccessTokenUrl.append("?appid=").append(weiXinConfig.getAppID());
        getAccessTokenUrl.append("&secret=").append(weiXinConfig.getAppsecret());
        getAccessTokenUrl.append("&code=").append(code);
        getAccessTokenUrl.append("&grant_type=authorization_code");
        return getAccessTokenUrl.toString();
    }
    private String postRequestForWechat(String getAccessTokenUrl) {
        ResponseEntity<String> postForEntity = restTemplate.postForEntity(getAccessTokenUrl, null, String.class);
        String json = postForEntity.getBody();
        return json;
    }
        private Map jsonToMap(String json) {
        Gson gons = new Gson();
        Map map = gons.fromJson(json, new TypeToken<Map>(){}.getType());
        return map;
    }

Micro-channel user information acquired by the code and access_token openid follows:

    /**
     * 获取微信用户信息通过  access_token 和 openid
     * @param map
     * @return
     */
    public Map getWeiXinUserInfo(Map<String, Object> map) {
        
        String getUserInfoUrl = concatGetWeiXinUserInfoURL(map);
        String json = getRequestForWechat(getUserInfoUrl);
        Map userInfoMap = jsonToMap(json);
        
        return userInfoMap;
    }
        private String concatGetWeiXinUserInfoURL(Map<String, Object> map) {
        String openId = (String) map.get("openid");
        String access_token = (String) map.get("access_token");
        // 绕过检验授权凭证(access_token)是否有效
        StringBuilder getUserInfoUrl = new StringBuilder(GE_USERINFO_URL);
        getUserInfoUrl.append("?access_token=").append(access_token);
        getUserInfoUrl.append("&openId=").append(openId);
        getUserInfoUrl.append("&lang=zh_CN");
        
        return getUserInfoUrl.toString();
    }
    private String getRequestForWechat(String getUserInfoUrl) {
        ResponseEntity<String> postForEntity = restTemplate.getForEntity(getUserInfoUrl.toString(), String.class);
        String json = postForEntity.getBody();
        return json;
    }

test

After downloading the micro-letter web developer tools to complete, can be installed in accordance fool. After installation is complete open web developer tools, public numbers selected page as shown below.
Here Insert Picture Description
Enter http: 127.0.1: 8090 / sbe2 / weixin / getWeiXinUserInfo, users will see information about the number of public test.
Here Insert Picture Description
Under normal circumstances we configured via interface testing environment domain name or number to test IP, after the test can be configured through the web domain name on the authorization service number, by the way can be replaced appid appid service number in the configuration of our project. Specific operation is as follows:
Here Insert Picture Description
Here Insert Picture Description

summary

Get public micro-channel number of the user information is the step of: a first step of splicing guide users authorized to address the micro channel then redirects the service based on the address, the second step to get authorization code, and obtaining access_token OpenId The code, according to a third acquisition step and access_token OpenId WeChat user information.

I introduce here the most simple three-step, in terms of normal access_token also need to verify the validity of this step can also be cached in the access_token by Reid and set the expiration time, after the failure refresh access_token.

Here again emphasize that provides micro-channel operation documentation must look at a few, because many of the details have been described in the document. When you put the micro-channel operation to provide documentation to see through, you will feel that it is a API calls.

The sample code

Specific code examples, please see the spring-boot-2.x-weixin my GitHub repository springbootexamples of view.

GitHub:https://github.com/zhuoqianmingyue/springbootexamples

Guess you like

Origin www.cnblogs.com/jerry126/p/11531308.html