小程序获取openid 获取绑定手机号,获取unionid

  • Post author:
  • Post category:小程序


//根据code换取用户openId
    @SuppressWarnings({"static-access", "resource"})
    @RequestMapping(value = "getOpenId")
    public JSONObject getOpenId(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            String appid ="";//appid
            String secret ="";//密钥
            String code = request.getParameter("code");
            if (!StringUtils.isBlank(appid)) {
                String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret
                        + "&js_code=" + code + "&grant_type=authorization_code";
                HttpClient client = new DefaultHttpClient();
                // 发送get请求
                HttpGet req = new HttpGet(url);
                HttpResponse res = client.execute(req);
                String strResult = "";
                if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    /** 读取服务器返回过来的json字符串数据 **/
                    strResult = EntityUtils.toString(res.getEntity());
                }
                JSONObject jsonObj = new JSONObject();
                jsonObj = new JSONObject().parseObject(strResult);
                String session_key = jsonObj.getString("session_key");
                String openid = jsonObj.getString("openid");
                System.out.println("openid" + openid);
                JSONObject record = new JSONObject();
                record.put("session_key", session_key);
                record.put("openid", openid);    
                return JsonUtils.successJsonApi("获取成功!",record);
            } else {
                return JsonUtils.error(400, "appid错误");
            }
        } catch (Exception e) {
            return JsonUtils.error(500, e.getMessage());
        }
    }

获取绑定手机号

 @ResponseBody
    @RequestMapping(value = "decodeUserInfo", method = RequestMethod.POST)
    public Map decodeUserInfo(String encryptedData, String iv, String session_key) {
        Map map = new HashMap();
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "";
        //授权(必填)
        String grant_type = "authorization_code";
         1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&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");

         2、对encryptedData加密数据进行AES解密 
        try {
            String result = AesUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");
                JSONObject userInfoJSON = JSONObject.parseObject(result);
                Map userInfo = new HashMap();
                userInfo.put("openId", openId);
                userInfo.put("phoneNumber", userInfoJSON.get("phoneNumber"));
                map.put("userInfo", userInfo);
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");
        return map;
    }

获取unionid

  @ResponseBody
        @RequestMapping(value  =  "/decodeUserInfo",  method  =  RequestMethod.POST)
        public  Map  decodeUserInfo(String  encryptedData,  String  iv,  String  code)  {
                Map  map  =  new  HashMap();
                //登录凭证不能为空
                if  (code  ==  null  ||  code.length()  ==  0)  {
                        map.put("status",  0);
                        map.put("msg",  "code  不能为空");
                        return  map;
                }
                //小程序唯一标识      (在微信小程序管理后台获取)
                String  wxspAppid  =  "";
                //小程序的  app  secret  (在微信小程序管理后台获取)
                String  wxspSecret  =  "";
                //授权(必填)
                String  grant_type  =  "authorization_code";
                  1、向微信服务器  使用登录凭证  code  获取  session_key  和  openid  
                //请求参数
                String  params  =  "appid="  +  wxspAppid  +  "&secret="  +  wxspSecret  +  "&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");

                  2、对encryptedData加密数据进行AES解密  
                try  {
                        String  result  =  AesUtil.decrypt(encryptedData,  session_key,  iv,  "UTF-8");
                        if  (null  !=  result  &&  result.length()  >  0)  {
                                map.put("status",  1);
                                map.put("msg",  "解密成功");

                                JSONObject  userInfoJSON  =  
                                JSONObject.parseObject(result);
                                Map  userInfo  =  new  HashMap();
                                userInfo.put("openId",  userInfoJSON.get("openId"));
                                userInfo.put("nickName",  userInfoJSON.get("nickName"));
                                userInfo.put("gender",  userInfoJSON.get("gender"));
                                userInfo.put("city",  userInfoJSON.get("city"));
                                userInfo.put("province",  userInfoJSON.get("province"));
                                userInfo.put("country",  userInfoJSON.get("country"));
                                userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
                                userInfo.put("unionId",  userInfoJSON.get("unionId"));
                                map.put("userInfo",  userInfo);
                                return  map;
                        }
                }  catch  (Exception  e)  {
                        e.printStackTrace();
                }
                map.put("status",  0);
 
加载更多

工具类

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;

public class AesUtil {
    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 {

        //被加密的数据
        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;
    }

}



版权声明:本文为weixin_41018853原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。