微信登录并拿手机号码(实战)目前仅公众号及小程序登录


微信开放的接口就很迷,公众号拿得到头像、用户名,小程序啥的只有灰白头像和默认名……不知道是我的问题还是就这样设计的……

1.公众号、小程序内用户登录

公众号登录重定向跨域问题

一般来讲,通过前端请求后端login方法后,后端重定向没问题,我这里写的时候,前后端完全分离的,因此出现跨域问题。CORS error xhr
解决办法: 直接让前端调用微信授权的OAuth2地址。
即:window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=https%3A%2F%2F域名%2F后台方法名1%2F后台方法名2%2F后台方法名3&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";
记得将APPID替换为自己的,分别再替换后台方法名1、2、3即可,需要编码的缘故,所以地址栏有乱码。
后台方法名拼写规则为:https://域名/后台方法名1/后台方法名2/后台方法名3(即下文中的:callBack()方法),1、2处为controller地址
后来发现这样前台拿不到数据,
最后由后台重定向到前台,并带token过去response.sendRedirect("https://666.com/h5?token="+user.getToken());
前端调用验证token进行登录

注意: 公众号登录的openid和小程序的openid不一样

Pom 依赖文件

        <!--HttpClient的依赖-->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

        <!--CloseableHttpClient的依赖-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

工具类

package com.xxx.tool;

import net.sf.json.JSONObject;
import wiremock.org.apache.http.HttpEntity;
import wiremock.org.apache.http.HttpResponse;
import wiremock.org.apache.http.ParseException;
import wiremock.org.apache.http.client.ClientProtocolException;
import wiremock.org.apache.http.client.methods.CloseableHttpResponse;
import wiremock.org.apache.http.client.methods.HttpGet;
import wiremock.org.apache.http.client.methods.HttpPost;
import wiremock.org.apache.http.entity.StringEntity;
import wiremock.org.apache.http.impl.client.CloseableHttpClient;
import wiremock.org.apache.http.impl.client.DefaultHttpClient;
import wiremock.org.apache.http.impl.client.HttpClients;
import wiremock.org.apache.http.message.BasicHeader;
import wiremock.org.apache.http.protocol.HTTP;
import wiremock.org.apache.http.util.EntityUtils;
import java.io.IOException;

/**
 * 工具类
 *
 * @author Cheng Rong Yu
 * @date 2022-08-11
 */
public class AuthUtil {
    public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
        JSONObject jsonObject = null;
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.fromObject(result);
        }
        httpGet.releaseConnection();
        return jsonObject;
    }

    /**
     * 发送post请求
     *
     * @param url        路径
     * @param jsonObject 参数(json类型)
     * @param encoding   编码格式
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String send(String url, JSONObject jsonObject, String encoding) throws ParseException, IOException {
        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        //装填参数
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        //设置参数到请求对象中
        httpPost.setEntity(s);
        System.out.println("请求地址:" + url);
//        System.out.println("请求参数:"+nvps.toString());

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
//        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;

    }
}


Java代码

package com.xxx;

import cn.hutool.http.HttpUtil;
import com.ruoyi.clearwater.controller.tool.AuthUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import net.sf.json.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录Controller
 *
 * @author Cheng Rong Yu
 * @date 2022-08-12
 */
@CrossOrigin
@Controller
@RequestMapping("/clearwater/wx")
public class WXLoginController {

	//参考:https://blog.csdn.net/Ellis_li/article/details/103070060
	//回调域名
    String sym = "http://xxxx.xxx.xx:2088";
    //appID 查看地址(https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index)
    private String appId1 = "xxx";
    //AppSecret(密钥) 查看地址同上
    private String secret1 = "xxxxx";

