PHP 处理微信文本内容安全识别
踩坑处
- 给微信传值时注意content字段是经过UTF8处理的,如果未处理则什么都是通过
- 在传递scene时,注意使用场景,目前发现2的权重较高些
- 获取ACCESS_TOKEN的地方,这里可以使用微信推荐的access_token或者authorizer_access_token都可以
public function wxCheck(string $openId, string $title, string $content = null)
{
$data = [
'openid' => $openId,
'scene' => 2,
'version' => 2,
'content' => $title,
];
isset($content) && $data['title'] = $content;
$result = $this->postsCurl($data);
if (isset($result['errcode']) && $result['errcode'] == 0 && $result['result']['suggest']=='pass') {
return 1;
} else {
return 0;
}
}
public function postsCurl(array $data)
{
// 构造请求头
$headers = array(
'Content-Type: application/json'
);
// 定义变量
$url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" . $this->getWxToken();
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
public function getWxToken()
{
$token = Redis::get('wx_token');
if (!$token) {
//从微信服务器获取 token
$appid = 'appid';//小程序的appid
$secret = 'secret';//小程序的AppSecret
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
$tmptoken = json_decode($res);
$token = $tmptoken->access_token;
Redis::setex('wx_token', 7200, $token);
}
return $token;
}