一、在微信开放平台创建移动应用
点击创建移动应用
二、拿到微信登录权限
三、app或小程序授权
1. app在拿到用户同意授权的时候,会传来一个code码:
后台接受到app端传来的code码,远程调用接口:https://api.weixin.qq.com/sns/oauth2/access_token;请求接口为GET请求;参数为:appid,secret,code,grant_type
具体请求方式可参考:
public static String net(String strUrl, Map<String, Object> params, String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if (method == null || method.equals("GET")) {
strUrl = strUrl + "?" + urlencode(params);
}
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
if (method == null || method.equals("GET")) {
conn.setRequestMethod("GET");
} else {
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
conn.setReadTimeout(DEF_READ_TIMEOUT);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params != null && method.equals("POST")) {
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(params));
} catch (Exception e) {
e.printStackTrace();
}
}
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
}
调用方法参考:
Map<String, Object> params = new HashMap<String, Object>();
params.put("appid", WeChatProperties.APPID);
params.put("secret", WeChatProperties.SECRET);
params.put("code", code);
params.put("grant_type", WeChatProperties.GRANT_TYPE);
Map<String, String> resultMap = (Map<String, String>) JSON
.parse(Certification.net("https://api.weixin.qq.com/sns/oauth2/access_token", params, "GET"));
获取到返回值:
{
"access_token": "",
"refresh_token": "",
"unionid": "",
"openid": "",
"scope": "",
"expires_in": 7200
}
在使用spring boot时,也可以直接使用RestTemplate来进行调用,示例为:
Map<?, ?> map = new ObjectMapper()
.readValue(
restTemplate
.getForEntity(MiniappProperties.login_url + "?appid=" + MiniappProperties.appid
+ "&secret=" + MiniappProperties.secret + "&grant_type="
+ MiniappProperties.grant_type + "&js_code=" + code, String.class)
.getBody(),
Map.class);
来直接调用。
openid为在此应用下,此种登录方法的微信号的标识;可在数据库记录此字段,判断是否为同一微信号登录;unionid为在此应用下微信号的标识,可用来标识不同登录方式采用的是同一个微信号;
2. 小程序在拿到用户同意授权的时候,会传来一个code码:
后台接受到app端传来的code码,远程调用接口:https://api.weixin.qq.com/sns/jscode2session;请求接口为GET请求;参数为:appid,secret,js_code,grant_type
除了参数不同,调用接口不同,其他使用方法与app登录相同
获取返回值:
{
"openid": "",
"session_key": "",
"expires_in": 7200
}
openid为在此应用下,此种登录方法的微信号的标识;