为了避免小程序与开发者后台通信时数据被截取和篡改,微信侧维护了一个用户维度的可靠key,用于小程序和后台通信时进行加密和签名。开发者可以分别通过小程序前端和微信后台提供的接口,获取用户的加密 key来实现数据的加密和解密
对于在小程序中调用接口时需要防止用户脱离小程序调用接口时使用,例如登录,注册等敏感接口时使用小程序加密网络通道来实现数据加密传输
//someAESEncryptMethod 和 someAESDEcryptMethod 分别为加解密函数,由开发者自行引入加解密库来实现
const somedata = 'xxxxx'
const userCryptoManager = wx.getUserCryptoManager()
userCryptoManager.getLatestUserKey({
success({encryptKey, iv, version, expireTime}) {
const encryptedData = someAESEncryptMethod(encryptKey, iv, somedata)
wx.request({
data: encryptedData,
success(res) {
const decryptedData = someAESDEcryptMethod(encryptKey, iv, res.data)
console.log(decryptedData)
}
})
}
})
//使用easywechat拓展实现
//$code 表示用户登录凭证,$data表示接口传递参数
$miniProgram = Yii::$app->wechat->miniProgram;
$code2Session = $miniProgram->auth->session($code);
if (isset($code2Session['openid'], $code2Session['session_key'])) {
$result = $miniProgram->auth->request(
'wxa/business/getuserencryptkey',
'POST',
[
'query' => [
'openid' => $code2Session['openid'],
'signature' => bin2hex(hash_hmac('sha256', '', $code2Session['session_key'], true)),
'sig_method' => 'hmac_sha256'
]
]
);
if (isset($result['errcode']) && $result['errcode'] == 0) {
$encryptKeyData = ArrayHelper::getValue($result, ['key_info_list', 0]);
$encrypt_key = $encryptKeyData['encrypt_key'];
$iv = $encryptKeyData['iv'];
$data = openssl_decrypt(base64_decode($data), 'AES-256-CBC', $encrypt_key, 0, $iv);
//业务代码处理
......
$result = 'XXX';//返回数据
return openssl_encrypt(base64_encode($result), 'AES-256-CBC', $encrypt_key, 0, $iv)
}
}
return false;