JAVA实现微信公众号授权

一、前提条件

1.申请微信公众号测试号申请一个微信公众号测试号。测试号申请:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

2.扫码登陆注册,注册成功后就会生成微信公号的appID和appsecret

 

3.需要设置网页授权(体验接口权限表 —》 网页服务 —》网页帐号 —》 网页授权获取用户基本信息

 

 

4.点击修改,填写域名,切记一定不能加上http://协议,

 注:没有域名的话可以用内网穿透动态解析一个域名:https://natapp.cn/register

注册登录成功后可以看到下图,选择免费隧道进行购买

 

 

购买免费的隧道之后,点击我的隧道就会看下图1,同时在本地新建一个natapp目录,并且下载客户端到natapp目录下,将压缩包解压,同时在需要在新建一个config.ini文件,这样我们就拿到了我们的域名(步骤5)

 

下载客户端

 config.ini文件内容:

#将本文件放置于natapp同级目录 程序将读取 [default] 段
#在命令行参数模式如 natapp -authtoken=xxx 等相同参数将会覆盖掉此配置
#命令行参数 -config= 可以指定任意config.ini文件
[default]
authtoken=xxxxxxxxxx                      #对应一条隧道的authtoken
clienttoken= #对应客户端的clienttoken,将会忽略authtoken,若无请留空,
log=none #log 日志文件,可指定本地文件, none=不做记录,stdout=直接屏幕输出 ,默认为none
loglevel=ERROR #日志等级 DEBUG, INFO, WARNING, ERROR 默认为 DEBUG
http_proxy= #代理设置 如 http://10.123.10.10:3128 非代理上网用户请务必留空

 

5.配置域名

 

 

 

 

6.下载微信开发者工具:https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html

二:实现逻辑

网页授权流程分为四步:参考官方:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

1.引导用户进入授权页面同意授权,获取code

public void getCode(HttpServletResponse response) throws Exception{
String appId = "wxbac840ef8aba6443";
// 官方地址
String urlFir = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=";
// 微信申请的域名(提前准备)
String domain = "http://rhvp5f.natappfree.cc";
// 自定义跳转方法
String redirectMethod = "/v1/weChat/callback";
String encoderUrl = getURLEncoderString(domain + redirectMethod);
String url = urlFir + appId + "&redirect_uri=" + encoderUrl + "&response_type=code&scope=snsapi_base" + "&state=123" + "#wechat_redirect";
response.sendRedirect(url);
}
public static String getURLEncoderString(String str) {
String result = "";
if (null == str) {
return "";
}
try {
result = java.net.URLEncoder.encode(str, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}

2.通过 code 换取网页授权access_token(与基础支持中的access_token不同)

public void callback(@RequestParam String code, @RequestParam String state)  {
String appId = "wxbac840ef8aba6443";
String appIdSecret = "dbf4aadaae8dab4e699ff5259c0c0ad8";
log.info("获取code:{}",code);
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
+ appId + "&secret=" + appIdSecret + "&code=" + code + "&grant_type=authorization_code";
Map<String, Object> paramMap = null;
String res = HttpUtil.get(url, paramMap);
String openid = JSONObject.parseObject(res).getString("openid");
//只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。
String unionid = JSONObject.parseObject(res).getString("unionid");
log.info("根据code查询得到openId:{}",openid);
log.info("unionid:{}",unionid);

}

注:网页授权的作用域为snsapi_base,则本步骤中获取到网页授权access_token的同时,也获取到了openid,snsapi_base式的网页授权流程即到此为止。本次文章也是到本步骤结束。

3.如果需要,开发者可以刷新网页授权access_token,避免过期

4.通过网页授权access_token和 openid 获取用户基本信息(支持 UnionID 机制)

三:测试

 

posted @ 2022-12-20 18:15  搬运工强仔  阅读(822)  评论(0编辑  收藏  举报