lizhen_gitee 8 ماه پیش
والد
کامیت
6dd232fa3a

+ 170 - 0
application/common/library/Alisms.php

@@ -0,0 +1,170 @@
+<?php
+
+namespace app\common\library;
+
+/**
+ * 阿里大于SMS短信发送
+ */
+class Alisms
+{
+    private $_params = [];
+    public $error = '';
+    protected $config = [];
+    protected static $instance;
+
+    public function __construct($options = [])
+    {
+        if ($config = config('alisms')) {
+            $this->config = array_merge($this->config, $config);
+        }
+        $this->config = array_merge($this->config, is_array($options) ? $options : []);
+    }
+
+    /**
+     * 单例
+     * @param array $options 参数
+     * @return Alisms
+     */
+    public static function instance($options = [])
+    {
+        if (is_null(self::$instance)) {
+            self::$instance = new static($options);
+        }
+
+        return self::$instance;
+    }
+
+    /**
+     * 设置签名
+     * @param string $sign
+     * @return Alisms
+     */
+    public function sign($sign = '')
+    {
+        $this->_params['SignName'] = $sign;
+        return $this;
+    }
+
+    /**
+     * 设置参数
+     * @param array $param
+     * @return Alisms
+     */
+    public function param(array $param = [])
+    {
+        foreach ($param as $k => &$v) {
+            $v = (string)$v;
+        }
+        unset($v);
+        $param = array_filter($param);
+        $this->_params['TemplateParam'] = $param ? json_encode($param) : '{}';
+        return $this;
+    }
+
+    /**
+     * 设置模板
+     * @param string $code 短信模板
+     * @return Alisms
+     */
+    public function template($code = '')
+    {
+        $this->_params['TemplateCode'] = $code;
+        return $this;
+    }
+
+    /**
+     * 接收手机
+     * @param string $mobile 手机号码
+     * @return Alisms
+     */
+    public function mobile($mobile = '')
+    {
+        $this->_params['PhoneNumbers'] = $mobile;
+        return $this;
+    }
+
+    /**
+     * 立即发送
+     * @return boolean
+     */
+    public function send()
+    {
+        $this->error = '';
+        $params = $this->_params();
+        $params['Signature'] = $this->_signed($params);
+        $response = $this->_curl($params);
+        if ($response !== false) {
+            $res = (array)json_decode($response, true);
+            if (isset($res['Code']) && $res['Code'] == 'OK') {
+                return true;
+            }
+            $this->error = isset($res['Message']) ? $res['Message'] : 'InvalidResult';
+        } else {
+            $this->error = 'InvalidResult';
+        }
+        return false;
+    }
+
+    /**
+     * 获取错误信息
+     * @return string
+     */
+    public function getError()
+    {
+        return $this->error;
+    }
+
+    private function _params()
+    {
+        return array_merge([
+            'AccessKeyId'      => $this->config['key'],
+            'SignName'         => isset($this->config['sign']) ? $this->config['sign'] : '',
+            'Action'           => 'SendSms',
+            'Format'           => 'JSON',
+            'Version'          => '2017-05-25',
+            'SignatureVersion' => '1.0',
+            'SignatureMethod'  => 'HMAC-SHA1',
+            'SignatureNonce'   => uniqid(),
+            'Timestamp'        => gmdate('Y-m-d\TH:i:s\Z'),
+        ], $this->_params);
+    }
+
+    private function percentEncode($string)
+    {
+        $string = urlencode($string);
+        $string = preg_replace('/\+/', '%20', $string);
+        $string = preg_replace('/\*/', '%2A', $string);
+        $string = preg_replace('/%7E/', '~', $string);
+        return $string;
+    }
+
+    private function _signed($params)
+    {
+        $sign = $this->config['secret'];
+        ksort($params);
+        $canonicalizedQueryString = '';
+        foreach ($params as $key => $value) {
+            $canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value);
+        }
+        $stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
+        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $sign . '&', true));
+        return $signature;
+    }
+
+    private function _curl($params)
+    {
+        $uri = 'http://dysmsapi.aliyuncs.com/?' . http_build_query($params);
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+        curl_setopt($ch, CURLOPT_URL, $uri);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
+        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36");
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+        $reponse = curl_exec($ch);
+        curl_close($ch);
+        return $reponse;
+    }
+}

