直接上代码
class WechatService extends Frontend
{
protected $noNeedLogin = '*';
protected $noNeedRight = '*';
protected $layout = '';
private $token;
private $encodingAesKey;
private $appId;
public function __construct($token = "前端设置的token", $encodingAesKey = "前端设置的encodingAesKey", $appId = "企业微信的corpid")
{
$this->token = $token;
$this->encodingAesKey = base64_decode($encodingAesKey . '=');
$this->appId = $appId;
}
/**
* 回调地址
*/
public function callback() {
file_put_contents('wechat1.log',json_encode($_GET));
$xml = $this->decryptMsg($_GET['echostr']);
echo $xml;
}
public function decryptMsg($encryptMsg)
{
// 对密文进行解密
$ciphertext_dec = base64_decode($encryptMsg);
$iv = substr($this->encodingAesKey, 0, 16);
$decrypted = openssl_decrypt($ciphertext_dec, 'AES-256-CBC', $this->encodingAesKey, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
// 去除补位字符
$result = $this->decode($decrypted);
// 去除16位随机字符串, 网络字节序
if (strlen($result) < 16) {
return "";
}
$content = substr($result, 16, strlen($result));
$len_list = unpack("N", substr($content, 0, 4));
$xml_len = $len_list[1];
$xml_content = substr($content, 4, $xml_len);
$from_appid = substr($content, $xml_len + 4);
if ($from_appid != $this->appId) {
return "";
}
return $xml_content;
}
private function decode($text)
{
$pad = ord(substr($text, -1));
if ($pad < 1 || $pad > 32) {
$pad = 0;
}
return substr($text, 0, (strlen($text) - $pad));
}