简介:
小程序获取OpenId有两种方式,第一种是使用云开发获取,第二种是服务端获取,这里讲述的是第二种使用服务端获取OpenId的方式,如下图调用登陆凭证校验接口,服务端采用springboot框架(只包含服务端代码)。
1.配置文件
因为采用Https调用,所以我们需要提前设置HttpClient。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.7</version>
</dependency>
2.OpenId获取
在进行openid获取的时候,code由前端进行提供,我们需要给前端写调用接口,这里就不进行描述了,只涉及服务端调用微信接口获取openId。
微信提供的接口地址:
GET https://api.weixin.qq.com/sns/jscode2session
请求参数有四个:
示例:
GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
因为采用的是路由拼接的形式,所以我们的请求是没有请求头和请求体的,我们要把所有的东西都拼接到路由上。
String url = UriComponentsBuilder.fromHttpUrl(baseUrl)
.queryParam("appid",appId)
.queryParam("secret",appSecret)
.queryParam("js_code",code)
.queryParam("grant_type","authorization_code")
.build().toUriString();
HttpEntity<HashMap<String, Object>> entity = new HttpEntity<>(null, null);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
其中的code由前端传递,剩余部分的内容都是提前设置好的。
为了方便我们后续获取数据,我们将传递回来的数据转换成map类型。
JSONObject jsonObject = JSON.parseObject(response.getBody());
Map<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(jsonObject));
返回参数:
返回数据示例:
{
"openid":"xxxxxx",
"session_key":"xxxxx",
"unionid":"xxxxx",
"errcode":0,
"errmsg":"xxxxx"
}
错误码: