获得code后,您需要通过code换取access_token和openid。具体步骤如下:
-
发送请求到微信服务器:使用获得的code,appid和secret向微信服务器发送请求。
-
解析响应数据:微信服务器会返回包含access_token和openid的JSON数据,您需要解析这个数据。
第一步:index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Welcome</title>
<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script>
function getOpenId() {
const appId = document.getElementById('wechatAppId').value;
const redirectUri = document.getElementById('wechatRedirectUri').value;
console.log('AppID:', appId);
console.log('Redirect URI:', redirectUri);
if (!appId) {
alert('AppID 不能为空');
return;
}
const encodedAppId = encodeURIComponent(appId);
const encodedRedirectUri = encodeURIComponent(redirectUri);
const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${encodedAppId}&redirect_uri=${encodedRedirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
console.log('URL:', url);
window.location.href = url;
}
</script>
</head>
<body>
<h1 th:text="${message}">Welcome to Spring Boot!</h1>
<h2>Your OpenID is: <span th:text="${openid}">OpenID</span></h2>
<input type="hidden" id="wechatAppId" th:value="${wechatAppId}" />
<input type="hidden" id="wechatRedirectUri" th:value="${wechatRedirectUri}" />
<button onclick="getOpenId()">点击获取OpenID</button>
</body>
</html>
第二步:WeChatController
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Controller
public class
WeChatController {
private static final Logger logger = LoggerFactory.getLogger(WeChatController.class);
@Value("${wechat.appid}")
private String wechatAppId;
@Value("${wechat.redirect_uri}")
private String wechatRedirectUri;
@GetMapping("/wechat")
public String wechat(Model model) {
logger.info("wechatAppId: {}", wechatAppId);
logger.info("wechatRedirectUri: {}", wechatRedirectUri);
model.addAttribute("message", "Welcome to Spring Boot!");
model.addAttribute("openid", ""); // 添加 openid 变量,暂时设为空字符串
model.addAttribute("wechatAppId", wechatAppId);
model.addAttribute("wechatRedirectUri", wechatRedirectUri);
return "index";
}
}
第三步:callback.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Callback</title>
</head>
<body>
<h1 th:text="${message}">Callback</h1>
<p>Authorization Code: <span th:text="${code}">No Code</span></p>
<p>Your OpenID is: <span th:text="${openid}">OpenID</span></p>
<p>Your Nickname is: <span th:text="${nickname}">Nickname</span></p>
<p>Your Profile Picture: <img th:src="${headimgurl}" alt="Profile Picture"></p>
</body>
</html>
第四步:WeChatCallbackController
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
@Controller
public class WeChatCallbackController {
@Value("${wechat.appid}")
private String appId;
@Value("${wechat.appsecret}")
private String appSecret;
@GetMapping("/wechat/callback")
public String callback(@RequestParam("code") String code, Model model) {
String tokenUrl = String.format(
"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
appId, appSecret, code
);
RestTemplate restTemplate = new RestTemplate();
String tokenResponse = restTemplate.getForObject(tokenUrl, String.class);
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode tokenNode = objectMapper.readTree(tokenResponse);
String accessToken = tokenNode.get("access_token").asText();
String openId = tokenNode.get("openid").asText();
String userInfoUrl = String.format(
"https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN",
accessToken, openId
);
String userInfoResponse = restTemplate.getForObject(userInfoUrl, String.class);
JsonNode userInfoNode = objectMapper.readTree(userInfoResponse);
model.addAttribute("openid", openId);
model.addAttribute("nickname", userInfoNode.get("nickname").asText());
model.addAttribute("headimgurl", userInfoNode.get("headimgurl").asText());
model.addAttribute("code", code);
} catch (IOException e) {
e.printStackTrace();
model.addAttribute("openid", "Error parsing JSON response");
}
return "callback";
}
}