微信公众号或小程序获取OPENID方法

此类可以直接使用。。。

package com.XXX.controller.api;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
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.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcx.controller.index.BaseController;
import com.xcx.util.Base64Util;


/**
 * 
 * @author Jacky
 *
 */
@Controller
@RequestMapping("/weiXinApi/")
public class WeiXinApiController  extends BaseController {

private static final Logger log = LoggerFactory.getLogger(WeiXinApiController.class);
/**
* 获取微信小程序 session_key 和 openid
*
* @param code 调用微信登陆返回的Code
* @return
*/
@ResponseBody
@RequestMapping("getWXOpenId")
public static JSONObject getSessionKeyOropenid(String code,String appid,String secret) {
log.info("/weiXinApi/getWXOpenId          调用微信登陆返回的Code开始");
    //微信端登录code值
    String wxCode = code.trim();
    log.info("wxCode==="+wxCode);
//     Locale locale = new Locale("en", "US");
//     ResourceBundle resource = ResourceBundle.getBundle("config/wx-config",locale);   //读取属性文件
    String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";//resource.getString("url");  //请求地址 https://api.weixin.qq.com/sns/jscode2session
    Map<String, String> requestUrlParam = new HashMap<String, String>();
    requestUrlParam.put("appid", appid.trim());//"wxa1d1f519b7d51fc7");//resource.getString("appId"));  //开发者设置中的appId
    requestUrlParam.put("secret", secret.trim());//"4d2d87a85cbfb470eda7a05224c5b9a5");//resource.getString("appSecret")); //开发者设置中的appSecret
    requestUrlParam.put("js_code", wxCode); //小程序调用wx.login返回的code
    requestUrlParam.put("grant_type", "authorization_code");//resource.getString("grantType"));    //默认参数 authorization_code
    log.info("appid==="+appid);
    log.info("secret==="+secret);
    log.info("js_code==="+wxCode);
    //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
    JSONObject jsonObject = JSON.parseObject(sendPost(requestUrl, requestUrlParam));
    log.info("/weiXinApi/getWXOpenId     "+jsonObject+"     调用微信登陆返回的Code结束");
    return jsonObject;
}
 
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, Map<String, ?> paramMap) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
 
    String param = "";
    Iterator<String> it = paramMap.keySet().iterator();
 
    while (it.hasNext()) {
        String key = it.next();
        param += key + "=" + paramMap.get(key) + "&";
    }
 
    try {
        URL realUrl = new URL(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);
        // 获取URLConnection对象对应的输出流
        out = new PrintWriter(conn.getOutputStream());
        // 发送请求参数
        out.print(param);
        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
       e.getMessage();
    }
    //使用finally块来关闭输出流、输入流
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}
 
/**
     * 解密用户敏感数据获取用户信息
     *
     * @param sessionKey    数据进行加密签名的密钥
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv            加密算法的初始向量
     * @return
     * */
    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
      
    // 被加密的数据
//         byte[] dataByte = Base64Util.decodeByte(encryptedData);
    byte[] dataByte = null;
try {
dataByte = Base64Util.decodeString(encryptedData);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
        // 加密秘钥
//         byte[] keyByte = Base64Util.decodeByte(sessionKey);
    byte[] keyByte = null;
try {
keyByte = Base64Util.decodeString(sessionKey);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
        // 偏移量
//         byte[] ivByte = Base64Util.decodeByte(iv);
    byte[] ivByte = null;
try {
ivByte = Base64Util.decodeString(iv);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
        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 JSON.parseObject(result);
            }
        } catch (NoSuchAlgorithmException e) {
            e.getMessage();
        } catch (NoSuchPaddingException e) {
        e.getMessage();
        } catch (InvalidParameterSpecException e) {
        e.getMessage();
        } catch (IllegalBlockSizeException e) {
        e.getMessage();
        } catch (BadPaddingException e) {
        e.getMessage();
        } catch (UnsupportedEncodingException e) {
        e.getMessage();
        } catch (InvalidKeyException e) {
        e.getMessage();
        } catch (InvalidAlgorithmParameterException e) {
        e.getMessage();
        } catch (NoSuchProviderException e) {
        e.getMessage();
        }
        return null;
    }
    
    
    @ResponseBody  
    @RequestMapping("getOpenId")//此处填自己要用到的项目名。  
    public static String getOpenid(@RequestParam(value="code",required=false)String getcode) {//接收用户传过来的code,required=false表明如果这个参数没有传过来也可以。  
    log.info("/weiXinApi/getOpenId         得到微信gOpenId开始");
          String code=getcode;  
         //接收从客户端获取的code  
         //向微信后台发起请求获取openid的url  
//          String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=<span style="color:#ff0000;">APPID</span>&secret=<span style="color:#ff0000;">SECRET</span>&js_code=<span style="color:#ff0000;">JSCODE</span>&grant_type=authorization_code";  
//    [html] view plain copy
    String WX_URL = "";
             //这三个参数就是之后要填上自己的值。  
        //替换appid,appsecret,和code  
        String requestUrl = WX_URL.replace("APPID", "------------------").//填写自己的appid  
          replace("SECRET", "----------------------").replace("JSCODE", code).//填写自己的appsecret,  
          replace("authorization_code", "authorization_code");  
        
         //调用get方法发起get请求,并把返回值赋值给returnvalue  
           String  returnvalue=GET(requestUrl);  
           System.out.println(requestUrl);//打印发起请求的url  
           System.out.println(returnvalue);//打印调用GET方法返回值  
           //定义一个json对象。   
           JSONObject convertvalue=new JSONObject();  
          
           //将得到的字符串转换为json  
           convertvalue=(JSONObject) JSON.parse(returnvalue);  
     
     
         System.out.println("return openid is :"+(String)convertvalue.get("openid")); //打印得到的openid  
         System.out.println("return sessionkey is :"+(String)convertvalue.get("session_key"));//打印得到的sessionkey,  
         //把openid和sessionkey分别赋值给openid和sessionkey  
         String openid=(String) convertvalue.get("openid");  
         String sessionkey=(String) convertvalue.get("session_key");//定义两个变量存储得到的openid和session_key.  
         log.info("/weiXinApi/getOpenId     "+openid+"    得到微信gOpenId结束");
         return openid;//返回openid  
   }  
          //发起get请求的方法。  
   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.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) {  
           // 异常记录  
       } finally {  
           try {  
               if (in != null) {  
                   in.close();  
               }  
               if (is != null) {  
                   is.close();  
               }  
               if (isr != null) {  
                   isr.close();  
               }  
           } catch (Exception e2) {  
               // 异常记录  
           }  
       }  
       return result;  
   }  
      
   /*此方法没有用到。就先放在这吧  
   public static String jedisOperate(String Session_key, String openid) {  
       //这里需要引入一下jedis的dependenicy  
       Jedis jedis = new Jedis("localhost");   
       String openid = openid;  
       String session_key = session_key;  
       String uid = UUID.randomUUID().toString();  
       StringBuffer sb = new StringBuffer();  
       sb.append(openid);  
       sb.append(","+session_key);  
       jedis.set(uid, sb.toString());  
       return uid;  
       //如果需要获取登录用户的用户名和昵称,我们就需要注意一个问题,如果昵称中有中文就会出现乱码,这是因为微信对于中文是按照ISO-8859-1来进行编码的而我们需要的utf8编码,对于获取用户昵称出现乱码这个问题我们做一下简单的处理就可以解决:  
       //String nickNameDecode = new String(nickName.getBytes("ISO-8859-1"),"utf-8");  
     
   }*/  
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值