短信接口Demo【华信、大鱼】

<?php
namespace think;
/**
 * @description    短信接口
 * @author         LiYI <1041012846@qq.com>
 * @date 2016-11-1     时间
 * @version 1.0.0  版本
 * @copyright
 */
class SmsApi {
   public $user     = '******'; //短信账户    默认liyi
   public $password  = '******'; //账户密码
   public $type     = 'huaxin/dayu';    //发送短信分类   默认华信
   public $time     = 60;     //发送短信间隔   默认120秒
   public $length    = 4;      //验证码位数    默认4位
   public $signature     = '******';   //签名         默认千翼
   private    $ip;               //当前用户ip
    private $file_path  = '';   //  文件保存地址
   /**
    * 构造函数
    * @param string $type       发送短信分类
    * @param string $user       短信账户
    * @param string $password    账户密码
    * @param string $signature       签名    
    * @param string $time       发送短信间隔 默认120秒
    * @param string $length      验证码位数  默认4位
    */
   function __construct($type=null,$user=null,$password=null,$signature=null,$time=null,$length=null){
      //修改默认值
      $this ->type      = $type?$type:$this ->type;
      $this ->user      = $user?$user:$this ->user;
      $this ->password   = $password?$password:$this ->password;
      $this ->signature  = $signature?$signature:$this ->signature;
      $this ->time      = $time?$time:$this ->time;
      $this ->length        = $length?$length:$this ->length;
      $this ->ip           = $_SERVER["REMOTE_ADDR"];
   }

    /**
     * 内部发送方法(不限制次数时间)
     * @param $phone int 手机号
     * @param string $content 短信内容
     * @return array|mixed
     */
    public function inner_send($phone,$content='')
    {
        $phone_regex = '#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#';
        if(!preg_match($phone_regex,$phone))
            return array('status'=>-101,'info' =>'请填写正确手机号');    //验证手机号
        if(!$content){
            return ['status' => -109,'info' => '请填写短信内容'];      //  验证短信内容
        }

        $content = "【".$this ->signature."】".$content;             //拼接签名

        $data = $this ->huaxin($phone,$content);    //  发送短信

        if(!$data['status'])
        {
            trace(['发送失败',$data],'sms');    //  ThinkPHP日志记录错误原因
            return array('status'=>-104,'info' =>'系统繁忙请稍后再试');    //判断发送状态
        }
        //  ThinkPHP记录短信日志
        trace(['mobile' => $phone,'content'=>$content,'time'=>date('Y-m-d H:i:s')],'sms');
        $data=array('status'=>1,'info' =>'信息发送成功');               //返回数据
        return $data;
    }

    /**
     * 执行主方法
     * @param string  $phone  电话号码
     * @param string $content 短信内容
     * @return array|mixed
     */
   public function send ($phone,$content=''){
      /*$phone_regex = '#^1\d{10}$#';
      if(!preg_match($phone_regex,$phone))
         return array('status'=>-101,'info' =>'请填写正确手机号');    //验证手机号*/
      
      if(!$this->checkSms($phone,'','time'))
         return array('status'=>-102,'info' =>'短信已发送!请稍等');    //验证发送时间
      
      if(!$this->checkSms($this ->ip,'','ip'))
         return array('status'=>-103,'info' =>'短信已发送!请稍等');    //验证ip发送时间
      
      if(!$this->checkApp($phone,'','time')){
         return array('status'=>-104,'info' =>'短信已发送!请稍等');    //验证发送时间
      }
      $code=substr(rand(100000,999999),0,$this->length);
      if(!$content){ 
         $content = $this ->getSmsContent($code);
      }
      $content = "【".$this ->signature."】".$content;             //拼接签名

      switch(strtolower($this ->type)){                          //发送短信
         case 'huaxin': $data = $this ->huaxin($phone,$content);break;  //华信
         case 'dayu': $data = $this ->dayu($phone,$code);break;    //大鱼
         default:$data = $this ->huaxin($phone,$content);break;       //默认华信
      }
      if(!$data['status'])
        {
            trace(['验证码发送失败',$data],'sms');    //  ThinkPHP日志记录错误原因
            return array('status'=>-104,'info' =>'系统繁忙请稍后再试');    //判断发送状态
        }

      
      //太慢
      //$this ->writeSmsLog($phone,$content);                         //写入日志
      
      if(!empty($code)){
         Session::set('code_quyum_'.$phone,$code);                 //添加验证码
         $this ->writeSmsApp($phone,$code);                      //app写入日志
      }else{
         $this ->writeSmsApp($phone);                              //app写入日志
      }
      trace(['验证码发送成功','mobile' => $phone,'content'=>$content,'time'=>date('Y-m-d H:i:s')],'sms');  //  ThinkPHP记录短信日志
      Session::set('time_quyum_'.$phone,time());                   //添加手机号时间
      Session::set('time_quyum_'.$this ->ip,time());                //添加ip时间
      $data=array('status'=>1,'info' =>'信息发送成功');               //返回数据
      return $data;
   }
   /**
    * 获取发送短信内容
    * @param unknown $code  验证码 
    * @return string 短信信息
    */
   private function getSmsContent($code){
      $content="您于".date('Y-m-d').",申请的验证码".$code;
      $content=$content.',请勿泄漏他人!';
      return $content;
   }
   
