小程序Openid 获取,服务器 encryptedData 解密 遇到的坑

获取客户 openId 和 unionId 需要以下步骤(都为必须步骤)

1.从验证从客户端传上来code, 获取sessionKey (需要配合小程序appid ,secret 发送到微信服务器)

$params = [
   'appid' => $this->appid,
   'secret' => $this->secret,
   'js_code' => $this->code,
   'grant_type' => $this->grant_type
];

2.获取到微信服务器 返回信息

(通过客户端传来的 原始数据 + 获取的sessionKey 与客户端传来的 签名对比)

$signature = sha1($this->rawData . $this->sessionKey);
if ($signature !== $this->signature){ return $this->ret_message("signNotMatch"."sessionKey 签名不匹配"); }

3.重要环节:

通过 服务器返回的 session_key 解密 客户端上传的加密数据

/* 3.通过 服务器返回的 session_key 解密 客户端上传的加密数据
* 需要参数
* [
     "appid"=>$this->appid,
     "sessionKey"=>$sessionKey,
     "encryptedData"=>$this->encryptedData,
     "iv"=>$this->iv,
    ];
*/

坑:客户端上传的 encryptedData 需要用encodeURIComponent方法进行URL编码,对应服务端需要URL解码

坑:客户端上传的 encryptedData 需要用encodeURIComponent方法进行URL编码,对应服务端需要URL解码

坑:客户端上传的 encryptedData 需要用encodeURIComponent方法进行URL编码,对应服务端需要URL解码

重要的事情说三遍!

小程序:

encodeURIComponent(data.encryptedData);//一定要把加密串转成URL编码

对应服务端需要进行URL解码 否则出现解密结果 为NULL的错误

服务端

<?php
//php 端接受数据 时做url解码
$encryptedData=urldecode($_GET["encryptedData"]);