1、介绍
1.1、OpenID是什么
openId是用户在当前微信公众号下的唯一标识,就是说通过这个openId,就能区分在这个公众号下具体是哪个用户。
1.2 、拓展:UnionID的作用
如果开发者拥有多个移动应用、网站应用和公众账号,可通过获取用户基本信息中的unionid来区分用户的唯一性,因为同一用户,对同一个微信开放平台下的不同应用(移动应用、网站应用和公众账号),unionid是相同的。
2、获取OpenID流程
2.1、获取用户登录凭证code
需要在微信小程序调用登录开放接口 wx.login()
,获取用户登录凭证code
。
wx.login()接口说明:
wx.login({
//成功返回
success:(res)=>{
console.log(res);
let code = res.code
}
})
2.2、获取OpenID
在服务端调用code2Session
接口,获取OpenID
。
接口说明 :
3、Java代码
3.1、maven引用
需要用到hutool
的HttpUtil
工具类,也可自己实现http
的get
方法。
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.27</version>
</dependency>
3.2、测试类
import cn.hutool.http.HttpUtil;
import org.junit.Test;
/**
* 微信测试类
*/
public class WechatDirectTest {
//微信小程序获取OpenID
@Test
public void wechatMiniGetOpenID(){
String code = "微信小程序 wx.login 接口返回的code";
String wechatMiniAppid = "微信小程序appId";
String wechatMiniAppSecret = "微信小程序开发密钥";
String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
, wechatMiniAppid , wechatMiniAppSecret , code);
System.out.println("微信获取openId 请求地址:" + url);
String httpReponse = HttpUtil.get(url);
System.out.println("微信获取openId 返回参数:" + httpReponse);
}
}