import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
public class myTest {
@Test
public void userInfoTest() {
String appId = "";
String secret = "";
String code = "";
String userInfo = getOpenIdByCode(appId, secret, code);
System.out.println(userInfo);
}
/**
* 微信根据code获取openId
* HttpClientUtil请求工具类
*/
private String getOpenIdByCode(String appId, String secret, String code) {
String userInfo = "";
//String accessUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
String accessUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appId, secret, code);
String accessTokenStr = HttpClientUtil.httpGet(accessUrl);
JSONObject jsonObject = JSON.parseObject(accessTokenStr);
if (jsonObject.get("errcode") != null)
System.out.println(jsonObject.get("errcode").toString() + ":" + jsonObject.get("errmsg"));
String accessToken = jsonObject.getString("access_token");
String openId = jsonObject.getString("openid");
//根据openId和access_token获取用户头像和昵称
String accessUrl2 = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openId);
String accessTokenStr2 = HttpClientUtil.httpGet(accessUrl2);
JSONObject jsonObject2 = JSON.parseObject(accessTokenStr2);
if (jsonObject2.get("errcode") != null)
System.out.println(jsonObject.get("errcode").toString() + ":" + jsonObject.get("errmsg"));
String nickname = jsonObject2.getString("nickname");
String headimgurl = jsonObject2.getString("headimgurl");
userInfo = "用户OpenId:" + openId + "用户昵称:" + nickname + "用户头像地址:" + headimgurl;
return userInfo;
}
}
JAVA之微信根据code获取openId
于 2020-09-02 17:17:45 首次发布