####主要是为了调用微信小程序msgSecCheck、imgSecCheck接口。
1 先附上小程序接口说明文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/sec-check/msgSecCheck.html 2 1、首先要获取access_token(需要appId、appSecret、grant_type这个是固定值); 3 ###msgSecCheck接口: 4 2、用获取到的token带入到微信端的接口地址: https://api.weixin.qq.com/wxa/msg_sec_check?access_token=ACCESS_TOKEN。 5 这里需要注意的是: 1、message信息的格式要是JSON格式,不能直接传string,不然会报 47001,data format error hin 错误。 6 ###imgSecCheck接口: 7 3、用获取到的token带入到微信端的接口地址:https://api.weixin.qq.com/wxa/img_sec_check?access_token=ACCESS_TOKEN。 8 这里需要注意的是: 1、image的格式要是formdata 格式,不能直接传url,不然会报 41005,media data missing hin 错误。参数名应该使用:media,这是小程序定好的。 9 我这里是获取到微信上传的图片的url,然后把它下载到一个存放临时文件的区/dev/shm,然后再转为curlFile()对象 。 10 附上具体代码: 11 12 /*微信图片敏感内容检测*/ 13 public function imgSecCheck($img) 14 { 15 $img = file_get_contents($img); 16 $filePath = '/dev/shm/tmp1.png'; 17 file_put_contents($filePath, $img); 18 $obj = new CURLFile(realpath($filePath)); 19 $obj->setMimeType("image/jpeg"); 20 $file['media'] = $obj; 21 $token = $this->getAccessToken(); 22 $url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=$token"; 23 $info = $this->http_request($url,$file); 24 return json_decode($info,true); 25 } 26 27 /*微信文字敏感内容检测*/ 28 public function msgSecCheck($msg) 29 { 30 $token = $this->getAccessToken(); 31 $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=$token"; 32 $info = $this->http_request($url,json_encode($msg)); 33 return json_decode($info,true); 34 } 35 36 /*获取access_token,不能用于获取用户信息的token*/ 37 public function getAccessToken() 38 { 39 $token_file = '/dev/shm/heka_token.json'; 40 $data = json_decode(file_get_contents($token_file)); 41 if ($data->expire_time < time()) { 42 $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret"; 43 $res = json_decode($this->http_request($url)); 44 $access_token = $res->access_token; 45 if ($access_token) { 46 $data->expire_time = time() + 7000; 47 $data->access_token = $access_token; 48 file_put_contents($token_file, json_encode($data)); 49 } 50 } else { 51 $access_token = $data->access_token; 52 } 53 return $access_token; 54 } 55 56 57 //HTTP请求(支持HTTP/HTTPS,支持GET/POST) 58 private function http_request($url, $data = null) 59 { 60 $curl = curl_init(); 61 curl_setopt($curl, CURLOPT_URL, $url); 62 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); 63 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); 64 65 if (!empty($data)) { 66 curl_setopt($curl, CURLOPT_POST, TRUE); 67 curl_setopt($curl, CURLOPT_POSTFIELDS,$data); 68 } 69 curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); 70 $output = curl_exec($curl); 71 curl_close($curl); 72 file_put_contents('/tmp/heka_weixin.' . date("Ymd") . '.log', date('Y-m-d H:i:s') . "\t" . $output . "\n", FILE_APPEND); 73 return $output; 74 }
转载的话:记得带上原文链接哦^_^ https://www.cnblogs.com/xinxinmifan/p/9722876.html