微信获取code
//获取微信code 用于解密手机号密文,获取openid
getWxCode() {
let that = this;
uni.login({
provider: 'weixin',
success: function(res) {
var code = res.code;
if (code) {
that.code = code
console.log('code:',code);
}
}
});
},
授权获取手机号:需要按钮引导授权才行
<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">+添加关注影院</button>
//获取手机号
getPhoneNumber(e) {
//用户授权获取
if (e.detail.errMsg == "getPhoneNumber:ok"){
console.log(e.detail.errMsg);
console.log(e.detail.iv);
console.log(e.detail.encryptedData);
//this.getWxCode();
//解密手机号
this.getPhoneByCode(e.detail.iv,e.detail.encryptedData)
}else {
//用户取消授权
}
},
授权获取用户信息:需要按钮引导授权才行
<button open-type="getUserInfo" @getuserinfo="getuserinfo" class="login_btn color_fff">登录</button>
getuserinfo(e) {
let that = this;
console.log(e)
uni.login({
success: function(data) {
that.getOpenId(data.code,e.detail.userInfo.nickName)
},
fail: function(err) {
console.log('wx.login 接口调用失败,将无法正常使用开放接口等服务', err);
callback(err);
}
});
},
后台解密信息
import cn.gjing.http.HttpClient;
import cn.gjing.http.HttpMethod;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yz.zygfyz.bean.AppParam;
import com.yz.zygfyz.config.WxApiConf;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
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;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class demo {
private Logger logger = LogManager.getLogger(this.getClass());
/**
* 解密用户敏感数据获取用户信息
*
* @param sessionKey 数据进行加密签名的密钥
* @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
* @param iv 加密算法的初始向量
* @return
* @author YeFei
*/
public JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
// 被加密的数据
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) {
logger.error(e.getMessage(), e);
} catch (NoSuchPaddingException e) {
logger.error(e.getMessage(), e);
} catch (InvalidParameterSpecException e) {
logger.error(e.getMessage(), e);
} catch (IllegalBlockSizeException e) {
logger.error(e.getMessage(), e);
} catch (BadPaddingException e) {
logger.error(e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
} catch (InvalidKeyException e) {
logger.error(e.getMessage(), e);
} catch (InvalidAlgorithmParameterException e) {
logger.error(e.getMessage(), e);
} catch (NoSuchProviderException e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* 根据code获取openid unionid sessionKey
* @param appParam
* @return
*/
public Map getOpenIdByCode(AppParam appParam){
Map result = new HashMap();
String url = "https://api.weixin.qq.com/sns/jscode2session";
url += "?appid=" + WxApiConf.appid;
url += "&secret=" + WxApiConf.secret;
url += "&js_code=" + appParam.getCode();
url += "&grant_type=authorization_code";
// url += "&connect_redirect=1";
Map map = HttpClient.builder(url, HttpMethod.GET, Map.class)
.execute().get();
logger.info(map);
String openId = map.get("openid") == null ? "" : map.get("openid").toString();
String unionId = map.get("unionid") == null ? "" : map.get("unionid").toString();
String session_key = map.get("session_key") == null ? "" : map.get("session_key").toString();
if (null != openId) {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("openId", openId);
dataMap.put("unionId", unionId);
dataMap.put("session_key", session_key);
result.put("result", dataMap);
result.put("code", 0);
result.put("message", "成功");
}else{
result.put("code", 1);
result.put("message", "失败");
}
return result;
}
}
小程序间跳转:
//方式一 函数执行跳转
wx.navigateToMiniProgram({
appId: '12312312312', // 需要跳转到指定的小程序appid
path: 'pages/index/index', // 打开的页面
envVersion: 'release',
success(res) {
// 打开成功
}
})
注意:小程序功能需要用到code的地方 一个code只能使用一次,如根据code获取openid后需要获取手机号或者用户信息,此时code需要重新获取一个新的,不然会获取失败
此文仅做记录,如有误差请留言!