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

最近在写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;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现微信、手机号登陆可以分为以下几步: 1. 微信登陆 在前端页面中,使用微信提供的登录接口获取用户的微信授权信息,包括用户的openID、sessionKey等。将这些信息发送到后台,后台通过验证微信服务器返回的信息,获取用户的唯一标识openID,再将openID与自己的用户系统进行关联,实现微信登录。 2. 手机号登陆 在前端页面中,用户输入手机号和验证码,将这些信息发送到后台,后台通过验证手机号和验证码的正确性,再将手机号与自己的用户系统进行关联,实现手机登录。 3. 微信小程序获取手机号授权用户登录功能和注册功能 在微信小程序中,可以使用微信提供的getUserInfo接口获取用户信息,包括昵称、头像、性别等,但是获取手机号需要用户授权。可以使用微信提供的getPhoneNumber接口获取用户手机号码,但是需要先获取用户授权。具体步骤如下: a. 在小程序中引入wx.login接口,获取用户的code。 b. 将code发送到后台,后台通过code向微信服务器获取session_key和openid。 c. 在小程序中引入wx.getSetting接口,获取用户是否授权手机号的状态。 d. 如果用户未授权,可以使用wx.authorize接口向用户发起授权请求,获取用户手机号。 e. 如果用户已授权,可以使用wx.getUserInfo接口获取用户信息,包括手机号。 f. 将获取到的手机号和其他信息发送到后台,后台进行用户注册登录操作。 注意事项: 1. 在获取用户手机号之前,需要先获取用户授权。 2. 在用户授权之前,需要向用户说明获取手机号的目的和使用方式。 3. 在用户授权之后,需要保护用户的个人隐私,不得将用户手机号用于其他非法用途。 4. 尽可能减少用户的操作次数,提高用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值