待发短信

在线客服
产品支持 短信宝客服
合作渠道 渠道合作
服务咨询

4001-021-502

工作时间

9:00-21:00

typehoV1.2短信插件开发

typeho是一款内核强健﹑扩展方便﹑体验友好﹑运行流畅的轻量级开源博客程序。仅仅 7 张数据表,加上不足 400KB 的代码,就实现了完整的插件与模板机制。超低的 CPU 和内存使用率,足以发挥主机的最高性能。今天小编为大家讲解一下typehoV1.2这个版本的短信插件该如何开发,短信接口使用的是我们短信宝短信群发平台,我们短信宝短信群发平台极其稳定,而且短信发送速度相当快捷,验证码和订单通知在3~5秒就能收到,用户体验非常好,注册就送测试短信。

插件的目录结构如下:

├─SmsBaoSms插件目录

│  ├─captcha           字体文件目录

│  │  ├─resources   

│  │  │  ├─fonts   

│  │  │  ├─tools    

│  │  │  ├─words    

│  │  ├─ captcha.php  

│  ├─page_regbysms.php           注册界面

│  ├─Plugin.php           插件类

│  ├─register.php           登录界面

│  ├─sendsms.php           短信发送类

下面具体给大家说一下每个文件的作用及代码 Plugin.php是插件的安装文件,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php
/**
 * Typecho版本手机注册插件
 * @package SmsBaoSms For Typecho
 * @author 短信宝
 * @version 1.0.1
 */
