老样子直接上代码
需要注意的是
- 1、就是必须是post提交
- 2、必须是utf-8编码,这个地方不是对你要验证的内容是utf-8编码,而是你进行json_encode编码时,最后编码的数据是 utf-8编码,原因如下:
$data = json_encode(array('content'=>$checkContent),JSON_UNESCAPED_UNICODE),然后再调用msgSecCheck的api。
JSON_UNESCAPED_UNICODE(中文不转为unicode ,对应的数字256)
虽然mb_detect_encoding验证单独的内容已经是utf-8,但是json编码是不使用JSON_UNESCAPED_UNICODE,$data其实是ASCII编码,而非utf-8,就导致验证什么内容均可通过检测
/**
* [msgSecCheck 小程序内容检测]
* @author xiancai
* @Date 2021-01-04
* @param [type] [description]
* @return [type] [description]
*/
public function msgSecCheck(){
if(!$this->request->post('content')){
$this->error(__('Parameter %s can not be empty','content'));
}
$access_token = $this->getAccessToken('wxxxxxxx87','6xxxxxxxxxxxxxxxxx00');
$url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=$access_token";
$str = $this->request->post('content');
$data = json_encode(array('content'=>$str),JSON_UNESCAPED_UNICODE); //虽然mb_detect_encoding验证单独的内容已经是utf-8,但是json编码是不使用JSON_UNESCAPED_UNICODE,$data其实是ASCII编码,而非utf-8,就导致验证什么内容均可通过检测
$info = http_request($url,$data);
if($info){
$info = json_decode($info,true);
}
$this->success(__('Get success'), ['info'=>$info]);
}
/**
* 获取小程序全局唯一后台接口调用凭据 accessToken
* access_token 的有效期目前为 2 个小时,需定时刷新,重复获取将导致上次获取的 access_token 失效;
* @param appid 小程序appid
* @param appsecret 小程序公众号秘钥
*/
public static function getAccessToken($appid,$appsecret)
{
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
// 如果accessToken 不存在或者已过期,则重新去生成一个
$token = $redis->get("jw_applet_accessToken");
if (!$token) {
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
$html = file_get_contents($url);
$output = json_decode($html, true);
$access_token = $output['access_token'];
/**
* 微信平台会保证 在5分钟内,新老 access_token 都可用,所以需要提前去刷新,这里设置提前4分钟进行刷新
* 创建一个具有时间限制的键值,过期则删除,秒为单位,成功返回true
*/
$redis->setex('jw_applet_accessToken', $output['expires_in'] - 240, $access_token);
return $access_token;
}
return $token;
}
http_request
/**
- [http_request 支持post/get]
- @author xiancai
- @Date 2021-01-04
- @param [type] [description]
- @param [type] $url [description]
- @param [type] $data [description]
- @return [type] [description]
*/
function http_request($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
file_put_contents('/tmp/heka_weixin.' . date("Ymd") . '.log', date('Y-m-d H:i:s') . "\t" . $output . "\n", FILE_APPEND);
return $output;
}