微信小程序+java后台实现unionId获取

微信 端JS ,必须是先login 然后再调用getUserInfo  后台解密的时候才不会报错

1 wx.login

2wx.getUserInfo

wx.login({
      success: function (res) {
        var code = res.code;//登录凭证
        if (code) {
          //2、调用获取用户信息接口
          wx.getUserInfo({
            success: function (res) {
              console.log({ encryptedData: res.encryptedData, iv: res.iv, code: code })
              //3.请求自己的服务器,解密用户信息 获取unionId等加密信息
              wx.request({
                url: 'http://域名/**.action',//自己的服务接口地址
                method: 'get',
                header: {
                  "Content-Type": "applciation/json"
                },
                data: { encryptedData: res.encryptedData, iv: res.iv, code: code },
                success: function (data) {

                  //4.解密成功后 获取自己服务器返回的结果
                  if (data.data.status == 1) {
                    var userInfo_ = data.data.userInfo;
                    console.log(userInfo_)
                  } else {
                    console.log('解密失败')
                  }
                },
                fail: function () {
                  console.log('系统错误')
                }
              })
            },
            fail: function () {
              console.log('获取用户信息失败')
            }
          })
        } else {
          console.log('获取用户登录态失败!' + r.errMsg)
        }
      },
      fail: function () {
        console.log('登陆失败')
      }
    })

 

导入包不能出错或者是其它包

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yitai.tms.common.utils.MyLog;
import com.yitai.tms.weixin.service.AccountService;



	@ResponseBody
	@PostMapping("/loginPhone")
	//@RequiresPermissions("order:order:order")
	public Map<String, Object> loginPhone(@RequestBody String infoData) {
		Map<String, Object> map = new HashMap<>();
		try {
			JSONObject dataObj = JSONObject.parseObject(infoData);
			String  code =  (String) dataObj.get("code");
			
			JSONObject openjson  = getSessionKey(code,dataObj);
			
			dataObj.put("openid", openjson.get("openid"));
			dataObj.put("unionid", openjson.get("unionid"));
			map = accountService.loginWithPhone(dataObj);
			if (map.get("code").equals(0)) {
				map.put("openid", openjson.get("openid"));
			}
		} catch (Exception e) {
			logger.error("用户登录成功 ", e);
		}
		return map;
	}


 //发起get请求的方法。特别注意编码 utf-8 格式
		public static String GET(String url) {
			String result = "";
			BufferedReader in = null;
			InputStream is = null;
			InputStreamReader isr = null;
			try {
				URL realUrl = new URL(url);
				URLConnection conn = realUrl.openConnection();
				 conn.setRequestProperty("accept", "*/*");
		            conn.setRequestProperty("connection", "Keep-Alive");
		            conn.setRequestProperty("Accept-Charset", "utf-8");
		            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		            // 发送POST请求必须设置如下两行
		       /*  conn.setDoOutput(true);
		         conn.setDoInput(true);*/
				conn.connect();
				Map<String, List<String>> map = conn.getHeaderFields();
				is = conn.getInputStream();
				isr = new InputStreamReader(is);
				in = new BufferedReader(isr);
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
			} catch (Exception e) {
				logger.error("Exception{} ", e);
			} finally {
				try {
					if (in != null) {
						in.close();
					}
					if (is != null) {
						is.close();
					}
					if (isr != null) {
						isr.close();
					}
				} catch (Exception e2) {
					// 异常记录
				}
			}
			return result;
		}

 private static final String APP_SECRET="35d042c5c5f588f8ec8852b3240c9f84";
 private static final String APP_ID = "wx20f8462ca04e6fad";
 
	public JSONObject getSessionKey(String code,JSONObject infodata) {
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret="
				+ APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
		String reusult = GET(url);
		JSONObject oppidObj = JSONObject.parseObject(reusult);
		String openid = (String) oppidObj.get("openid");
		String session_key = (String) oppidObj.get("session_key");
		oppidObj.put("openid", openid);
		oppidObj.put("session_key", session_key);
		if (oppidObj.containsKey("unionid")) {
			oppidObj.put("unionid", (String) oppidObj.get("unionid"));
		}else{
			String encryptedData=infodata.getString("encryptedData");
			String iv=infodata.getString("iv");
			JSONObject object = getUserInfo(encryptedData,session_key,iv);
			logger.info("再次获取unionid=======>>>>{}",object);
			oppidObj.put("unionid", object.getString("unionId"));
		}
		return oppidObj;
	}
 

	/**
     * 获取信息
     */
    public JSONObject getUserInfo(String encryptedData,String sessionkey,String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decodeBase64(encryptedData.getBytes());
        // 加密秘钥
        byte[] keyByte = Base64.decodeBase64(sessionkey.getBytes());
        // 偏移量
        byte[] ivByte = Base64.decodeBase64(iv.getBytes());
        try {
               // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            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);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (NoSuchAlgorithmException e) {
        	logger.info("NoSuchAlgorithmException{}" + e);
        } catch (NoSuchPaddingException e) {
        	logger.info("NoSuchPaddingException{}" + e);
        } catch (InvalidParameterSpecException e) {
        	logger.info("InvalidParameterSpecException{}" + e);
        } catch (IllegalBlockSizeException e) {
        	logger.info("IllegalBlockSizeException{}" + e);
        } catch (BadPaddingException e) {
        	logger.info("BadPaddingException{}" + e);
        } catch (UnsupportedEncodingException e) {
        	logger.info("UnsupportedEncodingException{}" + e);
        } catch (InvalidKeyException e) {
        	logger.info("InvalidKeyException{}" + e);
        } catch (InvalidAlgorithmParameterException e) {
        	logger.info("InvalidAlgorithmParameterException{}" + e);
        } catch (NoSuchProviderException e) {
        	logger.info("NoSuchProviderException{}" + e);
        }
        return null;
    }

 

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值