微信测试公众号
netapp
1 第一步:用户同意授权,获取code
2 第二步:通过 code 换取网页授权access_token
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用户信息(需 scope 为 snsapi_userinfo)
5 附:检验授权凭证(access_token)是否有效
– 来源https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
第2步 就可以获取到 openId 了
代码如下
package com.scd.serverless.controller;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;/*** @author James*/
@RestController
@RequestMapping(value = "/wx")
public class WxController {private static final Logger LOGGER = LoggerFactory.getLogger(WxController.class);public static final String MAP_URL = "http://shootercheng.nat300.top";public static final String WE_CHAT_APP_ID = "wxfcfbe0c738b569a5";public static final String WE_CHAT_APP_SECRET = "002b379cbe62689eab9d0a7cfc227dd8";public static final String WE_CHAT_CLIENT_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";public static final String WE_CHAT_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";@Autowiredprivate RestTemplate restTemplate;@RequestMapping(value = "/config")public String testConfig(HttpServletRequest request) {String signature = request.getParameter("signature");// 时间戳String timestamp = request.getParameter("timestamp");// 随机数String nonce = request.getParameter("nonce");// 随机字符串String echostr = request.getParameter("echostr");LOGGER.info("config return info {}", echostr);// TODO checkreturn echostr;}@RequestMapping(value = "/client")public String genWxUrl() throws UnsupportedEncodingException {String redirectUrl = MAP_URL + "/wx/callback?token=" + UUID.randomUUID();String encodeUrl = URLEncoder.encode(redirectUrl, StandardCharsets.UTF_8.name());String clientUrl = String.format(WE_CHAT_CLIENT_URL, WE_CHAT_APP_ID, encodeUrl);LOGGER.info("client url {}", clientUrl);return clientUrl;}@RequestMapping(value = "/callback")public String wxCallBack(HttpServletRequest request) throws JsonProcessingException {String code = request.getParameter("code");String token = request.getParameter("token");LOGGER.info("current token {}", token);// 校验 tokenString tokenUrl = String.format(WE_CHAT_ACCESS_TOKEN_URL, WE_CHAT_APP_ID, WE_CHAT_APP_SECRET, code);String result = restTemplate.getForObject(tokenUrl, String.class);LOGGER.info("token result {}", result);return result;}}
debug启动服务之后,执行以下步骤