    /**
     * Tea微信登录公众号接口
     * 拿公众号的id 和密钥登录
     * 需要关注公众号,没关注会提示
     *
     * @throws IOException
     */
    @Log(title = "微信登录接口")
    @RequestMapping("/login")
    public void wxLogin(HttpServletResponse response) throws IOException {
        System.out.println("------------------------------------------------------");
        System.out.println("开始请求");
        System.out.println("------------------------------------------------------");
        //回调域名
        String sym = "http://公网地址:端口号";
        //这里是回调的url地址
        String redirect_uri = URLEncoder.encode(sym + "/clearwater/wx/callBack", "UTF-8");
        /**
         * 请求参数鉴权登录
         */
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=APPID" +
                "&redirect_uri=REDIRECT_URI" +
                "&response_type=code" +
                "&scope=SCOPE" +
                "&state=123" +
				"&connect_redirect=1#wechat_redirect";
        try {
            /**
             * 重定向地址调用
             */
            response.sendRedirect(url.replace("APPID", appId1).replace("REDIRECT_URI", redirect_uri).replace("SCOPE", "snsapi_userinfo"));
        } catch (Exception e) {
            /**
             * 返回错误信息
             */
            e.printStackTrace();
        }
    }

    /**
     * Tea微信授权成功的回调函数
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @Log(title = "微信授权回调接口")
    @RequestMapping("/callBack")
    public AjaxResult deGet(HttpServletRequest request, HttpServletResponse response) {
        /**
         * 微信用户信息
         */
        JSONObject userInfo = null;
        /**
         * 返回标识 0为error 1为success
         */
        Boolean flag = false;
        /**
         * 返回信息
         */
        String msg = "";
        try {
            //获取回调地址中的code
            String code = request.getParameter("code");
            System.out.println("---------------------------------------------------------------------");
            System.out.println("code:" + code);
            System.out.println("---------------------------------------------------------------------");
            //拼接url
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+secret1+"&code=" + code + "&grant_type=authorization_code";
            JSONObject jsonObject = AuthUtil.doGetJson(url);
            //1.获取微信用户的openid
            String openid = jsonObject.getString("openid");
            System.out.println("---------------------------------------------------------------------");
            System.out.println("openid:" + openid);
            System.out.println("---------------------------------------------------------------------");
            //2.获取获取access_token
            String access_token = jsonObject.getString("access_token");
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
                    + "&lang=zh_CN";
            //3.获取微信用户信息(openid,nickname,sex,language,city,province,country,headimgurl,privilege)
            userInfo = AuthUtil.doGetJson(infoUrl);
            System.out.println("---------------------------------------------------------------------");
            System.out.println("userInfo:");
            System.out.println(userInfo.toString());
            System.out.println("---------------------------------------------------------------------");
            //至此拿到了微信用户的所有信息,剩下的就是业务逻辑处理部分了
            //保存openid和access_token到session
            request.getSession().setAttribute("openid", openid);
            request.getSession().setAttribute("access_token", access_token);
            //去数据库查询此微信是否绑定过手机
            SysUser user = sysUserService.getUserByOpenId(openid);
            //登录账号即为手机号
            String mobile = user == null ? "" : user.getLoginName();
            /**
             * 若有手机号返回登录成功信息
             * 没有返回登录失败
             */
            if (null == mobile || "".equals(mobile)) {
                flag = false;
                msg = "登录失败,请绑定手机号码";
            } else {
                flag = true;
                msg = "登录授权成功";
            }
            /**
             * 此处用于直接跳转返回地址
             */
//            if(null == mobile || "".equals(mobile)){
//                //如果无手机信息,则跳转手机绑定页面
//                response.sendRedirect("/front/register.html");
//            }else{
//                //否则直接跳转首页
//                response.sendRedirect("/front/index.html");
//            }
        } catch (Exception e) {
            /**
             * 返回错误信息
             */
            e.printStackTrace();
        } finally {
            if (flag) {
                return AjaxResult.success(msg, userInfo);
            } else {
                return AjaxResult.error(msg);
            }
        }
    }


    /**
     * 小程序登录代码
     */

    //小程序登录鉴权地址
    private String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
    //小程序id 查看地址(https://mp.weixin.qq.com/wxamp/wadevelopcode/sandbox?lang=zh_CN)
    private String appId = "xxx";
    //AppSecret(小程序密钥) 查看地址同上
    private String secret = "xxx";

    /**
     * 根据前端 wx.login 获取的e.code传入后台
     * 拿取session_key以及openid
     * @param code 微信登录验证码
     * @return session_key以及openid
     */
    public JSONObject getSessionKeyOrOpenId(String code) {
        /**
         * 存储请求参数
         */
        Map<String, Object> requestUrlParam = new HashMap<>();
        //小程序appId
        requestUrlParam.put("appid", appId);
        //小程序 appSecret
        requestUrlParam.put("secret", secret);
        //小程序端返回的code
        requestUrlParam.put("js_code", code);
        //默认参数
        requestUrlParam.put("grant_type", "authorization_code");

        //发送post请求读取调用微信接口获取openid用户唯一标识
        //我用的hutool工具包的HttpUtil、JSONUtil,各位按需导入
        JSONObject SessionKeyOpenId = null;
        try {
            /*
             * get请求拿取信息
             */
            String result = HttpUtil.get(requestUrl, requestUrlParam);
            /**
             * 转换json格式
             */
            SessionKeyOpenId = JSONObject.fromObject(result);
            System.err.println("--------------------------------------------");
            System.err.println(requestUrl);
            System.err.println(requestUrlParam);
            System.err.println(SessionKeyOpenId);
            System.err.println("--------------------------------------------");
        } catch (Exception e) {
            /**
             * 提示报错信息
             */
            e.printStackTrace();
        }
        /**
         * session_key以及openid
         */
        return SessionKeyOpenId;
    }

    /**
     *
     * @param encryptedData
     * @param iv
     * @param code
     * @return
     */
    @Log(title = "微信")
    @RequestMapping("/wxRegistry")
    public String wxRegistry(String encryptedData, String iv, String code) {

        /**
         * 防止前端传参丢失+等特殊字符
         * 否则会报 javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
         */
        System.err.println("--------------------------------------------");
        System.err.println(encryptedData = encryptedData.replace(" ", "+"));
        System.err.println(iv = iv.replace(" ", "+"));
        System.err.println(code = code.replace(" ", "+"));
        System.err.println("--------------------------------------------");

        //第一步:通过code获取openid sessionKey
        JSONObject sessionKeyOrOpenId = getSessionKeyOrOpenId(code);

        String openid = sessionKeyOrOpenId.getString("openid");
        String sessionKey = sessionKeyOrOpenId.getString("session_key");

        System.err.println("--------------------------------------------");
        System.err.println(openid);
        System.err.println(sessionKey);
        System.err.println("--------------------------------------------");

        //第二步:从encryptedData iv 解密 用户信息 拿到用户信息
        JSONObject userInfo = getUserInfo(encryptedData, iv, sessionKey);

//        String phone = userInfo.getString("phoneNumber");

        System.err.println("--------------------------------------------");
        System.err.println("执行手机号注册登录逻辑");
        System.err.println(userInfo);
        System.err.println("--------------------------------------------");

        return null;
    }

    /**
     * 从encryptedData iv 解密 用户信息 拿到用户信息
     * @param encryptedData
     * @param iv
     * @param sessionKey
     * @return
     */
    public static JSONObject getUserInfo(String encryptedData, String iv, String sessionKey) {

        // 被加密的数据
        byte[] dataByte = cn.hutool.core.codec.Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = cn.hutool.core.codec.Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = cn.hutool.core.codec.Base64.decode(iv);
        try {
            // 如果密钥不足16位,那么就补足.
            int base = 16;
            keyByte = completToBase(keyByte, base);
            ivByte = completToBase(ivByte, base);
            System.out.println("-------------------------------------");
            System.out.println(dataByte);
            System.out.println(keyByte);
            System.out.println(ivByte);
            System.out.println("-------------------------------------");
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            System.out.println("-------------------------------------");
            System.out.println(dataByte);
            System.out.println(resultByte);
            System.out.println(ivByte);
            System.out.println("-------------------------------------");
            /**
             * 判断解密结果
             */
            if (null != resultByte && resultByte.length > 0) {
                /**
                 * 转成人类能看懂的字符串
                 */
                String result = new String(resultByte, "UTF-8");
                System.out.println("-------------------------------------");
                System.out.println(result);
                System.out.println("-------------------------------------");
                //json格式输出
                return JSONObject.fromObject(result);
            }
        }
        /**
         * 异常抛出
         */
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        return null;
    }

    //补全数组位数
    public static byte[] completToBase(byte[] bytes, int base) {
        byte[] temp = new byte[]{};
        if (bytes.length % base != 0) {
            int groups = bytes.length / base + (bytes.length % base != 0 ? 1 : 0);
            temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(bytes, 0, temp, 0, bytes.length);
            return temp;
        } else {
            return bytes;
        }
    }

}

