微信公众号获取openid
1.设置域名
使用内网穿透工具:natapp.cn,可以同时申请域名,并使用该域名进行穿透(12元/月),

window下:下载natapp,进入natapp.exe的目录后:natapp -token=TOKEN(图中的)
2.申请微信公共测试账号,登录后页面搜索网页授权,修改添加刚才进行穿透的域名进行网页授权(没有http前缀)
以下参照:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0
3.获取code:填充https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_re
4.使用code换取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
controller层代码:
@RestController
@RequestMapping("weixin")
@Slf4j
public class WeixinController {
@GetMapping("auth")
public void auth(@RequestParam("code") String code){
log.info("进入auth方法");
log.info("code={}",code);
RestTemplate restTemplate=new RestTemplate();
String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx2757df78874fdcfa&secret=d3f7ea9e5b8ba542e5a50504b67e13e3&code="+code+"&grant_type=authorization_code";
String response=restTemplate.getForObject(url,String.class);
log.info(response);
}
}

浙公网安备 33010602011771号