项目需要验证用户发布文章内容是否违规发现了微信公众平台有一个文本检测接口,只需要有公众号appid和secret就行了
微信接口官方网址:https://mp.weixin.qq.com/cgi-bin/announce?token=976729357&action=getannouncement&key=11522142966rk3L2&version=1&lang=zh_CN&platform=2
为了方便使用封装了一个类
<?php
class Util_Verification
{
private $appid;
private $appSecret;
public function __construct() {
//获取配置文件中的appid和appsecrt
$conf = new Yaf_Config_Ini($ini_file);
$this->appid = $conf->get('WX_APPID');
$this->appSecret = $conf->get('WX_APPSECRT');
}
/**
* 获取微信AccessToken
*/
public function getAccessToken()
{
$redis = Cache_Redis::getInstance();
$accessToken = $redis->read('AccessToken');
if(empty($accessToken)){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appSecret;
$info=curl_init();
curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
curl_setopt($info,CURLOPT_HEADER,0);
curl_setopt($info,CURLOPT_NOBODY,0);
curl_setopt($info,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($info,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($info,CURLOPT_URL,$url);
$output= curl_exec($info);
curl_close($info);
$result = json_decode($output, true);
if (!empty($result['errcode'])) {
return $result['errmsg'];
}else{
//为了方便放到了redis里
$accessToken = $result['access_token'];
$redis->write('AccessToken', $accessToken, 30);
}
}
return $accessToken;
}
/**
* 违规验证
* @param $content
* @return array
*/
public function msgSecCheck($content)
{
$accessToken = $this->getAccessToken();
$url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=".$accessToken;
$postdata = json_encode(['content'=>$content],JSON_UNESCAPED_UNICODE);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 3 ,// 超时时间(单位:s)
'user-Agent' => "Mozilla/5.0 (Windows NT 6.1; rv:21.0) Gecko/20100101 Firefox/21.0\r\n" .
"X-Requested-With: XMLHttpRequest",
)
);
$context = stream_context_create($options);
try{
$result = file_get_contents($url,false, $context);
$result = json_decode($result, true);
if (!$result) {
throw new \Exception("获取信息失败,请重新打开页面");
}
return $result;
}catch (Exception $exception) {
return $exception->getMessage();
}
}
}