微信小程序内容安全检测接口代码

UniApp2023-09-1149 人已阅来源:网络

UNIAPP前端代码:

msgSecCheck(){
	wx.login({
		success: function(res) {
			uni.request({
				url: 'https://mingpian.senguokeji.com/index.php?s=api/ThirdData/danmuMsgSecCheck', //仅为示例,并非真实接口地址。
				data: { code: res.code, content:'摸你大咪咪' },
				header:{'content-type': 'application/x-www-form-urlencoded'},
				success: (res) => {
					if(res.data.status != 200){
						uni.showModal({
							title: '系统提示',
							showCancel: false,
							content:res.data.message
						})
						return false
					}
					// 页面逻辑
					
				},
				fail: (res) => {
					// 页面逻辑
					
				}
			});
		},
		fail: function(res) {
			// 页面逻辑
			
		}
	})
},

后端接口代码:

/**
     * 【手持弹幕】微信小程序内容安全检测
     * 接口地址:https://mingpian.senguokeji.com/index.php?s=api/ThirdData/danmuMsgSecCheck
     * @return \think\response\Json
     * @throws \cores\exception\BaseException
     */
    public function danmuMsgSecCheck(){
        $content = $this->request->param('content');
        $code = $this->request->param('code');
        if(empty($content)) return $this->renderSuccess([], '内容为空');
        // 实例化微信
        $weixinBase = new WxUser('*************', '*******************');
        // 获取accessToken
        $accessToken = $weixinBase->getAccessToken();
        // 获取openid
        if(!$userData = $weixinBase->jscode2session($code)){
            return $this->renderError($weixinBase->getError());
        }
        // 检测文本内容安全
        $res = $weixinBase->post('https://api.weixin.qq.com/wxa/msg_sec_check?access_token='.$accessToken, helper::jsonEncode([
            'content' => $content,
            'version' => 2,
            'scene' => 2, // 场景枚举值(1 资料;2 评论;3 论坛;4 社交日志)
            'openid' => $userData['openid']
        ]));
        $resData = helper::jsonDecode($res);
        if($resData['errcode'] != 0){
            return $this->renderError($resData['errmsg']);
        }
        if($resData['result']['label'] == 100){
            return $this->renderSuccess([], '检测通过');
        }
        return $this->renderError('内容不合法:请勿包含'.$this->getLabelErrorType($resData['result']['label']).'等内容');
    }

    /**
     * 获取错误信息
     * @param $code
     * @return string
     */
    protected function getLabelErrorType($code){
        $error = [
            '10001' => '广告',
            '20001' => '时政',
            '20002' => '色情',
            '20003' => '辱骂',
            '20006' => '违法犯罪',
            '20008' => '欺诈',
            '20012' => '低俗',
            '20013' => '版权',
            '21000' => '其它'
        ];
        return !empty($error[$code])?$error[$code]:'其它';
    }