微信小程序获得unionid

一、微信小程序中app.js中:

    wx.login({
      success: res => {
        if(res.code){
          var code = res.code;
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo']) {
                wx.getUserInfo({
                  success: res => {
                    var encryptedData = res.encryptedData;
                    var iv = res.iv;
                    wx.request({
                      url: 'http://localhost:9001/method/decodeUserInfo',//发送到开发者服务器
                      method: 'post',
                      data: { code: code, encryptedData:encryptedData,iv:iv },
                      dataType:'json',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      success: function (rs) {
                        console.log(rs);
                      },
                      fail: function (e) {
                        console.log(e);
                        wx.showToast({
                          title: '网络异常!',
                          duration: 2000
                        });
                      }
                    });
                    if (this.userInfoReadyCallback) {
                      this.userInfoReadyCallback(res)
                    }
                  }
                })
              }else{
                console.log("未授权");
              }
            }
          })
        }
    }
  })

二、开发者服务器中进行接收数据并解密数据

1.控制器中代码:

  @RequestMapping("/method/decodeUserInfo")
    public String decodeUserInfo(HttpServletRequest request, HttpServletResponse response)throws Exception{
        response.setHeader("Access-Control-Allow-Origin", "*");
        String code = request.getParameter("code");
        String encryptedData = request.getParameter("encryptedData");
        String iv = request.getParameter("iv");
        if(code.equals("") || code == null){return "failed";}
        if(encryptedData.equals("") || encryptedData == null){return "failed";}
        if(iv.equals("") || iv == null){return "failed";}

         1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid 
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+APPSECRET+"&js_code="+code+"&grant_type=authorization_code";
        String result = HttpHandler.sendGet(url);
        //解析相应内容(转换成json对象)
        JSONObject json = JSONObject.fromObject(result);
        //获取会话密钥(session_key)
        String session_key = json.get("session_key").toString();
        //用户的唯一标识(openid)
        String openid = json.get("openid").toString();
        System.out.println("session_key:"+session_key);
        System.out.println("openid:"+openid);

         2、对encryptedData加密数据进行AES解密其中包含这openid和unionid 
        String data = AesCbcUtil.decrypt(encryptedData,session_key,iv,"UTF-8");
        JSONObject jsonObject = JSONObject.fromObject(data);
        String unionid = jsonObject.get("unionId").toString();
        return unionid;
    }
2.HttpHandler类中sendGet方法:
  /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和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()) {

            }
            // 定义 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.AesCbcUtil中decrypt方法:
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

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.*;
import java.security.spec.InvalidParameterSpecException;

/**
 * Created by yfs on 2018/2/6.
 * <p>
 * AES-128-CBC 加密方式
 * 注:
 * AES-128-CBC可以自己定义“密钥”和“偏移量“。
 * AES-128是jdk自动生成的“密钥”。
 */
public class AesCbcUtil {
    static {
        //BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * AES解密
     *
     * @param data           //密文,被加密的数据
     * @param key            //秘钥
     * @param iv             //偏移量
     * @param encodingFormat //解密后的结果需要进行的编码
     * @return
     * @throws Exception
     */
    public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
//        initialize();
        //被加密的数据
        byte[] dataByte = Base64.decodeBase64(data);
        //加密秘钥
        byte[] keyByte = Base64.decodeBase64(key);
        //偏移量
        byte[] ivByte = Base64.decodeBase64(iv);


        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

            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);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, encodingFormat);
                return result;
            }
            return null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException 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;
    }
}

 

完成上面的几步就能成功实现微信小程序获得unionid.

 

转载于:https://www.cnblogs.com/wanyong-wy/p/9766591.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值