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