   /** 华信短信   我们合作
    * @param $phone 电话号码
    * @return mixed 发信息
    */
   public  function huaxin($phone,$content){
      $smsapi = "*********************";//地址
      $pass = md5($this ->password);
      $sendurl = $smsapi.'?action=send&userid=&account='.$this ->user.'&password='.$pass.'&mobile='.$phone.'&content='."【".$this->signature."】".$content.'&sendTime=&extno=';
      $sendurl=urldecode($sendurl);
      $result =file_get_contents($sendurl);
      //$result = '{"returnstatus":"Success","message":"操作成功","remainpoint":"21396","taskID":"1611013435567687","successCounts":"1"}';
      $result = json_decode($result);
      $data=array(
         'status'=>$result->successCounts,  //短信回馈接口码 0  失败  1成功
         'info'=>$result->message         //短信回馈文字描述
      );
      return $data;                    //返回信息
   }
   
   private function dayu($phone,$code){
      include_once 'aliyun-dysms-php-sdk/api_demo/SmsDemo.php';
      set_time_limit(0);
        header('Content-Type: text/plain; charset=utf-8');
        $phone = input('phone');
        $A_Sms= new \SmsDemo();
        $A_Sms::sendSms($phone,$code);
      // $iClientProfile = DefaultProfile::getProfile("cn-hangzhou", "LTAIeXQCLd55WIn5", "OK2teWPcO0AC86HnNCGFx2FtjvqQ7e");
      // $client = new DefaultAcsClient($iClientProfile);
      // $request = new Sms\SingleSendSmsRequest();
      // $request->setSignName("李族格");/*签名名称*/
      // $request->setTemplateCode("SMS_127095104");/*模板code*/
      // $request->setRecNum("$phone");/*目标手机号*/
      // $request->setParamString("{\"code\":\"{$code}\",\"product\":\"李族格\"}");/*模板变量,数字一定要转换为字符串*/
      // try {
      //     $response = $client->getAcsResponse($request);
      //     //print_r($response);
      // } 
      // catch (ClientException  $e) {
      //     //print_r($e->getErrorCode());
      //     //print_r($e->getErrorMessage());
      // }
      // catch (ServerException  $e) {
      //     //print_r($e->getErrorCode());
      //     //print_r($e->getErrorMessage());
      // }
      $data=array(
            'status'=>1,   //短信回馈接口码 0  失败  1成功
            'info'=>'发送成功'       //短信回馈文字描述
      );
      return $data;                    //返回信息
   }
   

   
   /**
    * 手机验证检测
    * @param string $type        验证规则 默认验证码 code 验证码 time 验证时间 ip 验证ip
    * @param string $phone       手机号/ip
    * @param string $code    验证码
    * @return boolean
    */
   Public function checkSms($phone,$code,$type){
      switch ($type){
         case 'code' ://验证码验证
            $data = true;
            $scode = Session::get('code_quyum_'.$phone);
            if($code != $scode)$data = false;break;
         case 'time' ://短信时间验证
            $data = true;
            $time = Session::get('time_quyum_'.$phone)+$this->time;
            if(time()< $time)$data = false;break;
         case 'ip' ://验证ip发送时间
            $data = true;
            $time = Session::get('time_quyum_'.$phone)+$this->time;
            if(time()< $time)$data = false;break;
         default:   //默认短信验证
            $data = true;
            $scode = Session::get('code_quyum_'.$phone);
            if($code != $scode)$data = false;break;
      }
      return $data;
   }
   /**
    * 删除短信验证码
    * @param string $phone       手机号
    * @param string $type        删除条件
    * @return boolean
    */
   Public function deleteSendSms($phone,$type){
      switch ($type){
         case 'code' ://验证码验证
            Session::delete('code_quyum_'.$phone);
            Session::delete('time_quyum_'.$phone);
            Session::delete('time_quyum_'.$this->ip);break;
         default:   //默认短信验证
            Session::delete('code_quyum_'.$phone);
            Session::delete('time_quyum_'.$phone);
            Session::delete('time_quyum_'.$this->ip);break;
      }
      return true;
   }

