1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Java实现微信小程序登录注册:获取OpenId和手机号

Java实现微信小程序登录注册:获取OpenId和手机号

时间:2022-03-02 15:34:10

相关推荐

Java实现微信小程序登录注册:获取OpenId和手机号

登录流程时序:

说明

调用wx.login()获取临时登录凭证code,并回传到开发者服务器。调用auth.code2Session接口,换取用户唯一标识 OpenID、 用户在微信开放平台帐号下的唯一标识UnionID(若当前小程序已绑定到微信开放平台帐号) 和会话密钥 session_key

之后开发者服务器可以根据用户标识来生成自定义登录态,用于后续业务逻辑中前后端交互时识别用户身份。

注意事项

会话密钥session_key是对用户数据进行加密签名的密钥。为了应用自身的数据安全,开发者服务器不应该把会话密钥下发到小程序,也不应该对外提供这个密钥。临时登录凭证 code 只能使用一次

获取OpenId:

@PostMapping("/getOpeId")//获取openIdpublic 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./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;}

获取手机号:

@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./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./wxa/business/getuserphonenumber?access_token="+access_token);String sr3 = HttpRequest.sendPost(url,jsonObject);JSONObject phone_info = JSONObject.parseObject(sr3);return phone_info;}

说明:appid和secret需要在微信小程序管理后台获取

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 .URL;import .URLConnection;import java.util.List;import java.util.Map;public class HttpRequest {public static void main(String[] args) {//发送 GET 请求String s = HttpRequest.sendGet("/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");System.out.println(s);//发送 POST 请求// String sr=HttpRequest.sendPost("/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;}}

相关文档:小程序登录 | 微信开放文档

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。