微信小程序授权登录获取用户openID,unionId

小程序必须先绑定公众号不然获取不到unionId

logs.js

Page({
  data: {
    //判断小程序的API,回调,参数,组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    var that = this;
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              console.info("已经授权");
             // that.queryUsreInfo(res);
              //从数据库获取用户信息
              that.queryUsreInfo(res);
              //用户已经授权过
              wx.reLaunch({
                url: '/pages/index/index'
              })
            }
          });
        }
      }
    })
  },
  bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      console.info("用户按了允许授权按钮");
      var that = this;
      that.queryUsreInfo(e.detail);
      //授权成功后,跳转进入小程序首页
      wx.reLaunch({
        url: '/pages/index/index'
      })
    } else {
      //用户按了拒绝按钮
      console.info("用户按了拒绝按钮");
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  },
  //获取用户信息接口
  queryUsreInfo: function (detail) {
    console.info("queryUsreInfo" + detail);
    wx.login({
      success: function (res) {
        var code = res.code; 
          // userInfo 只存储个人的基础数据
          wx.setStorageSync('userInfo', res.userInfo);
          // 请求自己的服务器,解密用户信息 获取unionId等加密信息
          wx.request({
            url: 'url',//自己的服务接口地址
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              encryptedData: detail.encryptedData,
              iv: detail.iv,
              code: code,
            },
            success: function (data) {
              //4.解密成功后 获取自己服务器返回的结果
              if (data.data.code == 200) {
                console.log('解密成功' + JSON.stringify(data.data));
                var encryptInfo = data.data;
                wx.setStorageSync('openid', encryptInfo.openid); // 单独存储openid
                wx.setStorageSync('encryptInfo', encryptInfo); // 存储解密之后的数据
              } else {
                console.log('解密失败')
              }
            },
            fail: function (res) {
              console.log(res);
              console.log('请求错误')
            }
          })
      }
    })
  },
})

logs.wxml


    
        
    
 
    
        申请获取以下权限
        获得你的公开信息(昵称,头像等)
    
 
    

 
请升级微信版本

logs.wxss

.header {
    margin: 90rpx 0 90rpx 50rpx;
    border-bottom: 1px solid #ccc;
    text-align: center;
    width: 650rpx;
    height: 300rpx;
    line-height: 450rpx;
}
 
.header image {
    width: 200rpx;
    height: 200rpx;
}
 
.content {
    margin-left: 50rpx;
    margin-bottom: 90rpx;
}
 
.content text {
    display: block;
    color: #9d9d9d;
    margin-top: 40rpx;
}
 
.bottom {
    border-radius: 80rpx;
    margin: 70rpx 50rpx;
    font-size: 35rpx;
}

logs.json

{
  "navigationBarTitleText": "授权登录"
}

服务器处理

需要导入的jar包


    org.codehaus.xfire
    xfire-core
    1.2.6


    org.bouncycastle
    bcprov-jdk16
    1.46

	String requestUrl= "https://api.weixin.qq.com/sns/jscode2session?appid=自己的appid&secret=自己的secret&js_code=cede&grant_type=authorization_code"
	Map map = HTTPSUtil.get(requestUrl, null);
	//解密过程
	Map userMap = null;
	// 被加密的数据
	byte[] dataByte = Base64.decode(reqMap.get("encryptedData").toString());
	// 加密秘钥
	byte[] keyByte = Base64.decode(map.get("session_key").toString());
	// 偏移量
	byte[] ivByte = Base64.decode(reqMap.get("iv").toString());
	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");
	       userMap = JSONObject.fromObject(result);
	   }
	} catch (NoSuchAlgorithmException e) {
	   e.printStackTrace();
	} catch (NoSuchPaddingException e) {
	   e.printStackTrace();
	} catch (InvalidParameterSpecException e) {
	   e.printStackTrace();
	} catch (IllegalBlockSizeException e) {
	   e.printStackTrace();
	} catch (BadPaddingException e) {
	   e.printStackTrace();
	} catch (UnsupportedEncodingException e) {
	   e.printStackTrace();
	} catch (InvalidKeyException e) {
	   e.printStackTrace();
	} catch (InvalidAlgorithmParameterException e) {
	   e.printStackTrace();
	} catch (NoSuchProviderException e) {
	   e.printStackTrace();
	}
}

http工具类

package *;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bns.sp.utils.JsonUtil;

/**
 * 发送HTTPS请求工具类
 * 
 * @author leeon
 */
public class HTTPSUtil {
	
	private static Logger log = LoggerFactory.getLogger(HTTPSUtil.class);

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式(GET、POST)
	 * @param requestData
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	@SuppressWarnings("unchecked")
	private static Map httpRequest(String requestUrl, String requestMethod, String requestData) {

		Map map = new HashMap();
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象,并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != requestData) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(requestData.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			log.info("微信返回:" + buffer.toString());
			map = JsonUtil.parseObject(buffer.toString(), Map.class);
		} catch (ConnectException ce) {
			System.out.println("Weixin server connection timed out.");
			log.error("", ce);
		} catch (Exception e) {
			System.out.println("https request error");
			log.error("", e);
		}
		return map;
	}

	public static Map get(String requestUrl, String requestData) {
		return httpRequest(requestUrl, "GET", requestData);
	}

	public static Map post(String requestUrl, String requestData) {
		return httpRequest(requestUrl, "POST", requestData);
	}
	
}

你可能感兴趣的:(小程序)