java后端获取微信的openId


-- 首先说明一下  code 只能用一次并且有使用期限,好像是五分钟,通过前端传过来code和后台配置的appSecret和appid完成获取openid的操作。

public class WxUtil {
private static final String openIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
public static OpenIdAndSessionKey getOpenId(String appId, String secret, String code) {
OpenIdAndSessionKey openIdAndSessionKey =new OpenIdAndSessionKey();
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
String requestUrl = String.format(openIdUrl, appId, secret, code);
HttpGet httpGet = new HttpGet(requestUrl);
HttpEntity responseEntity = httpClient.execute(httpGet).getEntity();
if (responseEntity != null) {
String responseStr = EntityUtils.toString(responseEntity);
if (responseStr.contains("openid")) {
WxResponse wxResponse = JsonUtil.toJsonObject(responseStr, WxResponse.class);
openIdAndSessionKey.setOpenId(wxResponse.getOpenid());
openIdAndSessionKey.setSessionKey(wxResponse.getSession_key());
return openIdAndSessionKey;
}
}
}catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
}
这里我用了一个openIdAndSessionKey类来接受微信后台返回给我的openId和SessionKey,如果想获取手机号码那就会用到这个key。获取手机号码的操作在我另外一篇博客里有写。


maven 依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>

















免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM