小程序授權java

/**

* @author vincent

* @date

*/

@Controller

@RequestMapping("/xcx")

public class XcXAuthController extends BaseController {

? ? @Resource(name = "wxMpService")

? ? private WxMpService wxService;

? ? @Autowired

? ? private WechatProperties properties;

? ? @Autowired

? ? private ILoginService iLoginService;


? ? @Value("${wechat.xcx.redirectURL}")

? ? private String redirectURL;

? ? //微信授權登錄

? ? @ResponseBody

? ? @RequestMapping(value = "/login" , method = RequestMethod.GET)

? ? public String wxAuthController(HttpServletRequest request){

? ? ? ? String para = request.getParameter("code");

? ? ? ? log.info("/xcx/login=======================>微信授權獲取的code"+para);

? ? ? ? JSONObject sessionKeyOropenid = this.getSessionKeyOropenid(para);

? ? ? ? return sessionKeyOropenid.toJSONString();

? ? }

? ? @ResponseBody

? ? @RequestMapping(value = "/login2" , method = RequestMethod.GET)

? ? public ResponseModel wxAuthController2(HttpServletRequest request) throws Exception{

? ? ? ? //該用戶是否位小程序分享鏈接進來的

? ? ? ? String encryptedData = request.getParameter("encryptedData");

? ? ? ? String sessionKey = request.getParameter("keys");

? ? ? ? String iv = request.getParameter("iv");

? ? ? ? log.info("/xcx/login2======>微信授權獲取的encryptedData"+encryptedData+

? ? ? ? "======>keys"+sessionKey+"======>iv");

? ? ? ? JSONObject userInfo = this.getUserInfo(encryptedData, sessionKey, iv);

? ? ? ? String headImgUrl = userInfo.getString("avatarUrl");

? ? ? ? String nickName = EmojiFilter.filterEmoji(userInfo.getString("nickName"));

? ? ? ? int gender = userInfo.getIntValue("gender");

? ? ? ? WxMpUser wxUser = JSONObject.toJavaObject(userInfo,WxMpUser.class);

? ? ? ? wxUser.setHeadImgUrl(headImgUrl);

? ? ? ? wxUser.setNickname(nickName);

? ? ? ? if(gender==0){

? ? ? ? ? ? wxUser.setSex("無");

? ? ? ? }else if(gender==1){

? ? ? ? ? ? wxUser.setNickname("男");

? ? ? ? }else? if(gender==2){

? ? ? ? ? ? wxUser.setNickname("女");

? ? ? ? }

? ? ? ? log.info("------------:"+JsonUtil.bean2json(wxUser));

? ? ? ? String openId = wxUser.getOpenId();

? ? ? ? log.info("------- = " + wxUser.getOpenId());

? ? ? ? log.info("-----------------openId---->"+openId);

? ? ? ? log.info("======================授權成功***************************");

? ? ? ? //this.setUser2Redis(wxUser, wxUser.getUnionid());

? ? ? ? boolean flag = iLoginService.toFindUser(request,openId);

? ? ? ? log.info("-----------------> 用戶是否存在" + flag);

? ? ? ? if(!flag){? ? ? ? ? ? ? ? ? ? ? ? ? //未注冊,獲取去授權信息插入到數據庫

? ? ? ? ? ? iLoginService.createUser(request,wxUser);

? ? ? ? }

? ? ? ? request.setAttribute("wxUser",wxUser);

? ? ? ? return new ResponseModel(true,000000,wxUser);

? ? }

? ? public JSONObject getUserInfo(String encryptedData,String sessionKey,String iv) throws Exception{

? ? ? ? // 被加密的數據

? ? ? ? byte[] dataByte = Base64.decode(encryptedData);

? ? ? ? // 加密秘鑰

? ? ? ? byte[] keyByte = Base64.decode(sessionKey);

? ? ? ? // 偏移量

? ? ? ? byte[] ivByte = Base64.decode(iv);

? ? ? ? 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) {

? ? ? ? ? ? log.error(e.getMessage(), e);

? ? ? ? } catch (NoSuchPaddingException e) {

? ? ? ? ? ? log.error(e.getMessage(), e);

? ? ? ? } catch (InvalidParameterSpecException e) {

? ? ? ? ? ? log.error(e.getMessage(), e);

? ? ? ? } catch (IllegalBlockSizeException e) {

? ? ? ? ? ? log.error(e.getMessage(), e);

? ? ? ? } catch (BadPaddingException e) {

? ? ? ? ? ? log.error(e.getMessage(), e);

? ? ? ? } catch (UnsupportedEncodingException e) {

? ? ? ? ? ? log.error(e.getMessage(), e);

? ? ? ? } catch (InvalidKeyException e) {

? ? ? ? ? ? log.error(e.getMessage(), e);

? ? ? ? } catch (InvalidAlgorithmParameterException e) {

? ? ? ? ? ? log.error(e.getMessage(), e);

? ? ? ? } catch (NoSuchProviderException e) {

? ? ? ? ? ? log.error(e.getMessage(), e);

? ? ? ? }

? ? ? ? return null;

? ? }

? ? private JSONObject getSessionKeyOropenid(String code){

? ? ? ? //微信端登錄code值

? ? ? ? String wxCode = code;

? ? ? ? String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";? ? //請求地址

? ? ? ? Map<String,String> requestUrlParam = new HashMap<String,String>();

? ? ? ? requestUrlParam.put("appid", properties.getAppId());? //開發者設置中的appId

? ? ? ? requestUrlParam.put("secret", properties.getSecret()); //開發者設置中的appSecret

? ? ? ? requestUrlParam.put("js_code", wxCode);? ? //小程序調用wx.login返回的code

? ? ? ? requestUrlParam.put("grant_type", "authorization_code");? //默認參數

? ? ? ? //發送post請求讀取調用微信 https://api.weixin.qq.com/sns/jscode2session 接口獲取openid用戶唯一標識

? ? ? ? JSONObject jsonObject = JSON.parseObject(this.sendPost(requestUrl, requestUrlParam));

? ? ? ? return jsonObject;

? ? }

? ? /**

? ? * 向指定 URL 發送POST方法的請求

? ? *

? ? * @param url 發送請求的 URL

? ? * @return 所代表遠程資源的響應結果

? ? */

? ? private 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) {

? ? ? ? ? ? log.error(e.getMessage(), e);

? ? ? ? }

? ? ? ? //使用finally塊來關閉輸出流、輸入流

? ? ? ? finally{

? ? ? ? ? ? try{

? ? ? ? ? ? ? ? if(out!=null){

? ? ? ? ? ? ? ? ? ? out.close();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? if(in!=null){

? ? ? ? ? ? ? ? ? ? in.close();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? ? ? catch(IOException ex){

? ? ? ? ? ? ? ? ex.printStackTrace();

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return result;

? ? }

}

-----------------------js代碼

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容