class SmsBaoSms_Plugin implements Typecho_Plugin_Interface
{
    // 激活插件
    public static function activate(){
        return _t('插件已经激活,需先配置信息!');
    }
 
 
    // 禁用插件
    public static function deactivate(){
        //恢复原注册页面
        if(copy(dirname(__FILE__).'/register.php',dirname(__FILE__).'/../../../'.substr(__TYPECHO_ADMIN_DIR__,1,count(__TYPECHO_ADMIN_DIR__)-2).'/register.php')){
        }
        return _t('插件已被禁用');
    }
 
 
    // 插件配置面板
    public static function config(Typecho_Widget_Helper_Form $form){
        //表单验证
        $alidayukey = new Typecho_Widget_Helper_Form_Element_Text('alidayukey'null'', _t('短信宝账号:'));
        $form->addInput($alidayukey->addRule('required', _t('短信宝账号不能为空!')));
 
 
        $alidayusecret = new Typecho_Widget_Helper_Form_Element_Text('alidayusecret'null'', _t('短信宝密码:'));
        $form->addInput($alidayusecret->addRule('required', _t('短信宝密码不能为空!')));
 
 
        $signname = new Typecho_Widget_Helper_Form_Element_Text('signname'null'', _t('短信宝签名:'));
        $form->addInput($signname->addRule('required', _t('签名名称不能为空!')));
 
 
        $templatecode = new Typecho_Widget_Helper_Form_Element_Text('templatecode'null'', _t('短信宝模版CODE:'));
        $form->addInput($templatecode->addRule('required', _t('模版CODE不能为空!')));
 
 
        $isindex = new Typecho_Widget_Helper_Form_Element_Radio('isindex', array(
            'y'=>_t('存在'),
            'n'=>_t('不存在')
        ), 'y', _t('存在index.php'), _t("前台文章url是否存在index.php:"));
        $form->addInput($isindex->addRule('enum', _t(''), array('y''n')));
 
 
        $alidayukey = @isset($_POST['alidayukey']) ? addslashes(trim($_POST['alidayukey'])) : '';
        $isindex = @isset($_POST['isindex']) ? addslashes(trim($_POST['isindex'])) : '';
        if($alidayukey!=''){
            //$option = self::getConfig();
            $db = Typecho_Db::get();
            //判断目录权限
            $queryTheme= $db->select('value')->from('table.options')->where('name = ?''theme'); 
            $rowTheme = $db->fetchRow($queryTheme);
            if(!is_writable(dirname(__FILE__).'/../../themes/'.$rowTheme['value'])){
                Typecho_Widget::widget('Widget_Notice')->set(_t('主题目录不可写,请更改目录权限。'.__TYPECHO_THEME_DIR__.'/'.$rowTheme['value']), 'success');
            }
            if(!is_writable(dirname(__FILE__).'/../../../'.substr(__TYPECHO_ADMIN_DIR__,1,count(__TYPECHO_ADMIN_DIR__)-2).'/register.php')){
                Typecho_Widget::widget('Widget_Notice')->set(_t('后台目录不可写,请更改目录权限。'.__TYPECHO_ADMIN_DIR__.'register.php'), 'success');
            }
            //如果数据表没有添加注册页面就插入
            $query= $db->select('slug')->from('table.contents')->where('template = ?''page_regbysms.php'); 
            $row = $db->fetchRow($query);
            if(count($row)==0){
                $contents = array(
                    'title'      =>  '注册用户',
                    'slug'      =>  'reg',
                    'created'   =>  Typecho_Date::time(),
                    'text'=>  '<!--markdown-->',
                    'password'  =>  '',
                    'authorId'     =>  Typecho_Cookie::get('__typecho_uid'),
                    'template'     =>  'page_regbysms.php',
                    'type'     =>  'page',
                    'status'     =>  'hidden',
                );
                $insert = $db->insert('table.contents')->rows($contents);
                $insertId = $db->query($insert);
                $slug=$contents['slug'];
            }else{
                $slug=$row['slug'];
            }
            //如果page_regbysms.php不存在就创建
            if(!file_exists(dirname(__FILE__).'/../../themes/'.$rowTheme['value']."/page_regbysms.php")){
                $regfile = fopen(dirname(__FILE__)."/page_regbysms.php""r") or die("不能读取page_regbysms.php文件");
                $regtext=fread($regfile,filesize(dirname(__FILE__)."/page_regbysms.php"));
                fclose($regfile);
                $regpage = fopen(dirname(__FILE__).'/../../themes/'.$rowTheme['value']."/page_regbysms.php""w") or die("不能写入page_regbysms.php文件");
                fwrite($regpage, $regtext);
                fclose($regpage);
            }
            //将跳转新注册页面的链接写入原register.php
            $querySiteUrl= $db->select('value')->from('table.options')->where('name = ?''siteUrl'); 
            $rowSiteUrl = $db->fetchRow($querySiteUrl);
            if($isindex=='y'){
                $siteUrl=$rowSiteUrl['value'].'/index.php/'.$slug.'.html';
            }else{
                $siteUrl=$rowSiteUrl['value'].'/'.$slug.'.html';
            }
            $registerphp='
                <?php
                include "common.php";
                if ($user->hasLogin() || !$options->allowRegister) {
                    $response->redirect($options->siteUrl);
                }else{
                    header("Location: '.$siteUrl.'");
                }
                ?>
            ';
            $regphp = fopen(dirname(__FILE__).'/../../../'.substr(__TYPECHO_ADMIN_DIR__,1,count(__TYPECHO_ADMIN_DIR__)-2).'/register.php'"w") or die("不能写入register.php文件");
            fwrite($regphp, $registerphp);
            fclose($regphp);
        }
    }
 
 
    // 个人用户配置面板
    public static function personalConfig(Typecho_Widget_Helper_Form $form){}
 
 
    // 获得插件配置信息
    public static function getConfig(){
        return Typecho_Widget::widget('Widget_Options')->plugin('SmsBaoSms');
    }
}

2:page_regbysms.php为注册界面 代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
<?php
/**
 * 手机注册页面
 *
 * @package custom
 */
?>
<?php session_start();if (!defined('__TYPECHO_ROOT_DIR__')) exit; ?>
<?php
$db = Typecho_Db::get();
$action = isset($_POST['action']) ? addslashes(trim($_POST['action'])) : '';
/** 如果已经登录 */
if ($this->user->hasLogin()) {
    /** 直接返回 */
    $this->response->redirect($this->options->index);
}
 
