1. Registration test number
2. Understand the acquisition logic
To obtain the openid of WeChat, you need to visit a URL provided by WeChat to obtain the code.
Visit another URL provided by WeChat to obtain the openId.
The two links are:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE
https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code
3. Select the preview environment
The first link needs to be opened on the WeChat client, you can choose WeChat developer tools
Select official account webpage project
After opening, enter the first URL address in the address bar, followed by the redirected web page
Note: The address filled in this redirect_uri needs to be configured in the official account or the web page account in the test account
After the jump, you can see that there are two parameters in the address bar, code and state. At this time, we can get the code we need
4. Get openId
After getting the code, you can fill in the required content through the second link and get the openId.
It is recommended to obtain the openId from the backend. There may be a series of problems such as cross-domain, unavailable code, etc. The code can only be used once.
@GetMapping("/getOpenId")
@ApiOperation("获取OpenId")
public JSONObject getOpenId(@RequestParam("code") String code){
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type={grant_type}";
HashMap<String,String> params = new HashMap<>();
params.put("appid","");
params.put("secret","");
params.put("code",code);
params.put("grant_type","authorization_code");
String result = new RestTemplate().getForEntity(url, String.class, params).getBody();
return JSONObject.fromObject(result);
}