微信小程序获取手机号

1、主要接口

 //小程序 AppID
    private static final String appid = "wxa******e0b3";
    //小程序 AppSecret
    private static final String secret = "8ffc**************bc0896e937d";

    @PostMapping("/wxphone")
    public Map<String,Object> wxphone(@RequestBody Image image)
    {
        Map<String,Object> map=new HashMap<>();

        String encryptedData=image.getParams().get("encryptedData").toString();
        String session_key="";
        String iv=image.getParams().get("iv").toString();
        String code=image.getParams().get("code").toString();

//      获取session_key,完善一下 存到数据库
        HttpUtil httpUtil=new HttpUtil();
        String params = "appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        String session_keyData=HttpUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject json_session=JSONObject.parseObject(session_keyData);
        session_key=json_session.get("session_key").toString();

//      获取手机号
        String result= WXBizDataCrypt.decrypt1(encryptedData,session_key,iv);
        JSONObject json=JSONObject.parseObject(result);

        if (!StringUtils.isEmpty(result)&&result.length()>0) {
            map.put("purePhoneNumber", json.getString("purePhoneNumber"));
            map.put("phoneNumber", json.getString("phoneNumber"));
            map.put("countryCode", json.getString("countryCode"));
            map.put("msg","success");
        }
        map.put("msg","按操作成功");
        map.put("code",200);
        return map;
    }

2.工具类  请求接口


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    /**
     * 向指定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;
    }

}


3.解密用的


import org.apache.commons.codec.binary.Base64;

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 java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

public class WXBizDataCrypt {


        /**
         * AES解密
         *
         * @param data   //密文,被加密的数据
         * @param key    //秘钥
         * @param iv     //偏移量
         * @return
         * @throws Exception
         */
        public static String decrypt1(String data, String key,String iv){
            //被加密的数据
            byte[] dataByte = Base64.decodeBase64(data);
            //加密秘钥
            byte[] keyByte = Base64.decodeBase64(key);
            //偏移量
            byte[] ivByte = Base64.decodeBase64(iv);
            try {
                AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivByte);
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
                cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
                return new String(cipher.doFinal(dataByte),"UTF-8");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (InvalidAlgorithmParameterException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return null;
        }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

飞飞翼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值