PHP 处理微信文本内容安全识别

PHP 处理微信文本内容安全识别

踩坑处

  1. 给微信传值时注意content字段是经过UTF8处理的,如果未处理则什么都是通过
  2. 在传递scene时,注意使用场景,目前发现2的权重较高些
  3. 获取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;
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值