WechatAPI_BackEnd_TOKEN_OPENID
一、前期准备
- 有一台公网IP的服务器
- 注册域名并进行备案(保证合法开启80端口)
- 在微信公众号平台 AND 小程序平台 填写服务器相关配置和回调地址
- 拉取Demo、数字签名等等
- 进行微信认证
- 可以直接用80端口运行、也可以在有域名的情况下进行绑定其他端口。
#二、获取Token(用于对公众号和小程序进行操作)
“原理:你去异步访问他、带上相应参数、成功的话就能下载一个文件、这个文件里面就有相应的token”
1.公众号
1. 调用service方法(从网络Url中下载文件):
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=唯一标识&secret=唯一密码
2. 读取文件中的Token
public String UpdateToken(HttpServletRequest request) throws IOException {
String tokenURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx2b1927149d977111&secret=bf18aa42e02f697211a496882c7c1111";
File TokenFile = new File(this.getClass().getResource("").getFile() + "/token.txt");
HTTPUtils.downLoadFromUrl(tokenURL, "token.txt", TokenFile.getParent());
System.out.println(TokenFile.getAbsolutePath());
List<String> stringList = IOUtils.readLines(new FileInputStream(TokenFile));
String token = stringList.get(0);
String[] tokenParse = token.substring(1, token.length()).replaceAll("\"", "").split(",");
String[] result = tokenParse[0].split(":");
if (result[0].equals("access_token")) {
System.out.println("获取token成功");
System.out.println(result[1]);
request.getServletContext().setAttribute("WeachatToken", result[1]);
return result[1];
} else {
System.out.println("获取token失败");
return "获取token失败";
}
}
2.小程序
三、获取Openid(对公众号和小程序的用户进行操作)
“其实原理就是、你去重定向他、带上他想要的东西。然后他会吸收掉参数、然后来访问你的接口”
1.进行消息推送(公众号)
1.拿到code:
进行重定向https://open.weixin.qq.com/connect/oauth2/authorize?appid=唯一标识&redirect_uri=" + 回调地址(给需要openid的方法) + "&response_type=code&scope=snsapi_userinfo&state=13392876810#wechat_redirect=asd
2.拿到Openid:
写一个API接口接收code,访问https://api.weixin.qq.com/sns/oauth2/access_token?appid=唯一标识&secret=唯一密码&code=" + 第一步会带来的参数 + "&grant_type=authorization_code
2.进行消息推送(小程序)
END:codding项目地址
https://git.dev.tencent.com/a83841070/WechatAPI_BackEnd_TOKEN_OPENID.git
git@git.dev.tencent.com:a83841070/WechatAPI_BackEnd_TOKEN_OPENID.git