+ 81 - 0
application/common/library/Keyworld.php

@@ -0,0 +1,81 @@
+<?php
+
+namespace app\common\library;
+
+use think\Hook;
+use think\Config;
+/**
+ * 关键词检索类
+ */
+class Keyworld
+{
+
+    /**
+     * @todo 敏感词过滤,返回结果
+     * @param array $list  定义敏感词一维数组
+     * @param string $string 要过滤的内容
+     * @return string $log 处理结果
+     */
+    public static function sensitive_old($string){
+        $count = 0; //违规词的个数
+        $sensitiveWord = '';  //违规词
+        $stringAfter = $string;  //替换后的内容
+        $list = config('keyworld');  //定义敏感词数组
+
+        $pattern = "/".implode("|",$list)."/i"; //定义正则表达式
+        if(preg_match_all($pattern, $string, $matches)){ //匹配到了结果
+            $patternList = $matches[0];  //匹配到的数组
+            $count = count($patternList);
+            //$sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
+
+            //$replaceArray = array_combine($patternList,array_fill(0,count($patternList),'*')); //把匹配到的数组进行合并,替换使用
+            $replace_arr = [1=>'*',2=>'**',3=>'***',4=>'****',5=>'*****','more'=>'*****...',];
+            $replaceArray = [];
+            foreach($patternList as $key => $val){
+                $replaceArray[$val] = isset($replace_arr[mb_strlen($val)]) ? $replace_arr[mb_strlen($val)] : $replace_arr['more'];
+            }
+            $stringAfter = strtr($string, $replaceArray); //结果替换
+        }
+
+        /*$rs = [];
+        $rs['string'] = $string;
+        $rs['count'] = $count;
+        $rs['keyworld'] = $patternList;
+        $rs['newstring'] = $stringAfter;*/
+
+        return $stringAfter;
+    }
+
+    public static function sensitive($string){
+        if(empty($string)){
+            return $string;
+        }
+
+        $list = config('keyworld');  //定义敏感词数组
+        $replaceArray = [];          //含有的违禁词集合
+
+        foreach($list as $key => $word){
+            if(empty($word)){
+                continue;
+            }
+            $start = strpos($string,$word);
+            if($start !== false){
+                $replaceArray[$word] = '*';
+            }
+        }
+
+        $stringAfter = strtr($string, $replaceArray); //结果替换
+        return $stringAfter;
+    }
+
+    public static function checkAction($data,$fields){
+        //$string = 'likeyou小白喜欢小黑爱着的大黄'; //要过滤的内容
+        foreach($data as $key => $string){
+            if(in_array($key,$fields)){
+                $data[$key] = self::sensitive($string);
+            }
+        }
+
+        return $data;
+    }
+}

+ 195 - 0
application/common/library/Tenim.php

