背景
在使用小程序获得用户手机,返回服务器解密,总是不间断的出现错误。错误代码为
nodejs.ERR_OSSL_EVP_BAD_DECRYPTError: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

开发环境
前端:mpvue
后端:eggjs
错误原因
以上两个错均是解密时 sessionKey 与获取到的 加密串没有匹配。
必须进入页面就静默走一次登录流程,只有成功以后才能点击按钮。server 拿到加密信息才能正确解密。
参考代码
第一步:在页面加载的时候就调用login,获得session
onLoad() {
// 测试
this.getCode(); // 默认登录,获得code和session、openid
},
getCode() {
wx.login({
success: (res) => {
console.log(res);
this.getOpenid(res.code);
},
});
},
getOpenid(code) {
const appid = "xxxx"; // 请更换您自己的appid
const secret = "xxxx"; // 请更换您自己的secret
const data = { appid, secret, code };
this.$https
.request({
url: this.$interfaces.getOpenid,
method: "post",
data: data,
})
.then((res) => {
console.log(res);
// 将openid存储到vuex中
this.$store.dispatch("setOpenId", res.openid);
this.$store.dispatch("setSessionKey", res.session_key);
})
.catch((err) => console.log(err));
},
第二步:编写checkSession代码,专门用于在提交的时候检查session是否变化
checkSession() {
wx.checkSession({
success: () => {
// 未过期
console.log(this.$store.getters.sessionKey);
},
fail: () => {
// 过期
this.getCode();
},
});
},
第三步:调用getPhoneNumber获得用户手机
<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
{{ username }}
</button>
getPhoneNumber(e) {
// 判断授权是否成功
console.log(e);
if (e.mp.detail.errMsg === "getPhoneNumber:ok") {
console.log(1);
console.log(e.mp.detail.errMsg);
this.iv = e.mp.detail.iv;
this.encryptedData = e.mp.detail.encryptedData;
this.$store.dispatch("setIsAuthenticated",
this.checkSession(); // 检查session是否改变
this.decryptPhoneNumber(
this.$store.getters.openId,
this.$store.getters.sessionKey
);
},
decryptPhoneNumber(openid, session_key) {
const data = {
openId: openid,
sessionKey: session_key,
iv: this.iv,
encryptedData: this.encryptedData,
};
this.$https
.request({
url: this.$interfaces.decryptPhoneNumber, // 请更换您自己的url
method: "post",
data: data,
})
.then((res) => {
this.$store.dispatch("setPhone", res);
})
.catch((err) => console.log(err));
},
问题解决。
问题点
微信小程序的session是定期更新的,一般出错就是因为session出错,所以在自开始页面加载就获得code、openid和session。在每次调用页面的时候再更新程序。
网友评论