PHPCMS短信接口替换

来源:互联网 发布:北京房价数据app 编辑:程序博客网 时间:2024/06/05 21:01

PHPCMS V9采用PHP5+MYSQL做为技术基础进行开发。V9采用OOP(面向对象)方式进行基础运行框架搭建。模块化开发方式做为功能开发形式。框架易于功能扩展,代码维护,优秀的二次开发能力,可满足所有网站的应用需求。今天我就来带大家来做一次替换短信接口的工作。

短信接口使用的是短信宝短信平台的短信接口,小伙伴一定会问为什么使用短信宝作为案例呢?原因很简单,因为短信宝的平台极其稳定,而且短信发送速度相当快捷,验证码和订单通知在3~5秒就能收到,用户体验非常好,所以我们公司一直和短信宝保持着合作关系,小伙伴们也可以去短信宝的官网(http://www.smsbao.com)注册一个账号,还有免费的短信条数送呢。

接下来我就来说一下开发步骤:
1. 首先,我们先更换后台的显示界面文件。打开模板文件,替换一下模板文件。打开项目/phpcms/modules/sms/templates/index.tpl.php,替换的代码从12行~86行,代码如下图所示:

<div class="explain-col search-form">短信模块默认使用<a href="http://www.smsbao.com" target="_blank" style="font-weight:bold;color:red;">短信宝</a>接口,还没有短信宝账户,请点击<a href="http://smsbao.com/reg" target="_blank" style="font-weight:bold;color:red;">免费注册</a>,短信宝客服热线:400-716-3021,或联系短信宝<a href="http://wpa.b.qq.com/cgi/wpa.php?ln=1&key=XzkzODA0NjAyMV8yNTU0MzFfNDAwMDA5MDQ2NV8yXw" target="_blank" style="font-weight:bold;color:red;">在线客服</a></br>说明:欲购买1W条以上的短信套餐以及包月套餐用户,请咨询<a href="http://wpa.b.qq.com/cgi/wpa.php?ln=1&key=XzkzODA0NjAyMV8yNTU0MzFfNDAwMDA5MDQ2NV8yXw" target="_blank" style="font-weight:bold;color:red;">在线客服</a></br>备注:短信宝官网(http://www.smsbao.com),短信宝技术交流群:188145230</div></form><div class="btn text-l"><span class="font-fixh green">您当前账户为:<?php echo $this->smsapi->userid?>,短信宝账户剩余短信条数:<?php echo $smsinfo_arr?></span></div><br><br>    <table width="100%" cellspacing="0">        <thead>            <tr>            <th width="5%" align="center"><?php echo L('product_id')?></th>            <th width="20%" align="left"><?php echo L('product_name')?></th>            <th width="30%" align="left"><?php echo L('product_description')?></th>            <th width="10%" align="left"><?php echo L('totalnum')?></th>            <th width="10%" align="left"><?php echo L('give_away')?></th>            <th width="10%" align="left"><?php echo L('product_price').L('yuan')?></th>            <th width="10%" align="left"><?php echo L('buy')?></th>            </tr>        </thead>    <tbody>    <tr>        <td width="10%" align="center">1</td>        <td width="10%" align="left">50条短信</td>        <td width="10%" align="left">50条短信</td>        <td width="10%" align="left">50</td>        <td width="10%" align="left">0</td>        <td width="10%" align="left">5</td>        <td width="10%" align="left"><a href="http://smsbao.com/member/product/list.jhtml" target="_blank">购买</a></td>    </tr>    <tr>        <td width="10%" align="center">2</td>        <td width="10%" align="left">500条短信</td>        <td width="10%" align="left">500条短信</td>        <td width="10%" align="left">500</td>        <td width="10%" align="left">0</td>        <td width="10%" align="left">40</td>        <td width="10%" align="left"><a href="http://smsbao.com/member/product/list.jhtml" target="_blank">购买</a></td>    </tr>    <tr>        <td width="10%" align="center">3</td>        <td width="10%" align="left">2000条短信</td>        <td width="10%" align="left">2000条短信</td>        <td width="10%" align="left">2000</td>        <td width="10%" align="left">0</td>        <td width="10%" align="left">150</td>        <td width="10%" align="left"><a href="http://smsbao.com/member/product/list.jhtml" target="_blank">购买</a></td>    </tr>    <tr>        <td width="10%" align="center">4</td>        <td width="10%" align="left">5000条短信</td>        <td width="10%" align="left">5000条短信</td>        <td width="10%" align="left">5000</td>        <td width="10%" align="left">0</td>        <td width="10%" align="left">375</td>        <td width="10%" align="left"><a href="http://smsbao.com/member/product/list.jhtml" target="_blank">购买</a></td>    </tr>    <tr>        <td width="10%" align="center">5</td>        <td width="10%" align="left">10000条短信</td>        <td width="10%" align="left">10000条短信</td>        <td width="10%" align="left">10000</td>        <td width="10%" align="left">0</td>        <td width="10%" align="left">700</td>        <td width="10%" align="left"><a href="http://smsbao.com/member/product/list.jhtml" target="_blank">购买</a></td>    </tr>    </tbody>    </table>

打开项目/phpcms/modules/sms/templates/sms_sent.tpl.php,替换的代码从35行~53行,代码如下图所示:

<form name="dosubmit" action="?m=sms&c=sms&a=sms_sent" method="post" id="myform"><table width="100%" class="table_form"><tr><td  width="120">发送号码  <font color="#C0C0C0">(每行一个号码)</font></td> <td><textarea name="mobile"></textarea></td></tr><tr></br><td  width="120">发送内容  <font color="#C0C0C0">(短信群发内容)</font></td> <td><textarea name="msg"></textarea></td></tr></table><div class="bk15"></div><input name="dosubmit" type="submit" value="<?php echo L('submit')?>" class="button" id="dosubmit"></form>

打开项目/phpcms/modules/sms/templates/sms_setting.tpl.php,替换的代码从7行~32行,代码如下图所示:

<form name="myform" action="?m=sms&c=sms&a=sms_setting" method="post" id="myform"><table width="100%" class="table_form"><tr><td  width="120"><?php echo L('sms_enable')?></td> <td><input name="setting[sms_enable]" value="1" type="radio" id="sms_enable" <?php if($this->sms_setting[sms_enable] == 1) {?>checked<?php }?>> <?php echo L('open')?>  <input name="setting[sms_enable]" value="0" type="radio" id="sms_enable" <?php if($this->sms_setting[sms_enable] == 0) {?>checked<?php }?>> <?php echo L('close')?></td></tr><tr><td  width="120">短信宝用户名  <font color="#C0C0C0"></font></td> <td><input type="text" name="setting[userid]" size="20" placeholder="填写你在短信宝注册的用户名" value="<?php echo $this->sms_setting[userid]?>" id="userid"></td></tr><tr><td  width="120">短信宝密码 <font color="#C0C0C0"></font></td> <td><label><input type="input" id="sms_key" name="setting[sms_key]" value="<?php echo $this->sms_setting[sms_key]?>" size="50"><input type="hidden" name="pc_hash" value="<?php echo $_GET['pc_hash'];?>" size="50"></label></td></tr><tr><td  width="120">短信签名 <font color="#C0C0C0"></font></td> <td><input type="text" name="setting[productid]" size="20" placeholder="填写你所发送短信的签名" value="<?php echo $this->sms_setting[productid]?>" id="productid"></td></tr></table><div class="bk15"></div><input name="dosubmit" type="submit" value="<?php echo L('submit')?>" class="button" id="dosubmit"></form>

经过替换后,所有的显示都变成短信宝短信平台的了。第一步完成。接下来替换发送短信的业务代码。修改项目/phpcms/modules/sms/functions/global.func.php文件,代码如下:

<?phpfunction sms_status($status = 0,$return_array = 0) {    $array = array(            '0'=>'发送成功',            '30'=>'密码错误',            '40'=>'账号不存在',            '41'=>'余额不足',            '42'=>'帐号过期',            '43'=>'IP地址限制',            '50'=>'内容含有敏感词',            '51'=>'手机号码不正确',            '-1'=>'参数不全'        );    return $return_array ? $array : $array[$status];}function checkmobile($mobilephone) {        $mobilephone = trim($mobilephone);        if(preg_match("/^13[0-9]{1}[0-9]{8}$|15[01236789]{1}[0-9]{8}$|18[01236789]{1}[0-9]{8}$/",$mobilephone)){              return  $mobilephone;        } else {                return false;        }}function get_smsnotice($type = '') {    $url = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';    $urls = base64_decode('aHR0cDovL3Ntcy5waHBpcC5jb20vYXBpLnBocD9vcD1zbXNub3RpY2UmdXJsPQ==').$url."&type=".$type;    $content = pc_file_get_contents($urls,5);    if($content) {        $content = json_decode($content,true);        if($content['status']==1) {            return strtolower(CHARSET)=='gbk' ?iconv('utf-8','gbk',$content['msg']) : $content['msg'];        }    }    $urls = base64_decode('aHR0cDovL3Ntcy5waHBjbXMuY24vYXBpLnBocD9vcD1zbXNub3RpY2UmdXJsPQ==').$url."&type=".$type;    $content = pc_file_get_contents($urls,3);    if($content) {        $content = json_decode($content,true);        if($content['status']==1) {            return strtolower(CHARSET)=='gbk' ?iconv('utf-8','gbk',$content['msg']) : $content['msg'];        }    }    return '<font color="red">短信宝服务器无法访问!您将无法使用短信宝服务!</font>';}function sendsms($mobile, $send_txt, $tplid = 1, $id_code = '', $siteid=1) {    pc_base::load_app_class('smsapi', 'sms', 0); //引入smsapi类    $sms_setting = getcache('sms','sms');    $sms_uid = $sms_setting[$siteid]['userid'];//短信接口用户ID    $sms_pid = $sms_setting[$siteid]['productid'];//产品ID    $sms_passwd = $sms_setting[$siteid]['sms_key'];//32位密码    $smsapi = new smsapi($sms_uid, $sms_pid, $sms_passwd); //初始化接口类    $mobile = explode(',',$mobile);    $code = $smsapi->send_sms($mobile, $send_txt, 0, CHARSET,$id_code,$tplid,1); //发送短信    if($code==0) {        return 0;    } else {        return sms_status($code,1);    }}

修改项目/phpcms/modules/sms/classes/smsapi.class.php文件,代码如下:

<?php /** * 短信平台API接口类 */class smsapi {    public $userid;    public $statuscode;    private $productid, $sms_key, $smsapi_url;    /**     *      * 初始化接口类     * @param int $userid 用户id     * @param int $productid 产品id     * @param string $sms_key 密钥     */    public function __construct($userid = '', $productid = '', $sms_key = '') {        $this->smsapi_url = 'http://api.smsbao.com/sms?';        $this->userid = $userid;        $this->productid = $productid;        $this->sms_key = $sms_key;    }    /**     *      * 获取短信产品列表信息     */    public function get_price() {        $this->param = array('op'=>'sms_get_productlist');        $res = $this->pc_file_get_contents();        return !empty($res) ? json_decode($res, 1) : array();      }    /**     *      * 获取短信产品购买地址     */    public function get_buyurl($productid = 0) {        //return 'http://sms.phpip.com/index.php?m=sms_service&c=center&a=buy&sms_pid='.$this->productid.'&productid='.$productid;        return 'http://smsbao.com/member/product/list.jhtml';    }    public function show_qf_url() {        return $this->smsapi_url.'u='.$this->userid.'&p='.md5($this->sms_key).'&m={mobile}&c=【'.$this->productid.'】{content}';    }    /**     * 获取短信剩余条数和限制短信发送ip     */    public function get_smsinfo() {        $post='u='.$this->userid.'&p='.md5($this->sms_key);        $ret = file_get_contents('http://api.smsbao.com/query?'.$post);        $retArr = split("\n", $ret);        $balanceArr = split(",", $retArr[1]);        $balance = $retArr[0] == 0 ? $balanceArr[1] : $ret;        return $balance;       }       /**     * 获取充值记录     */    public function get_buyhistory() {        $this->param = array('op'=>'sms_get_paylist');        $res = $this->pc_file_get_contents();        return !empty($res) ? json_decode($res, 1) : array();              }    /**     * 获取消费记录     * @param int $page 页码     */    public function get_payhistory($page=1) {        $this->param = array('op'=>'sms_get_report','page'=>$page);        $res = $this->pc_file_get_contents();        return !empty($res) ? json_decode($res, 1) : array();          }    /**     * 获取短信api帮助     */    public function get_sms_help() {        $this->param = array('op'=>'sms_help','page'=>$page);        $res = $this->pc_file_get_contents();        return !empty($res) ? json_decode($res, 1) : array();          }    /**     *      * 批量发送短信     * @param array $mobile 手机号码     * @param string $content 短信内容     * @param datetime $send_time 发送时间     * @param string $charset 短信字符类型 gbk / utf-8     * @param string $id_code 唯一值 、可用于验证码     */    public function send_sms($mobile='', $content='', $send_time='', $charset='gbk',$id_code = '',$tplid = '',$return_code = 0) {        //短信发送状态        $status = $this->_sms_status();        $content = safe_replace($content);        $send_content = $content;        $send_time = strtotime($send_time);        $smsapi_senturl = $this->smsapi_url.'op=sms_service_new';        foreach($mobile as $key=>$val){            $data = array(                    'p' => md5($this->sms_key),                    'u' => $this->userid,                    'charset' => CHARSET,                    'c' => urlencode('【'.$this->productid.'】'.$send_content),                    'm' => $val,                    'send_time' => $send_time,                    'tplid' => $tplid,                );            $post = '';            foreach($data as $k=>$v) {                $post .= $k.'='.$v.'&';            }            $return = $this->_post($smsapi_senturl, 0, $post);            //增加到本地数据库            $sms_report_db = pc_base::load_model('sms_report_model');            $send_userid = param::get_cookie('_userid') ? intval(param::get_cookie('_userid')) : 0;            $ip = ip();            $new_content = $content;            if($return=='0') {                $sms_report_db->insert(array('mobile'=>$val,'posttime'=>SYS_TIME,'id_code'=>$id_code,'send_userid'=>$send_userid,'status'=>$this->statuscode,'msg'=>$new_content,'return_id'=>$return,'ip'=>$ip));            } else {                $sms_report_db->insert(array('mobile'=>$val,'posttime'=>SYS_TIME,'send_userid'=>$send_userid,'status'=>'-2','msg'=>$new_content,'ip'=>$ip));            }            if($this->statuscode==0) {                $barr = explode(':',$arr[1]);                if($barr[0]=='KEY') {                    return '短信已提交,请等待审批!审批时间为:9:00-18:00。 法定假日不审批!如需帮助,请联系phpcms.cn官网!';                }            }            //end        }        //$arr = explode('#',$return);        //$this->statuscode = $arr[0];        //if($return_code) {        //  return $arr[0];        //} else {        //  return isset($status[$arr[0]]) ? $status[$arr[0]] : $arr[0];        //}    }    /**     *      * 获取远程内容     * @param $timeout 超时时间     */    public function pc_file_get_contents($timeout=30) {        $this->setting = array(                            'u'=>$this->userid,                            'p'=>md5($this->sms_key),                              );        $this->param = array_merge($this->param, $this->setting);        $url = $this->smsapi_url.http_build_query($this->param);        $stream = stream_context_create(array('http' => array('timeout' => $timeout)));        return @file_get_contents($url, 0, $stream);    }    /**     *  post数据     *  @param string $url     post的url     *  @param int $limit      返回的数据的长度     *  @param string $post        post数据,字符串形式username='dalarge'&password='123456'     *  @param string $cookie  模拟 cookie,字符串形式username='dalarge'&password='123456'     *  @param string $ip      ip地址     *  @param int $timeout        连接超时时间     *  @param bool $block     是否为阻塞模式     *  @return string          返回字符串     */    private function _post($url, $limit = 0, $post = '', $cookie = '', $ip = '', $timeout = 30, $block = true) {        $return = '';        $matches = parse_url($url);        $host = $matches['host'];        $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';        $port = !empty($matches['port']) ? $matches['port'] : 80;        $siteurl = $this->_get_url();        if($post) {            $out = "POST $path HTTP/1.1\r\n";            $out .= "Accept: */*\r\n";            $out .= "Referer: ".$siteurl."\r\n";            $out .= "Accept-Language: zh-cn\r\n";            $out .= "Content-Type: application/x-www-form-urlencoded\r\n";            $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";            $out .= "Host: $host\r\n" ;            $out .= 'Content-Length: '.strlen($post)."\r\n" ;            $out .= "Connection: Close\r\n" ;            $out .= "Cache-Control: no-cache\r\n" ;            $out .= "Cookie: $cookie\r\n\r\n" ;            $out .= $post ;        } else {            $out = "GET $path HTTP/1.1\r\n";            $out .= "Accept: */*\r\n";            $out .= "Referer: ".$siteurl."\r\n";            $out .= "Accept-Language: zh-cn\r\n";            $out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";            $out .= "Host: $host\r\n";            $out .= "Connection: Close\r\n";            $out .= "Cookie: $cookie\r\n\r\n";        }        $fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);        if(!$fp) return '';        stream_set_blocking($fp, $block);        stream_set_timeout($fp, $timeout);        @fwrite($fp, $out);        $status = stream_get_meta_data($fp);        if($status['timed_out']) return '';            while (!feof($fp)) {            if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n"))  break;                     }        $stop = false;        while(!feof($fp) && !$stop) {            $data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));            $return .= $data;            if($limit) {                $limit -= strlen($data);                $stop = $limit <= 0;            }        }        @fclose($fp);        //部分虚拟主机返回数值有误,暂不确定原因,过滤返回数据格式        $return_arr = explode("\n", $return);        if(isset($return_arr[1])) {            $return = trim($return_arr[1]);        }        unset($return_arr);        return $return;    }    /**     * 获取当前页面完整URL地址     */    private function _get_url() {        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';        $php_self = $_SERVER['PHP_SELF'] ? $this->_safe_replace($_SERVER['PHP_SELF']) : $this->_safe_replace($_SERVER['SCRIPT_NAME']);        $path_info = isset($_SERVER['PATH_INFO']) ? $this->_safe_replace($_SERVER['PATH_INFO']) : '';        $relate_url = isset($_SERVER['REQUEST_URI']) ? $this->_safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$this->_safe_replace($_SERVER['QUERY_STRING']) : $path_info);        return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;    }    /**     * 安全过滤函数     *     * @param $string     * @return string     */    private function _safe_replace($string) {        $string = str_replace('%20','',$string);        $string = str_replace('%27','',$string);        $string = str_replace('%2527','',$string);        $string = str_replace('*','',$string);        $string = str_replace('"','&quot;',$string);        $string = str_replace("'",'',$string);        $string = str_replace('"','',$string);        $string = str_replace(';','',$string);        $string = str_replace('<','&lt;',$string);        $string = str_replace('>','&gt;',$string);        $string = str_replace("{",'',$string);        $string = str_replace('}','',$string);        $string = str_replace('\\','',$string);        return $string;    }    /**     *      * 接口短信状态     */    private function _sms_status() {        pc_base::load_app_func('global','sms');        return sms_status(0,1);    }}?>

修改项目/api/sms.php文件,代码如下:

<?phpdefined('IN_PHPCMS') or exit('No permission resources.');/** * 短信发送接口 */$sms_report_db = pc_base::load_model('sms_report_model');$session_storage = 'session_'.pc_base::load_config('system','session_storage');pc_base::load_sys_class($session_storage);if(empty($_SESSION['code'])) exit('-100');if(empty($_GET['session_code']) || preg_match('/^([a-zA-Z0-9])$/i',$_GET['session_code']) || $_SESSION['code']!=$_GET['session_code']) exit('-101');if(isset($_GET['mobile']) && !empty($_GET['mobile'])) {    $mobile = $_GET['mobile'];} else {    $mobile = $_SESSION['mobile'];}$_SESSION['code'] = '';if(!isset($_SESSION['csms'])) {    $_SESSION['csms'] = 0;} elseif($_SESSION['csms'] > 3) {    exit('-1');}$_SESSION['csms'] += 1;$siteid = get_siteid() ? get_siteid() : 1 ;$sms_setting = getcache('sms','sms');if(!preg_match('/^1[3-9]\d{9}$/',$mobile)) exit('mobile phone error');$posttime = SYS_TIME-86400;$where = "`mobile`='$mobile' AND `posttime`>'$posttime'";$num = $sms_report_db->count($where);if($num > 3) {    exit('-1');//当日发送短信数量超过限制 3 条}//同一IP 24小时允许请求的最大数$allow_max_ip = 10;//正常注册相当于 10 个人$ip = ip();$where = "`ip`='$ip' AND `posttime`>'$posttime'";$num = $sms_report_db->count($where);if($num >= $allow_max_ip) {    exit('-3');//当日单IP 发送短信数量超过 $allow_max_ip}if(intval($sms_setting[$siteid]['sms_enable']) == 0) exit('-99'); //短信功能关闭$sms_uid = $sms_setting[$siteid]['userid'];//短信接口用户ID$sms_pid = $sms_setting[$siteid]['productid'];//产品ID$sms_passwd = $sms_setting[$siteid]['sms_key'];//32位密码$posttime = SYS_TIME-600;$rs = $sms_report_db->get_one("`mobile`='$mobile' AND `posttime`>'$posttime'");if($rs['id_code']) {    $id_code = $rs['id_code'];} else {    $id_code = random(6);//唯一吗,用于扩展验证}//$send_txt = '尊敬的用户您好,您在'.$sitename.'的注册验证码为:'.$id_code.',验证码有效期为5分钟。';$send_txt = $id_code;$send_userid = intval($_GET['send_userid']);//操作者idpc_base::load_app_class('smsapi', 'sms', 0); //引入smsapi类$smsapi = new smsapi($sms_uid, $sms_pid, $sms_passwd); //初始化接口类//$smsapi->get_price(); //获取短信剩余条数和限制短信发送的ip地址$mobile = explode(',',$mobile);$tplid = 1;$id_code = random(6);//唯一吗,用于扩展验证$send_txt = '尊敬的用户您好,您的注册验证码为:'.$id_code.',验证码有效期为5分钟。'; $content = safe_replace($send_txt);$sent_time = intval($_POST['sendtype']) == 2 && !empty($_POST['sendtime'])  ? trim($_POST['sendtime']) : date('Y-m-d H:i:s',SYS_TIME);$smsapi->send_sms($mobile, $send_txt, $sent_time, CHARSET,$id_code,$tplid); //发送短信echo 0;?>

好了,经过以上的替换,短信宝的短信平台已经替换成功了,可以正常使用了。

报备一下短信宝的VIP模板,这样就可以走短信宝的优质通道了,并且免审核了,短信内容3~5秒就可送达。1

原创粉丝点击