E企盈营销工具技术服务商 热线:4006-838-530

微信获取用户信息,微信小程序之用户登录(获取用户信息,openid,unionld)java后台版

E企盈直播平台营销卖货系统

参考文章:https://blog.csdn.net/guochanof/article/details/80189935;感谢作者给的思路与大部分问题解决办法由于微信官方api的更改,wx.getuserinfo()方法无法在无授权的情况下直接使用,参考文中作者是直接可以拉取授权,但到我这里失效了,查看错误信息是failscopeunauthorized获取授权信息失败;查看官方文档https://developers.weixin.qq.com/blogdetail?action=get_post_info&lang=zh_CN&token=384460955&docid=000aee01f98fc0cbd4b6ce43b56c01后得到解决办法,需要用户手动点击button后调用授权,更改后成功.具体代码及后台如下:1.微信端app.js://app.jsApp({onLaunch:function(){//展示本地存储能力varlogs=wx.getStorageSync(‘logs’)||[]logs.unshift(Date.now())wx.setStorageSync(‘logs’,logs)varthat=this;//获取用户信息wx.getSetting({success:res={if(res.authSetting[‘scope.userInfo’]){//已经授权,可以直接调用getUserInfo获取头像昵称,不会弹框wx.getUserInfo({success:function(res){that.globalData.userInfo=res.userInfoconsole.log(that.globalData.userInfo)},fail:function(){wx.redirectTo({url:’../../pages/login/login’,})}})}else{//未授权,跳转登录页面wx.redirectTo({url:’../../pages/login/login’,})}}})},globalData:{userInfo:null,baseUrl:’XXXXXXXXXXX’,imageUrl:’XXXXXXXX’}})login页面:wxml:viewclass=”login-container”viewclass=”login”wx:if=”{{!logged}}”viewclass=”app-info”imageclass=”app-logo”src=”{{logo}}”/textclass=”app-name”{{title}}/text/viewviewclass=”alert”viewclass=”alert-title”尊敬的用户,请确认授权以下信息/viewviewclass=”alert-desc”viewclass=”alert-text”获得你的公开信息(昵称、头像等)/view/view/viewbuttonclass=”weui-btn”type=”primary”open-type=”getUserInfo”bindgetuserinfo=”login”确认登录/button/viewviewclass=”logged”wx:elseimageclass=”logged-icon”src=”../../images/iconfont-weixin.png”/viewclass=”logged-text”近期你已经授权登陆过{{title}}/viewviewclass=”logged-text”自动登录中/view/view/viewjs:constapp=getApp();varAPI_URL=app.globalData.baseUrl+’/ZZTG/wXLoginController.do?decodeUserInfo’;Page({onLoad:function(){},login:function(e){wx.login({success:function(r){varcode=r.code;//登录凭证console.log(code)if(code){//2、调用获取用户信息接口wx.getUserInfo({success:function(res){console.log({encryptedData:res.encryptedData,iv:res.iv,code:code})//3.请求自己的服务器,解密用户信息获取unionId等加密信息wx.request({url:API_URL,//自己的服务接口地址method:’POST’,header:{‘content-type’:’application/x-www-form-urlencoded’},data:{encryptedData:res.encryptedData,iv:res.iv,code:code},success:function(data){//4.解密成功后获取自己服务器返回的结果if(data.data.status==1){varuserInfo_=data.data.userInfo;app.globalData.userInfo=userInfo_;console.log(userInfo_)}else{console.log(‘解密失败’)}},fail:function(){console.log(‘系统错误’)}})},fail:function(){console.log(‘获取用户信息失败’)}})}else{console.log(‘获取用户登录态失败!’+r.errMsg)}},fail:function(){console.log(‘登陆失败’)}})}})wxss:.login-container{height:100%;padding:10px30px;background:#fff;}.app-info{position:relative;padding:20px;text-align:center;}.app-info:after{content:””;position:absolute;left:0;bottom:0;right:0;height:1px;border-bottom:1pxsolid#E5E5E5;color:#E5E5E5;-webkit-transform-origin:0100%;transform-origin:0100%;-webkit-transform:scaleY(0.5);transform:scaleY(0.5);}.app-info.app-logo{display:block;width:64px;height:64px;margin:10pxauto;border-radius:4px;}.app-info.app-name{font-weight:bold;font-size:18px;color:#000;}.alert{margin:20px030px;}.alert.alert-title{font-weight:400;font-size:16px;color:#000;margin-bottom:10px;}.alert-desc{display:block;list-style:discinsidenone;}.alert.alert-text{display:list-item;text-align:-webkit-match-parent;font-size:14px;color:#999;}.logged{margin-top:100px;}.logged.logged-icon{display:block;width:64px;height:64px;margin:20pxauto;}.logged.logged-text{font-size:14px;color:#000;text-align:center;margin:10px0;}json:{“navigationBarBackgroundColor”:”#000000″,”navigationBarTitleText”:”微信登录”,”disableScroll”:true}后台java端:控制层:参考文中并没有给出Controller所引的包,在这里贴出packagecom.liruan.zztg.controller;importjava.util.HashMap;importjava.util.Map;importorg.activiti.engine.impl.util.json.JSONObject;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.ResponseBody;importcom.liruan.zztg.util.AesCbcUtil;importcom.liruan.zztg.util.HttpRequest;@Controller@RequestMapping(“/wXLoginController”)publicclassWXLoginController{@RequestMapping(params=”decodeUserInfo”)@ResponseBodypublicMapdecodeUserInfo(StringencryptedData,Stringiv,Stringcode){Mapmap=newHashMap();//登录凭证不能为空if(code==null||code.length()==0){map.put(“status”,0);map.put(“msg”,”code不能为空”);returnmap;}//小程序唯一标识(在微信小程序管理后台获取)StringwxspAppid=”wxd61ae972bca3dce6″;//小程序的appsecret(在微信小程序管理后台获取)StringwxspSecret=”8871bee8857cb7d997bcdbfb9d0c8438″;//授权(必填)Stringgrant_type=”authorization_code”;////////////////1、向微信服务器使用登录凭证code获取session_key和openid//////////////////////////////////请求参数Stringparams=”appid=”+wxspAppid+”&secret=”+wxspSecret+”&js_code=”+code+”&grant_type=”+grant_type;//发送请求Stringsr=HttpRequest.sendGet(“https://api.weixin.qq.com/sns/jscode2session”,params);//解析相应内容(转换成json对象)JSONObjectjson=newJSONObject(sr);//获取会话密钥(session_key)Stringsession_key=json.get(“session_key”).toString();//用户的唯一标识(openid)Stringopenid=(String)json.get(“openid”);////////////////2、对encryptedData加密数据进行AES解密////////////////try{Stringresult=AesCbcUtil.decrypt(encryptedData,session_key,iv,”UTF-8″);if(null!=result&&result.length()0){map.put(“status”,1);map.put(“msg”,”解密成功”);JSONObjectuserInfoJSON=newJSONObject(result);MapuserInfo=newHashMap();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”));//解密unionId&openId;if(!userInfoJSON.isNull(“unionId”)){userInfo.put(“unionId”,userInfoJSON.get(“unionId”));}map.put(“userInfo”,userInfo);}else{map.put(“status”,0);map.put(“msg”,”解密失败”);}}catch(Exceptione){e.printStackTrace();}returnmap;}}引用的两个工具类:AesCbcUtil.java和HttpRequest.java重点标识的这个jar包commons.codec.jar需要根据自己的jdk版本做对应的引入,我的是1.7的jdk,但程序里引入的1.3和1.9,一直报错,删除后引入1.7解决packagecom.liruan.zztg.util;importorg.apache.commons.codec.binary.Base64;importorg.bouncycastle.jce.provider.BouncyCastleProvider;importjavax.crypto.BadPaddingException;importjavax.crypto.Cipher;importjavax.crypto.IllegalBlockSizeException;importjavax.crypto.NoSuchPaddingException;importjavax.crypto.spec.IvParameterSpec;importjavax.crypto.spec.SecretKeySpec;importjava.io.UnsupportedEncodingException;importjava.security.;importjava.security.spec.InvalidParameterSpecException;/Createdbyyfson2018/3/25.pAES-128-CBC加密方式注:AES-128-CBC可以自己定义“密钥”和“偏移量“。AES-128是jdk自动生成的“密钥”。/publicclassAesCbcUtil{static{//BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/Security.addProvider(newBouncyCastleProvider());}/AES解密@paramdata//密文,被加密的数据@paramkey//秘钥@paramiv//偏移量@paramencodingFormat//解密后的结果需要进行的编码@return@throwsException/publicstaticStringdecrypt(Stringdata,Stringkey,Stringiv,StringencodingFormat)throwsException{//initialize();//被加密的数据byte[]dataByte=Base64.decodeBase64(data);//加密秘钥byte[]keyByte=Base64.decodeBase64(key);//偏移量byte[]ivByte=Base64.decodeBase64(iv);try{Ciphercipher=Cipher.getInstance(“AES/CBC/PKCS7Padding”);SecretKeySpecspec=newSecretKeySpec(keyByte,”AES”);AlgorithmParametersparameters=AlgorithmParameters.getInstance(“AES”);parameters.init(newIvParameterSpec(ivByte));cipher.init(Cipher.DECRYPT_MODE,spec,parameters);//初始化byte[]resultByte=cipher.doFinal(dataByte);if(null!=resultByte&&resultByte.length0){Stringresult=newString(resultByte,encodingFormat);returnresult;}returnnull;}catch(NoSuchAlgorithmExceptione){e.printStackTrace();}catch(NoSuchPaddingExceptione){e.printStackTrace();}catch(InvalidParameterSpecExceptione){e.printStackTrace();}catch(InvalidKeyExceptione){e.printStackTrace();}catch(InvalidAlgorithmParameterExceptione){e.printStackTrace();}catch(IllegalBlockSizeExceptione){e.printStackTrace();}catch(BadPaddingExceptione){e.printStackTrace();}catch(UnsupportedEncodingExceptione){e.printStackTrace();}returnnull;}}packagecom.liruan.zztg.util;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.URL;importjava.net.URLConnection;importjava.util.List;importjava.util.Map;publicclassHttpRequest{publicstaticvoidmain(String[]args){//发送GET请求Strings=HttpRequest.sendGet(“http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o”,””);System.out.println(s);////发送POST请求//Stringsr=HttpRequest.sendPost(“http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7″,””);//JSONObjectjson=JSONObject.fromObject(sr);//System.out.println(json.get(“data”));}/向指定URL发送GET方法的请求@paramurl发送请求的URL@paramparam请求参数,请求参数应该是name1=value1&name2=value2的形式。@returnURL所代表远程资源的响应结果/publicstaticStringsendGet(Stringurl,Stringparam){Stringresult=””;BufferedReaderin=null;try{StringurlNameString=url+”?”+param;URLrealUrl=newURL(urlNameString);//打开和URL之间的连接URLConnectionconnection=realUrl.openConnection();//设置通用的请求属性connection.setRequestProperty(“accept”,”/”);connection.setRequestProperty(“connection”,”Keep-Alive”);connection.setRequestProperty(“user-agent”,”Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)”);//建立实际的连接connection.connect();//获取所有响应头字段MapString,ListStringmap=connection.getHeaderFields();//遍历所有的响应头字段for(Stringkey:map.keySet()){System.out.println(key+”—“+map.get(key));}//定义BufferedReader输入流来读取URL的响应in=newBufferedReader(newInputStreamReader(connection.getInputStream()));Stringline;while((line=in.readLine())!=null){result+=line;}}catch(Exceptione){System.out.println(“发送GET请求出现异常!”+e);e.printStackTrace();}//使用finally块来关闭输入流finally{try{if(in!=null){in.close();}}catch(Exceptione2){e2.printStackTrace();}}returnresult;}/向指定URL发送POST方法的请求@paramurl发送请求的URL@paramparam请求参数,请求参数应该是name1=value1&name2=value2的形式。@return所代表远程资源的响应结果/publicstaticStringsendPost(Stringurl,Stringparam){PrintWriterout=null;BufferedReaderin=null;Stringresult=””;try{URLrealUrl=newURL(url);//打开和URL之间的连接URLConnectionconn=realUrl.openConnection();//设置通用的请求属性conn.setRequestProperty(“accept”,”/”);conn.setRequestProperty(“connection”,”Keep-Alive”);conn.setRequestProperty(“user-agent”,”Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)”);//发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);//获取URLConnection对象对应的输出流out=newPrintWriter(conn.getOutputStream());//发送请求参数out.print(param);//flush输出流的缓冲out.flush();//定义BufferedReader输入流来读取URL的响应in=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringline;while((line=in.readLine())!=null){result+=line;}}catch(Exceptione){System.out.println(“发送POST请求出现异常!”+e);e.printStackTrace();}//使用finally块来关闭输出流、输入流finally{try{if(out!=null){out.close();}if(in!=null){in.close();}}catch(IOExceptionex){ex.printStackTrace();}}returnresult;}}关于unionId这个信息是只给符合条件的用户下发,如不符合,则没有这个数据,在调用时需要做相应的判断,否则直接取值会报错,判断方法:if(!userInfoJSON.isNull(“unionId”)){userInfo.put(“unionId”,userInfoJSON.get(“unionId”));}

赞(0) 打赏
未经允许不得转载:E企盈小程序开发-热线:4006-838-530 » 微信获取用户信息,微信小程序之用户登录(获取用户信息,openid,unionld)java后台版
分享到: 更多 (0)
E企盈小程序直播营销卖货系统
E企盈直播平台营销卖货系统

评论 抢沙发

E企盈小程序开发

联系我们联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