@@ -0,0 +1,195 @@
+<?php
+
+namespace app\common\library;
+
+use getusersig\getusersig;
+use tencentim\tencentim;
+
+class Tenim
+{
+
+    /**
+     * 发送消息给某人-接口调用
+     */
+    public function sendToUser() {
+        $from_user = '2';// 发送者
+        $to_user = '294';// 接收者
+        $message = 'hello许犇';// 接收者
+        if(!$from_user || !$to_user || !$message) $this->error("参数缺失!");
+        $this->sendMessageToUser($from_user,$to_user,$message);
+    }
+
+
+    /**
+     * 发送消息给某人
+     */
+    //https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=88888888&identifier=admin&usersig=xxx&random=99999999&contenttype=json
+    public function sendMessageToUser($from_user,$to_user,$message) {
+
+        $random = rand(10000000,99999999);
+        $usersig = $this->usersig("administrator");
+        // 获取配置信息
+        $config = config("tencent_im");
+        $url = "https://console.tim.qq.com/v4/openim/sendmsg";
+        $url .= "?sdkappid=".$config["sdkappid"];
+        $url .= "&identifier=administrator";
+        $url .= "&usersig=".$usersig;
+        $url .= "&random=".$random;
+        $url .= "&contenttype=json";
+        $tencentObj = new tencentim($url);
+
+        $data = [];
+        $data["SyncOtherMachine"] = 1;
+        $data["From_Account"] = (string)$from_user;
+        $data["To_Account"] = (string)$to_user;
+        $data["MsgRandom"] = rand(1000000,9999999);
+        $data["MsgTimeStamp"] = time();
+
+        $data["MsgBody"][] = [
+            "MsgType" => "TIMTextElem",
+            "MsgContent" => [
+                "Text"=> $message
+            ],
+        ];
+        $res = $tencentObj->toSend($data);
+
+        if (empty($res['ActionStatus']) || $res['ActionStatus'] != 'OK') {
+            $error = !empty($res['ErrorInfo']) ? 'im error:'.$res['ErrorInfo'] : 'im error';
+            return $error;
+        }
+
+        return true;
+
+    }
+
+    /**
+     * 发送自定义消息给某人
+     */
+    public function sendCustomMessageToUser($from_user,$to_user,$message) {
+
+        $random = rand(10000000,99999999);
+        $usersig = $this->usersig("administrator");
+        // 获取配置信息
+        $config = config("tencent_im");
+        $url = "https://console.tim.qq.com/v4/openim/sendmsg";
+        $url .= "?sdkappid=".$config["sdkappid"];
+        $url .= "&identifier=administrator";
+        $url .= "&usersig=".$usersig;
+        $url .= "&random=".$random;
+        $url .= "&contenttype=json";
+        $tencentObj = new tencentim($url);
+
+        $data = [];
+        $data["SyncOtherMachine"] = 1;//1=消息同步至发送方,2=消息不同步至发送方
+        $data["From_Account"] = (string)$from_user;
+        $data["To_Account"] = (string)$to_user;
+        $data["MsgRandom"] = rand(1000000,9999999);
+        $data["MsgTimeStamp"] = time();
+
+        $data["MsgBody"][] = [
+            "MsgType" => "TIMCustomElem",
+            "MsgContent" => [
+                "Data" => json_encode($message),
+                "Desc" => $message['name'],
+                "Ext"  => $message['name'],
+                "Sound"=> '',
+            ],
+        ];
+        $data['CloudCustomData'] = $message['id'];
+        $res = $tencentObj->toSend($data);
+
+        if (empty($res['ActionStatus']) || $res['ActionStatus'] != 'OK') {
+            $error = !empty($res['ErrorInfo']) ? 'im error:'.$res['ErrorInfo'] : 'im error';
+            return $error;
+        }
+
+        return true;
+
+    }
+
+    //注册用户到im
+    public function register($userid,$nickname,$avatar) {
+
+        $random = rand(10000000,99999999);
+        $usersig = $this->usersig("administrator");
+        //dump($usersig);
+        // 获取配置信息
+        $config = config("tencent_im");
+        $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import";
+        $url .= "?sdkappid=".$config["sdkappid"];
+        $url .= "&identifier=administrator";
+        $url .= "&usersig=".$usersig;
+        $url .= "&random=".$random;
+        $url .= "&contenttype=json";
+        $tencentObj = new tencentim($url);
+
+        $data = [
+            'UserID' => $userid,
+            'Nick'  => $nickname,
+            'FaceUrl' => $avatar,
+        ];
+
+        $res = $tencentObj->toSend($data);
+
+        if (empty($res['ActionStatus']) || $res['ActionStatus'] != 'OK') {
+            $error = !empty($res['ErrorInfo']) ? 'im error:'.$res['ErrorInfo'] : 'im error';
+            return $error;
+        }
+
+        return true;
+    }
+
+    //某个用户是否im在线
+    //https://cloud.tencent.com/document/product/269/2566
+    /*  QueryResult.Status
+    返回的用户状态,目前支持的状态有:
+    前台运行状态(Online):客户端登录后和即时通信 IM 后台有长连接
+    后台运行状态(PushOnline):iOS 和 Android 进程被 kill 或因网络问题掉线,进入 PushOnline 状态,此时仍然可以接收消息的离线推送。客户端切到后台,但是进程未被手机操作系统 kill 掉时,此时状态仍是 Online
+    未登录状态(Offline):客户端主动退出登录或者客户端自上一次登录起7天之内未登录过
+    如果用户是多终端登录,则只要有一个终端的状态是 Online ,该字段值就是 Online
+    */
+    public function is_online($userid){
+        $random = rand(10000000,99999999);
+        $usersig = $this->usersig("administrator");
+        //dump($usersig);
+        // 获取配置信息
+        $config = config("tencent_im");
+        $url = "https://console.tim.qq.com/v4/openim/query_online_status";
+        $url .= "?sdkappid=".$config["sdkappid"];
+        $url .= "&identifier=administrator";
+        $url .= "&usersig=".$usersig;
+        $url .= "&random=".$random;
+        $url .= "&contenttype=json";
+        $tencentObj = new tencentim($url);
+
+        $data = [
+            'To_Account' => [$userid],
+        ];
+
+        $res = $tencentObj->toSend($data);
+
+        if (!empty($res['ActionStatus']) && $res['ActionStatus'] == 'OK') {
+            if(    isset($res['QueryResult'][0]['To_Account'])
+                && isset($res['QueryResult'][0]['Status'])
+                && $res['QueryResult'][0]['To_Account'] == $userid
+                && $res['QueryResult'][0]['Status'] == 'Online'){
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+
+
+    /**
+     * 获取usersig签名-具体操作
+     */
+    public function usersig($user_id) {
+        // 获取配置信息
+        $config = config("tencent_im");
+        $usersigObj = new getusersig($config["sdkappid"],$config["key"]);
+        $usersig = $usersigObj->genUserSig($user_id);
+        return $usersig;
+    }
+}

+ 171 - 0
application/common/library/Wechat.php

@@ -0,0 +1,171 @@
+<?php
+
+namespace app\common\library;
+
+use fast\Http;
+use think\Cache;
+use think\Session;
+
+/**
+ * 微信授权
+ *
+ */
+class Wechat
+{
+    private $app_id = '';
+    private $app_secret = '';
+
+    private $scope = 'snsapi_userinfo';
+
+    public function __construct()
+    {
+        $wxConfig = config('wechat_app_login');
+        $this->app_id = $wxConfig['appid'];
+        $this->app_secret = $wxConfig['secret'];
+    }
+
+    /**
+     * 获取微信授权链接
+     *
+     * @return string
+     */
+    /*public function getAuthorizeUrl()
+    {
+        $redirect_uri = addon_url('epay/api/wechat', [], true, true);
+        $redirect_uri = urlencode($redirect_uri);
+        $state = \fast\Random::alnum();
+        Session::set('state', $state);
+        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope={$this->scope}&state={$state}#wechat_redirect";
+    }*/
+
+    /**
+     * 获取微信openid
+     *
+     * @return mixed|string
+     */
+
+    /*
+     array(5) {
+                  ["access_token"] => string(89) "49_r4I-StVANS8uYWTUHG86GJ-g1iH6mMFWy-9LeOta--2l6Bzg8LVDQFu8VSARu87atETzVJFZ-fndy-aQqEb8wQ"
+                  ["expires_in"] => int(7200)
+                  ["refresh_token"] => string(89) "49_8Vfa-imGcRmUwcESvpvMcEkiuh8kmD_movl9bIz9DV5GonZrqfIya5NgT7G-NMeJ7KTuCjMrSJi4BtojjDxnCQ"
+                  ["openid"] => string(28) "o8lxjwRjlDortQKhTk1dpHjQxcBU"
+                  ["scope"] => string(15) "snsapi_userinfo"
+            }
+     * */
+
+    public function getOpenid($code = '')
+    {
+        $openid = Session::get('openid');
+        if (!$openid) {
+
+            $token = $this->getAccessToken($code);
+            $openid = isset($token['openid']) ? $token['openid'] : '';
+            if ($openid) {
+                Session::set("openid", $openid);
+            }
+        }
+        return $openid;
+    }
+
+    /*
+    array(2) {
+              ["ret"] => bool(true)
+              ["msg"] => string(307) "{"openid":"o8lxjwRjlDortQKhTk1dpHjQxcBU","nickname":"科","sex":1,"language":"zh_CN","city":"临沂","province":"山东","country":"中国","headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/LGYWIv4F5vxZ2zCM9GEUynoQeJ6ibX9IfoKPAWLlGIugn1mgaAMPuqxzPBDQ3ktLEv2ia7HmOeJYTg5LofG8YlwQ\/132","privilege":[]}"
+            }
+     */
+    public function getwxuserinfo($code = '')
+    {
+        $wxuserinfo = Session::get('wxuserinfo');
+        if (!$wxuserinfo) {
+
+            $token = $this->getAccessToken($code);
+
+            $openid = isset($token['openid']) ? $token['openid'] : '';
+
+            $access_token = isset($token['access_token']) ? $token['access_token'] : '';
+
+            $ret = Http::sendRequest('https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN');
+            if ($ret['ret']) {
+                $wxuserinfo = json_decode($ret['msg'], true);
+                Session::set('wxuserinfo', $wxuserinfo);
+            }else{
+                $wxuserinfo = [];
+            }
+
+        }
+        return $wxuserinfo;
+    }
+
+
+    /**
+     * 获取授权token网页授权
+     *
+     * @param string $code
+     * @return mixed|string
+     */
+    public function getAccessToken($code = '')
+    {
+        $params = [
+            'appid'      => $this->app_id,
+            'secret'     => $this->app_secret,
+            'code'       => $code,
+            'grant_type' => 'authorization_code'
+        ];
+        $ret = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET');
+        if ($ret['ret']) {
+            $ar = json_decode($ret['msg'], true);
+            return $ar;
+        }
+        return [];
+    }
+
+   /* public function getPublicAccessToken(){
+        $ret = Http::sendRequest('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->app_id.'&secret='.$this->app_secret);
+
+        if ($ret['ret']) {
+            $ar = json_decode($ret['msg'], true);
+
+            return $ar['access_token'];
+        }
+    }*/
+
+    //{"errcode":0,"errmsg":"ok","msgid":2054095443608862720}
+    /*public function send($ac,$openid,$first,$keyword1,$keyword2,$keyword3,$remark,$color){
+
+        $params = [
+            "touser"     => $openid,
+            "template_id"       => "lEUyDmLgwIaFDi9SNlIosXe-4fD43SiqSOZigIPOfJ8",
+            'url' => 'https://yanglaoweb.lanmaonet.com',
+            "data" => [
+                "first" => ["value"=>$first,"color"=>$color],
+                "keyword1" => ["value"=>$keyword1,"color"=>"#173177"],
+                "keyword2" => ["value"=>$keyword2,"color"=>"#173177"],
+                "keyword3" => ["value"=>$keyword3,"color"=>"#173177"],
+                "remark" => ["value"=>$remark,"color"=>$color],
+            ],
+            'miniprogram' => [],
+        ];
+
+        $rest = curl_post('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$ac,json_encode($params));
+
+    }*/
+
+    /*public function getJsticket($code = '')
+    {
+        $jsticket = Session::get('jsticket');
+        if (!$jsticket) {
+            $token = $this->getAccessToken($code);
+            $params = [
+                'access_token' => 'token',
+                'type'         => 'jsapi',
+            ];
+            $ret = Http::sendRequest('https://api.weixin.qq.com/cgi-bin/ticket/getticket', $params, 'GET');
+            if ($ret['ret']) {
+                $ar = json_decode($ret['msg'], true);
+                return $ar;
+            }
+        }
+        return $jsticket;
+    }*/
+}