Preface
I don't know if you have ever participated in the function of inviting Weixin friends to bargain. The first thing to consider is to get the information of Weixin users. To get user information is to get information about micro-credit users under public numbers. Today I will talk about how to get micro-credit users information from public numbers.
It needs to be declared that the right to access user information under Wechat Public Number is only provided by Service Number, which is not provided by Personal Subscription Number.
Access to Public Number User Information
The first step is to apply for the test number of the interface and set the authorization of the web page.
Visit the links below to apply for the Interface Test Number.
https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Requesting_an_API_Test_Account.html
Select the interface test number application, as shown in the following figure:
Or direct access: https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login as shown in the following figure:
Click on the login to scan the login code, as shown in the following figure:
After login, the following figure is shown:
Add the IP or domain name authorized by the web page in the page account column below.
In order to test conveniently, I set the loop address here, it is better to set the specific IP address or domain name information. Domain name and IP address do not add http or https. Here IP and domain names can be intranet addresses.
The authorization of the web page is set up here!
The second step is to download the Wechat web Developer Tool, which can be tested on PC.
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Web_Developer_Tools.html
Fool type step by step installation can be.
Step 3 Look at the Wechat Operations Tutorial and complete the code implementation
Next is the code part. Before developing, we need to look at the tutorial to get the information of Wechat Public Number users.
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html. There are four steps to obtain micro-credit user information.
Step 1: The user agrees to authorize and gets the code
The operation of the code is to stitch and guide users to the authorized address of Wechat, and then redirect to the Wechat service. The Wechat service redirects to our server according to the redirected URL address and carries code. In this step, you need to configure the public number appid and redirect_uri.
Note that the redirected address needs to be encode d below, as shown in the following code:
String url = URLEncoder.encode(request.getRequestURL().toString());
The specific address is shown in the following figure: the red box location needs to be changed to our public number appid and redirect_uri information, other content need not be changed.
When the program redirects the address, the user is authorized, as shown in the following figure:
After the user clicks and agrees, the Wechat service will redirect back to our service according to the redirection address and carry the code.
The second step is to get the access_token and openid authorized by the code.
Call the Wechat API as shown below. The red box code is replaced by the acquired code. No other changes are required.
Step 3: Refresh access_token (if necessary)
Access_token is valid for 7200s. When access_token expires, refresh_token can be used to refresh it. refresh_token is valid for 30 days. When refresh_token expires, users need to re-authorize it. This step can be done or not. We'll bypass it here.
Step 4: Pull user information (snsapi_userinfo is required for scope)
On the Difference between Two Scopes of Web Page Authorization
1. Web authorization initiated by snsapi_base for scope is used to obtain the openid of the user who enters the page, and it is silent authorization and automatically jumps to the callback page. What users perceive is that they go directly to callback pages (often business pages).
2. Web authorization initiated by snsapi_userinfo for scope is used to obtain the basic information of users. However, this kind of authorization requires the user's manual consent, and because the user has agreed to it, the basic information of the user can be obtained after authorization without any concern.
According to the access_token and opendId obtained in the second step, the information of micro-credit users is obtained. Call the Wechat API shown in the following figure and replace the access_token and opendId obtained with the red box location in the following figure without any other changes. The json information returned is the user information of the public good name.
After the operation process, the next step is the code implementation. Specific access to micro-credit user information Controller content is 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{ //Step 1: The user agrees to authorize and gets the code if (code == null) { String url = URLEncoder.encode(request.getRequestURL().toString()); String authorizeUrl = weiXinService.buildAuthorizeURL(url); response.sendRedirect(authorizeUrl); return null; } //Step 2: Exchange code for web authorization access_token and openid String htmlInfo = ""; Map<String, Object> openIdInfo = weiXinService.getOpenIdInfo(code); String errcode = (String)openIdInfo.get("errcode"); if(StringUtils.isEmpty(errcode)){ //Step 4: Pull user information (snsapi_userinfo for scope) according to access_token and OpenId Map<String, Object> weiXinUserInfo = weiXinService.getWeiXinUserInfo(openIdInfo); String userInfohtml = createUserInfoHtml(weiXinUserInfo); return userInfohtml; } return htmlInfo; }
The code of Wechat Public Number Configuration Class is as follows:
@Component @ConfigurationProperties(prefix="wx") public class WeiXinConfig { private String appID; private String mchID; private String appsecret; private String key; //Omit getter and setter }
The application.properties configuration is as follows:
The core processing of Wechat is in WeiXinService, which is implemented by RestTemplate when calling the Wechat interface.
Stitching guides users to authorize the address code of Wechat as follows:
/** * Splicing User Authorization Redirected URL s * @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 (no authorization page pops up, jump directly, only get user openid) //snsapi_userinfo (pop-up authorization page, you can get nicknames, gender, location through openid). Moreover, even in the absence of concern, users can obtain their information as long as they are authorized) authorizeUrl.append("&scope=snsapi_userinfo"); authorizeUrl.append("&state=").append("STATE"); authorizeUrl.append("#wechat_redirect"); return authorizeUrl.toString(); }
access_token and openid codes are obtained according to code as follows:
/** * Get access_token and 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; }
The microcredit user information code obtained by access_token and openid is as follows:
/** * access_token and openid are used to obtain micro-credit user information * @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"); // Bypass the validity of 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 Wechat Web Developer Tool, install it according to the fool style. After installation, open the web developer tool and select the public number page as shown in the figure below.
Enter http:127.0.1:8090/sbe2/weixin/getWeiXinUserInfo and you will see the user information for the test public number.
In general, we configure the test environment domain name or IP through the interface test number. After the test passes, we can configure the web authorization domain name on the service number. By the way, we can change the appid of our project configuration into the appid of the service number. The specific operation is as follows:
Summary
The first step is to connect and guide the user's authorized address and redirect it to the Wechat service according to the address. The second step is to get the authorized code, access_token and openid according to the code, and the third step is to get the user's information according to access_token and openid.
I'll introduce the simplest three steps. Normally, we also need to verify whether access_token is valid. This step can also be cached into Redis by caching access_token and setting an expiration time to refresh access_token when it fails.
Here again and again, Wechat must read more operation documents, because many details are explained in the documents. When you see through the operation documents provided by Wechat, you will feel that it is actually an API call.
Code example
See spring-boot-2.x-weixin in my GitHub repository spring bootexamples for specific code examples.
GitHub: https://github.com/zhuoqianmingyue/springbootexamples