    /**
     * 删除短信验证
     * @param string $phone
     * @return bool
     */
   public function deleteSendSmsApp($phone){
      header("Content-type: text/html; charset=utf-8");
      $file  = $this->getSmsAppLogPath($phone);        //日志名
      //检测文件是否存在
      if(!file_exists($file)){
         return true;
      }
      unlink($file);
   }
   /**
    * 获取ip 并且转换城市
    * @return array 
    */
   private  function GetIpLookup(){
      $ip_json=@file_get_contents($api="http://ip.taobao.com/service/getIpInfo.php?ip=".$this ->ip);
      return json_decode($ip_json);
   }
   /**
    * App存短短信
    */
   private function writeSmsApp($phone,$code=''){
      header("Content-type: text/html; charset=utf-8");
      $file  = $this->getSmsAppLogPath($phone);        //日志名
      //日志内容
      $data['time_quyum_'.$phone] = time();
      $data['time_quyum_'.$this ->ip] = time();
      $data['code_quyum_'.$phone] = $code;
      $log = json_encode($data);
      file_put_contents($file,$log);
   }
   /**
    * 获取文件内容
    */
   private function getSms($phone){
      header("Content-type: text/html; charset=utf-8");
      $file  = $this->getSmsAppLogPath($phone);        //日志名
      return file_get_contents($file);
   }
   /**
    * 手机验证检测
    * @param string $type        验证规则 默认验证码 code 验证码 time 验证时间 ip 验证ip
    * @param string $phone       手机号/ip
    * @param string $code    验证码
    * @return boolean
    */
   Public function checkApp($phone,$code,$type){
      //检测文件是否存在
      if(!file_exists($this->getSmsAppLogPath($phone))){
         return true;
      }
      //存在打开
      $sms = json_decode($this ->getSms($phone));
      switch ($type){
         case 'code' ://验证码验证
            $data = true;
            $name = 'code_quyum_'.$phone;
            $scode = $sms ->$name;
            if($code != $scode)$data = false;break;
         case 'time' ://短信时间验证
            $data = true;
            $name = 'time_quyum_'.$phone;
            $time = $sms ->$name+$this->time;
            if(time()< $time)$data = false;break;
         case 'ip' ://验证ip发送时间
            $data = true;
            $name = 'time_quyum_'.$phone;
            $time = $sms ->$name+$this->time;
            if(time()< $time)$data = false;break;
         default:   //默认短信验证
            $data = true;
            $name = 'code_quyum_'.$phone;
            $scode = $sms ->$name;
            if($code != $scode)$data = false;break;
      }
      return $data;
   }
   /**
    * 手机验证检测
    * @param string $phone       手机号/ip
    * @param string $code    验证码
    * @return boolean
    */
   Public function checkAppCode($phone,$code){
       echo '1231';exit;
      //检测文件是否存在
      if(!file_exists($this->getSmsAppLogPath($phone))){
         return false;
      }
      //存在打开
      $sms = json_decode($this ->getSms($phone));
      $data = true;
      $name = 'code_quyum_' . $phone;
      $scode = $sms->$name;
      if ($code != $scode)
         return false;
      //  验证成功删除验证码
      $this->deleteSendSms($phone,'code');
      $this->deleteSendSmsApp($phone);
      return $data;
   }
   /**
    * 写文件日志
    * @param string $phone       手机号    
    * @param string $content  短信内容
    */
   private function writeSmsLog($phone,$content){
      header("Content-type: text/html; charset=utf-8");
      $json = $this ->GetIpLookup($this ->ip);
      $country= $json ->data->country    ?$json ->data->country :'';   //国家
      $region    = $json ->data->region ?$json ->data->region  :'';   //省份
      $city  = $json ->data->city   ?$json ->data->city       :'';   //城市
      //$file  = 'smslog/'.date('Y-m-d',time()).'_smsLog.log';         //日志名
      $file  = date('Y-m-d',time()).'_smsLog.log';         //日志名
      //日志内容
      $log ='时间-'.date('Y-m-d H:i:s',time()).' 电话-'.$phone.' 地区-'.$country.$region.$city.' IP-'.$this ->ip.' 短信内容-'.$content."\r\n";
      file_put_contents($file,$log,FILE_APPEND);
   }

   private function getSmsAppLogPath($phone)
    {
        return LOG_PATH . $phone.'_smsApp.log';
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值