if($action=='regbysms'){
    $name = isset($_POST['name']) ? addslashes(trim($_POST['name'])) : '';
    $code = isset($_POST['code']) ? addslashes(trim($_POST['code'])) : '';;
    if($name&&$code){
        $sessionCode = isset($_SESSION['code']) ? $_SESSION['code'] : '';
 
        if(strcasecmp($code,$sessionCode)==0){
            $query= $db->select('uid')->from('table.users')->where('name = ?', $name);
            $user = $db->fetchRow($query);
            if($user){
                /*登录*/
                $authCode = function_exists('openssl_random_pseudo_bytes') ?
                    bin2hex(openssl_random_pseudo_bytes(16)) : sha1(Typecho_Common::randString(20));
                $user['authCode'] = $authCode;
 
                Typecho_Cookie::set('__typecho_uid', $user['uid'], 0);
                Typecho_Cookie::set('__typecho_authCode', Typecho_Common::hash($authCode), 0);
 
                /*更新最后登录时间以及验证码*/
                $db->query($db
                    ->update('table.users')
                    ->expression('logged''activated')
                    ->rows(array('authCode' => $authCode))
                    ->where('uid = ?', $user['uid']));
 
                /*压入数据*/
                $this->push($user);
                $this->_user = $user;
                $this->_hasLogin = true;
                $this->pluginHandle()->loginSucceed($this, $name, ''false);
 
                /*重置短信验证码*/
                $randCode = '';
                $chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPRSTUVWXYZ23456789';
                for ( $i = 0; $i < 5; $i++ ){
                    $randCode .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
                }
                $_SESSION['code'] = strtoupper($randCode);
 
                $this->widget('Widget_Notice')->set(_t('用户已存在,已为您登录 '), 'success');
                /*跳转验证后地址*/
                if (NULL != $this->request->referer) {
                    $this->response->redirect($this->request->referer);
                else if (!$this->user->pass('contributor'true)) {
                    /*不允许普通用户直接跳转后台*/
                    $this->response->redirect($this->options->profileUrl);
                else {
                    $this->response->redirect($this->options->adminUrl);
                }
            }else{
                /*注册*/
                /** 如果已经登录 */
                if ($this->user->hasLogin() || !$this->options->allowRegister) {
                    /** 直接返回 */
                    $this->response->redirect($this->options->index);
                }
                $hasher = new PasswordHash(8, true);
                $generatedPassword = Typecho_Common::randString(7);
 
                $dataStruct = array(
                    'name'      =>  $name,
                    'mail'      =>  $name.'@tongleer.com',
                    'screenName'=>  $name,
                    'password'  =>  $hasher->HashPassword($generatedPassword),
                    'created'   =>  $this->options->time,
                    'group'     =>  'subscriber'
                );
 
                $insert = $db->insert('table.users')->rows($dataStruct);
                $insertId = $db->query($insert);
 
                $this->pluginHandle()->finishRegister($this);
 
                $this->user->login($name, $generatedPassword);
 
                Typecho_Cookie::delete('__typecho_first_run');
 
                /*重置短信验证码*/
                $randCode = '';
                $chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPRSTUVWXYZ23456789';
                for ( $i = 0; $i < 5; $i++ ){
                    $randCode .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
                }
                $_SESSION['code'] = strtoupper($randCode);
 
                $this->widget('Widget_Notice')->set(_t('用户 <strong>%s</strong> 已经成功注册, 密码为 <strong>%s</strong>', $this->screenName, $generatedPassword), 'success');
                $this->response->redirect($this->options->adminUrl);
            }
        }else{
            echo'<script>alert("验证码错误!");</script>';
        }
    }
}
?>
<?php $this->need('header.php'); ?>
<link rel="stylesheet" href="//cdn.bootcss.com/mdui/0.4.1/css/mdui.min.css" xmlns="http://www.w3.org/1999/html">
<script src="//cdn.bootcss.com/mdui/0.4.1/js/mdui.min.js"></script>
<script src="//libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<!-- content section -->
<section>
    <div class="mdui-shadow-10 mdui-center" style="width:300px;">
        <div class="mdui-typo mdui-valign mdui-color-blue mdui-text-color-white">
            <h6 class="mdui-center">用户注册</h6>
        </div>
        <form action="" method="post" class="mdui-p-x-1 mdui-p-y-1">
            <div class="mdui-textfield mdui-textfield-floating-label">
                <label class="mdui-textfield-label"><?php _e('手机号'); ?></label>
                <input class="mdui-textfield-input" id="name" name="name" type="text" required value="<?php echo @$_POST['name']; ?>"/>
                <div class="mdui-textfield-error">手机号不能为空</div>
            </div>
 
            <div class="mdui-textfield mdui-textfield-floating-label">
                <label class="mdui-textfield-label"><?php _e('图形验证码'); ?></label>
                <input  class="mdui-textfield-input" id="CAPTCHA" style="width:50%;*float:left;" class="input" type="text" size="10" value="" name="captcha_code" >
                </input>
                <div class="mdui-textfield-error">图形验证码不能为空</div>
                <img style="150px;" id="captcha_img" src="<?php $this->options->siteUrl(); ?>usr/plugins/SmsBaoSms/captcha/captcha.php" title="看不清?点击更换" alt="看不清?点击更换" onclick="document.getElementById('captcha_img').src='<?php $this->options->siteUrl(); ?>usr/plugins/SmsBaoSms/captcha/captcha.php?'+Math.random();document.getElementById('CAPTCHA').focus();return false;" />
                <a href="javascript:void(0)" onclick="document.getElementById('captcha_img').src='<?php $this->options->siteUrl(); ?>usr/plugins/SmsBaoSms/captcha/captcha.php?'+Math.random();document.getElementById('CAPTCHA').focus();return false;">点击更换</a>
            </div>
 
            <div class="mdui-textfield mdui-textfield-floating-label">
                <label class="mdui-textfield-label"><?php _e('手机验证码'); ?></label>
                <input class="mdui-textfield-input" id="code" name="code" type="text" required value="<?php echo @$_POST['code']; ?>"/>
                <div class="mdui-textfield-error">手机验证码不能为空</div>
            </div>
            <div class="mdui-row-xs-2">
                <div id="smsmsg" class="mdui-col">
                    <button id="sendsmsmsg" class="mdui-btn mdui-color-blue mdui-text-color-white">发送验证码</button>
                </div>
                <div class="mdui-col">
                    <input type="hidden" id="sitetitle" value="<?php $this->options->title();?>" />
                    <input type="hidden" name="action" value="regbysms" />
                    <button id="reg" class="mdui-btn mdui-btn-block mdui-btn-raised mdui-color-theme-accent mdui-ripple mdui-color-blue mdui-text-color-white"><?php _e('注册'); ?></button>
                </div>
            </div>
        </form>
    </div>
</section>
<!-- end content section -->
<?php $this->need('footer.php'); ?>
<script>
    $("#sendsmsmsg").click(function(){
        var name=$("#name").val();
        var regexp = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        var captcha = $("#CAPTCHA").val();
        if(!regexp.test(name)){
            alert('请输入有效的手机号码!');
            return false;
        }
        // settime();
        $.post("<?php $this->options->siteUrl(); ?>usr/plugins/SmsBaoSms/sendsms.php",{name:name,sitetitle:$('#sitetitle').val(),captcha:captcha},function(data){
            if(data=='toofast'){
                alert('发送频率太快了~');
            }else if(data=='captchaempty'){
                alert('图形验证码有误~');
            }else if(data == 'captchafalse'){
                alert('图形验证码有误~');
            }else if(data == 'success'){
                alert('发送成功~');
                clearTimeout(timer);
                settime();
            }else{
                alert('发送失败');
            }
        });
    });
    $("#reg").click(function(e){
        var name=$("#name").val();
        var regexp = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        if(!regexp.test(name)){
            alert('请输入有效的手机号码!');
            return;
        }
        var yzm = $("input[name=code]").val().replace(/(^\s*)|(\s*$)/g, "");
        if(yzm==""){
            alert("请输入短信验证码");
            return;
        }
        $('form').submit();
    });
    var timer;
    var countdown=60;
    function settime() {
        if (countdown == 0) {
            $("#smsmsg").html("<button id='sendsmsmsg' class='mdui-btn mdui-btn-raised mdui-color-blue mdui-text-color-white'>发送验证码</button>");
            countdown = 60;
            clearTimeout(timer);
            return;
        else {
            $("#smsmsg").html("等待("+countdown+")秒");
            countdown--;
        }
        timer=setTimeout(function() {
            settime()
        },1000)
    }
</script>

3:register.php为登录界面 代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
include 'common.php';
 
if ($user->hasLogin() || !$options->allowRegister) {
    $response->redirect($options->siteUrl);
}
$rememberName = htmlspecialchars(Typecho_Cookie::get('__typecho_remember_name'));
$rememberMail = htmlspecialchars(Typecho_Cookie::get('__typecho_remember_mail'));
Typecho_Cookie::delete('__typecho_remember_name');
Typecho_Cookie::delete('__typecho_remember_mail');
 
$bodyClass = 'body-100';
 
include 'header.php';
?>
<div class="typecho-login-wrap">
    <div class="typecho-login">
        <h1><a href="http://typecho.org" class="i-logo">Typecho</a></h1>
        <form action="<?php $options->registerAction(); ?>" method="post" name="register" role="form">
            <p>
                <label for="name" class="sr-only"><?php _e('用户名'); ?></label>
                <input type="text" id="name" name="name" placeholder="<?php _e('用户名'); ?>" value="<?php echo $rememberName; ?>" class="text-l w-100" autofocus />
            </p>
            <p>
                <label for="mail" class="sr-only"><?php _e('Email'); ?></label>
                <input type="email" id="mail" name="mail" placeholder="<?php _e('Email'); ?>" value="<?php echo $rememberMail; ?>" class="text-l w-100" />
            </p>
            <p class="submit">
                <button type="submit" class="btn btn-l w-100 primary"><?php _e('注册'); ?></button>
            </p>
        </form>
 
        <p class="more-link">
            <a href="<?php $options->siteUrl(); ?>"><?php _e('返回首页'); ?></a>
            &bull;
            <a href="<?php $options->adminUrl('login.php'); ?>"><?php _e('用户登录'); ?></a>
        </p>
    </div>
</div>
<?php
include 'common-js.php';
?>
<script>
$(document).ready(function () {
    $('#name').focus();
});
</script>
<?php
include 'footer.php';
?>

4:sendsms.php 为短信宝发送类文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php 
session_start();
date_default_timezone_set('Asia/Shanghai');
include '../../../config.inc.php';
 
 
if(@$_COOKIE["sendcodetime"]!=''){
   echo 'toofast';
   return;
}
//验证图形验证码
$captcha =  $_POST['captcha'];
 
if(empty($captcha) || empty($_SESSION['sms_code'])) {
    echo 'captchaempty';
    return;
else if ((trim(strtolower($captcha)) != $_SESSION['sms_code'])) {
    echo 'captchafalse';
    return;
}else{
    unset($_SESSION['sms_code']);
    setcookie("sendcodetime", time(), time()+10);
    $query= $db->select('value')->from('table.options')->where('name = ?''plugin:SmsBaoSms');
    $row = $db->fetchRow($query);
    $arr=explode(':',$row['value']);
    $appkeystr=$arr[6];
    $secretstr=$arr[10];
    $aliCode=$arr[18];
    $signname=$arr[14];
    $appkey=substr($appkeystr,1,count($appkeystr)-4);
    $secret=substr($secretstr,1,count($secretstr)-4);
    $aliCode=substr($aliCode,1,count($aliCode)-4);
    $signname=substr($signname,1,count($signname)-4);
//重置短信验证码
    $randCode = rand(10000,99999);
    $content = '【'.$signname.'】'.str_replace('{$code}',$randCode,$aliCode);
    $_SESSION['code'] = $randCode;
    $name = isset($_POST['name']) ? addslashes(trim($_POST['name'])) : '';//发送到的用户名
    $sitetitle = isset($_POST['sitetitle']) ? addslashes(trim($_POST['sitetitle'])) : '';
    $smsapi = "http://api.smsbao.com/";
    $user = $appkey; //短信平台帐号
    $pass = md5($secret); //短信平台密码
    $content = $content;//要发送的短信内容
    $phone = $name;//要发送短信的手机号码
    $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
    $result = file_get_contents($sendurl);
    if($result == '0'){
        echo 'success';
    }else{
        echo 'false';
    }
    //    echo $_SESSION['code'];
}
 
?>

captcha文件下载链接 http://www.smsbao.com/download/captcha.zip

经过上面的替换,短信宝的短信平台已经替换成功了,可以正常使用了。进行测试发送:

报备一下短信宝的VIP模板,这样就可以走短信宝的优质通道了,即便遇到敏感文字我们都不会人工审核,短信内容3~5秒就可送达。

另外:我们已经开发好完整的typeho系统短信宝插件,点击此链接 下载及查看安装流程。

开源插件

最新更新

电商类

CMS类

微信类

文章标签