演示

公众号

在这里插入图片描述

小程序

在这里插入图片描述

2.Uni-app小程序内用户授权手机号码

工具类

package com.xxx;
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("Content-Type", "application/json");
            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;
    }
}

Java代码

package com.xxx;

import com.ruoyi.clearwater.controller.tool.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 微信登录获取手机号码Controller
 *
 * @author Cheng Rong Yu
 * @date 2022-08-12
 */
@CrossOrigin
@Controller
@RequestMapping("/clearwater/wxp")
public class WXGetPhoneController {

    /**
     * 获取手机号
     * @param code1
     * @return
     */
    @RequestMapping("/getPhoneNum")
    public Object getPhoneNum(String code1){
        // 获取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;
        System.out.println("-------------------------------------");
        System.out.println(params2);
        System.out.println("-------------------------------------");
        // 发送请求
        String sr2 = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", params2);
        // 解析相应内容(转换成json对象)
        JSONObject json2 = JSONObject.parseObject(sr2);
        System.out.println("-------------------------------------");
        System.out.println(json2);
        System.out.println("-------------------------------------");
        String access_token = json2.getString("access_token");
        //使用获取到的token和接受到的code像微信获取手机号
        String code = code1;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",code);
        System.out.println("-------------------------------------");
        System.out.println(jsonObject);
        System.out.println("-------------------------------------");
        String url = ("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+access_token);
        /**
         * post请求官方接口 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html
         */
        String sr3 = HttpRequest.sendPost(url,jsonObject);
        JSONObject phone_info = JSONObject.parseObject(sr3);
        System.out.println("-------------------------------------");
        System.out.println(sr3);
        System.out.println("-------------------------------------");
        System.out.println(phone_info);
        //拿取无区号手机号:JSONObject.parseObject(phone_info.getString("phone_info")).get("purePhoneNumber")
        /**
         * 返回结果信息
         */
        return phone_info;
    }

}

依赖

<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.3.9</version>
</dependency>

演示

在这里插入图片描述

前端代码

页面

<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">授权获取</button>
<button  @click="wxlogin">微信登录</button>

js

//获取手机号码
getPhoneNumber: function (e) {
     console.log(e)
     console.log(e.detail.iv)
     console.log(e.detail.encryptedData)
     //调用后台方法
	 this.getPhone(e.detail.code);
},
wxlogin() {
	let that = this;
	//调用微信小程序的登录接口
	wx.login({
		success(e) {
			console.log(e)
			// that.data.loginInfo.code = e.code //拿到的code存储在data中
			wx.showModal({
				title: '温馨提示',
				content: '微信授权登录后才能正常使用小程序功能',
				cancelText: '拒绝',
				confirmText: '同意',
				success(sucessInfo) {
					//调用微信小程序的获取用户信息的接口
					wx.getUserProfile({
						desc: '用于完善会员资料', // 声明获取用户个人信息后的用途
						lang: 'zh_CN',
						success(info) {
							console.log(info)
							//调用后台接口
							that.getWXInfo(info.encryptedData, info.iv, e.code);
						},
						fail(e) {
							console.log('获取用户信息失败', e)
						}
					})
				},
				fail() {
					console.log("拒绝")
				},
				complete() {}
			})
		},
		fail(e) {
			console.log('fail', e)
			wx.showToast({
				title: '网络异常',
				duration: 2000
			})
			return
		}
	})
},
getWXInfo(encryptedData, iv, code) {
	uni.request({
		url: 'http://xxx:2088/clearwater/wx/wxRegistry?encryptedData='+encryptedData +
			'&iv=' + iv + "&code=" + code,
		method: 'GET',
		header: {
			'content-type': 'application/x-www-form-urlencoded'
		},
		success: (res) => {
			console.log('6666')
			this.text = 'request success';
		}
	});
},
getPhone(code) {
	uni.request({
		url: 'http://xxx:2088/clearwater/wxp/getPhoneNum?&code1=' + code,
		method: 'GET',
		header: {
			'content-type': 'application/x-www-form-urlencoded'
		},
		success: (res) => {
			console.log('666')
			this.text = 'request success';
		}
	});
}
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程似锦吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值