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

参考文章:https://blog.csdn.net/guochanof/article/details/80189935;感谢作者给的思路与大部分问题解决办法

由于微信官方api的更改,wx.getuserinfo()方法无法在无授权的情况下直接使用,参考文中作者是直接可以拉取授权,但到我这里失效了,查看错误信息是

fail scope unauthorized 

获取授权信息失败;查看官方文档https://developers.weixin.qq.com/blogdetail?action=get_post_info&lang=zh_CN&token=384460955&docid=000aee01f98fc0cbd4b6ce43b56c01后得到解决办法,需要用户手动点击button后调用授权,更改后成功.具体代码及后台如下:

1.微信端

app.js:

//app.js
App ({
onLaunch : function () {
// 展示本地存储能力
var logs = wx .getStorageSync ( 'logs' ) || []
logs .unshift (Date .now ())
wx .setStorageSync ( 'logs' , logs )
var that = this ;
// 获取用户信息
wx .getSetting ({
success : res => {
if (res .authSetting [ 'scope.userInfo' ]) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx .getUserInfo ({
success : function (res ) {
that .globalData .userInfo = res .userInfo
console .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:

< view class= "login-container" >
   < view class= "login" wx:if= "{{ !logged }}" >
     < view class= "app-info" >
       < image class= "app-logo" src= "{{logo}}" / >
       < text class= "app-name" >{{title}} </ text >
     </ view >
     < view class= "alert" >
       < view class= "alert-title" >尊敬的用户,请确认授权以下信息 </ view >
       < view class= "alert-desc" >
         < view class= "alert-text" >获得你的公开信息(昵称、头像等) </ view >
       </ view >
     </ view >
     < button class= "weui-btn" type= "primary" open-type= "getUserInfo" bindgetuserinfo= "login" >确认登录 </ button >
   </ view >
   < view class= "logged" wx:else >
     < image class= "logged-icon" src= "../../images/iconfont-weixin.png" / >
     < view class= "logged-text" >近期你已经授权登陆过{{title}} </ view >
     < view class= "logged-text" >自动登录中 </ view >
   </ view >
</ view >

js:

const app = getApp ();
var API_URL = app .globalData .baseUrl + '/ZZTG/wXLoginController.do?decodeUserInfo' ;
Page ({
onLoad : function () {
},
login : function (e ){
wx .login ({
success : function (r ) {
var code = 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 ) {
var userInfo_ = 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: 10px 30px ;
   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: 1px solid #E5E5E5 ;
color: #E5E5E5 ;
-webkit-transform-origin: 0 100% ;
transform-origin: 0 100% ;
-webkit-transform: scaleY( 0.5 ) ;
transform: scaleY( 0.5 ) ;
}

.app-info .app-logo {
   display: block ;
   width: 64px ;
   height: 64px ;
   margin: 10px auto ;
   border-radius: 4px ;
}

.app-info .app-name {
   font-weight: bold ;
   font-size: 18px ;
   color: #000 ;
}

.alert {
   margin: 20px 0 30px ;
}

.alert .alert-title {
   font-weight: 400 ;
   font-size: 16px ;
   color: #000 ;
   margin-bottom: 10px ;
}

.alert-desc {
   display: block ;
list-style: disc inside none ;
}

.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: 20px auto ;
}

.logged .logged-text {
   font-size: 14px ;
   color: #000 ;
   text-align: center ;
   margin: 10px 0 ;
}

json:

{
"navigationBarBackgroundColor" : "#000000" ,
"navigationBarTitleText" : "微信登录" ,
"disableScroll" : true
}

后台java端:

控制层:参考文中并没有给出Controller所引的包,在这里贴出

package com.liruan.zztg.controller;

import java.util.HashMap;

import java.util.Map;

import org.activiti.engine.impl.util.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liruan.zztg.util.AesCbcUtil;
import com.liruan.zztg.util.HttpRequest;
@Controller
@RequestMapping("/wXLoginController")
public class WXLoginController {
	
    @RequestMapping(params = "decodeUserInfo")  
    @ResponseBody  
    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 = "wxd61ae972bca3dce6";  
    // 小程序的 app secret (在微信小程序管理后台获取)  
    String wxspSecret = "8871bee8857cb7d997bcdbfb9d0c8438";  
    // 授权(必填)  
    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 = new JSONObject(sr);  
    // 获取会话密钥(session_key)  
    String session_key = json.get("session_key").toString();  
    // 用户的唯一标识(openid)  
    String openid = (String) json.get("openid");  

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

            JSONObject userInfoJSON = new JSONObject(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"));  
            // 解密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 (Exception e) {  
        e.printStackTrace();  
    }       	return map;  
	}
}

引用的两个工具类:AesCbcUtil.java和HttpRequest.java   

重点标识的这个jar包commons.codec.jar需要根据自己的jdk版本做对应的引入,我的是1.7的jdk,但程序里引入的1.3和1.9,一直报错,删除后引入1.7解决

package com.liruan.zztg.util;

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; /** * Created by yfs on 2018/3/25. * <p> * AES-128-CBC 加密方式 * 注: * AES-128-CBC可以自己定义“密钥”和“偏移量“。 * AES-128是jdk自动生成的“密钥”。 */ public class AesCbcUtil { 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 { // initialize(); //被加密的数据 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; } }
package com.liruan.zztg.util;

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.PrintWriter;  
import java.net.URL;  
import java.net.URLConnection;  
import java.util.List;  
import java.util.Map;  
  
public class HttpRequest {  
  
    public static void main(String[] args) {  
        //发送 GET 请求  
        String s=HttpRequest.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");  
        System.out.println(s);  
  
//        //发送 POST 请求  
//        String sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7", "");  
//        JSONObject json = JSONObject.fromObject(sr);  
//        System.out.println(json.get("data"));  
    }  
  
    /** 
     * 向指定URL发送GET方法的请求 
     *  
     * @param url 
     *            发送请求的URL 
     * @param param 
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 
     * @return URL 所代表远程资源的响应结果 
     */  
    public static String sendGet(String url, String param) {  
        String result = "";  
        BufferedReader in = null;  
        try {  
            String urlNameString = url + "?" + param;  
            URL realUrl = new URL(urlNameString);  
            // 打开和URL之间的连接  
            URLConnection connection = realUrl.openConnection();  
            // 设置通用的请求属性  
            connection.setRequestProperty("accept", "*/*");  
            connection.setRequestProperty("connection", "Keep-Alive");  
            connection.setRequestProperty("user-agent",  
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
            // 建立实际的连接  
            connection.connect();  
            // 获取所有响应头字段  
            Map<String, List<String>> map = connection.getHeaderFields();  
            // 遍历所有的响应头字段  
            for (String key : map.keySet()) {  
                System.out.println(key + "--->" + map.get(key));  
            }  
            // 定义 BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(new InputStreamReader(  
                    connection.getInputStream()));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {  
            System.out.println("发送GET请求出现异常!" + e);  
            e.printStackTrace();  
        }  
        // 使用finally块来关闭输入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        }  
        return result;  
    }  
  
    /**  
     * 向指定 URL 发送POST方法的请求  
     *   
     * @param url  
     *            发送请求的 URL  
     * @param param  
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。  
     * @return 所代表远程资源的响应结果  
     */  
    public static String sendPost(String url, String param) {  
        PrintWriter out = null;  
        BufferedReader in = null;  
        String result = "";  
        try {  
            URL realUrl = new URL(url);  
            // 打开和URL之间的连接  
            URLConnection conn = realUrl.openConnection();  
            // 设置通用的请求属性  
            conn.setRequestProperty("accept", "*/*");  
            conn.setRequestProperty("connection", "Keep-Alive");  
            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()));  
            String line;  
            while ((line = in.readLine()) != null) {  
                result += line;  
            }  
        } catch (Exception e) {  
            System.out.println("发送 POST 请求出现异常!"+e);  
            e.printStackTrace();  
        }  
        //使用finally块来关闭输出流、输入流  
        finally{  
            try{  
                if(out!=null){  
                    out.close();  
                }  
                if(in!=null){  
                    in.close();  
                }  
            }  
            catch(IOException ex){  
                ex.printStackTrace();  
            }  
        }  
        return result;  
    }      
} 

关于unionId

这个信息是只给符合条件的用户下发,如不符合,则没有这个数据,在调用时需要做相应的判断,否则直接取值会报错,判断方法:

if (!userInfoJSON.isNull("unionId")) {
      userInfo.put("unionId", userInfoJSON.get("unionId"));  
}





猜你喜欢

转载自blog.csdn.net/weixin_41722987/article/details/80292435