最近在写Java实现微信小程序的登录注册,需要获取OpenId和手机号,经过查找资料,找到了一篇很不错的博文,完美解决了问题,原文链接如下:Java实现微信小程序登录注册:获取OpenId和手机号_java获取小程序登录用户信息、-CSDN博客
下面是转载内容:
1、登录流程时序
2、说明
(1)调用 wx.login() 获取 临时登录凭证code ,并回传到开发者服务器。
(2)调用 auth.code2Session 接口,换取 用户唯一标识 OpenID 、 用户在微信开放平台帐号下的唯一标识UnionID(若当前小程序已绑定到微信开放平台帐号) 和 会话密钥 session_key。
之后开发者服务器可以根据用户标识来生成自定义登录态,用于后续业务逻辑中前后端交互时识别用户身份。
3、注意事项
(1)会话密钥 session_key 是对用户数据进行 加密签名 的密钥。为了应用自身的数据安全,开发者服务器不应该把会话密钥下发到小程序,也不应该对外提供这个密钥。
(2)临时登录凭证 code 只能使用一次
4、获取OpenId
@PostMapping("/getOpeId")//获取openId
public String getOpeId(@RequestBody JSONObject js_code) {
String code = js_code.getString("js_code");
// 小程序唯一标识 (在微信小程序管理后台获取)
String appid = "";
// 小程序的 app secret (在微信小程序管理后台获取)
String secret = "";
// 授权(必填)
String grant_type = "authorization_code";
// 向微信服务器 使用登录凭证 code 获取 session_key 和 openid
// 请求参数
String params = "appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=" + grant_type;
// 发送请求
String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
// 解析相应内容(转换成json对象)
JSONObject json = JSONObject.parseObject(sr);
// 获取会话密钥(session_key)
// String session_key = json.get("session_key").toString();
// 用户的唯一标识(openid)
String openid = (String) json.get("openid");
return openid;
}
5、获取手机号:
@PostMapping("/getPhoneNum")//获取手机号
public Object getPhoneNum(@RequestBody JSONObject js_code){
// 获取token
// 小程序唯一标识 (在微信小程序管理后台获取)
String appid = "";
// 小程序的 app secret (在微信小程序管理后台获取)
String secret = "";
// 授权(必填)
String grant_type = "client_credential";
//向微信服务器 使用登录凭证 code 获取 session_key 和 openid
// 请求参数
String params2 = "appid=" + appid + "&secret=" + secret + "&grant_type=" + grant_type;
// 发送请求
String sr2 = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params2);
// 解析相应内容(转换成json对象)
JSONObject json2 = JSONObject.parseObject(sr2);
String access_token = json2.getString("access_token");
//使用获取到的token和接受到的code像微信获取手机号
String code = js_code.getString("js_code");
JSONObject jsonObject = new JSONObject();
jsonObject.put("code",code);
String url = ("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+access_token);
String sr3 = HttpRequest.sendPost(url,jsonObject);
JSONObject phone_info = JSONObject.parseObject(sr3);
return phone_info;
}
说明:appid和secret需要在微信小程序管理后台获取
6、HTTP工具类:
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequest {
public static void main(String[] args) {
//发送 GET 请求
String s = HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");
System.out.println(s);
//发送 POST 请求
// String sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7", "");
// JSONObject json = JSONObject.parseObject(sr);
// System.out.println(json.get("data"));
}
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, JSONObject param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String sendPost2(String url, String data) {
String response = null;
try {
CloseableHttpClient httpclient = null;
CloseableHttpResponse httpresponse = null;
try {
httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
StringEntity stringentity = new StringEntity(data,
ContentType.create("text/json", "UTF-8"));
httppost.setEntity(stringentity);
httpresponse = httpclient.execute(httppost);
response = EntityUtils
.toString(httpresponse.getEntity());
} finally {
if (httpclient != null) {
httpclient.close();
}
if (httpresponse != null) {
httpresponse.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}