初次写短信接口,基本方法都有....可能有点糙....已测试
验证码存在数据库
DROP TABLE IF EXISTS `dede_sms`;
CREATE TABLE `dede_sms` (`id` int(11) unsigned NOT NULL AUTO_INCREMENT,`phone` varchar(15) NOT NULL DEFAULT '',`code` varchar(8) NOT NULL DEFAULT '',`created_at` int(10) NOT NULL DEFAULT '0',`expire_at` int(10) NOT NULL DEFAULT '0',PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
WMsendSms.php 放在include下:
<?php
if(!defined('DEDEINC')) exit('Request Error!');//发送短信
//$cid 短信模板CID
function sendSms($mob,$cid = '微米短信模板查看CID')
{$res = validatePremise($mob);if($res){$ch = curl_init();curl_setopt($ch, CURLOPT_URL, "http://api.weimi.cc/2/sms/send.html");curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);curl_setopt($ch, CURLOPT_POST, TRUE);/*传入模板参数。短信模板内容示例:【微米】您的验证码是:%P%,%P%分钟内有效。如非您本人操作,可忽略本消息。传入两个参数:p1:610912p2:3最终发送内容:【微米】您的验证码是:610912,3分钟内有效。如非您本人操作,可忽略本消息。*/$uid = '微米查看去';$pas = '微米查看去';$p1 = createRandomCoder(4);$p2 = 5; //分钟curl_setopt($ch, CURLOPT_POSTFIELDS, "uid=$uid&pas=$pas&mob=$mob&cid=$cid&p1=$p1&p2=$p2&type=json");$res = curl_exec( $ch );curl_close( $ch );$arr = json_decode($res,true);if($arr['code'] == 0){saveCode($mob,$p1);return "短信发送成功!";}return "短信发送失败!";}else{return "短信发送频繁,请稍后再发送!";}
}//生成随机字符串
//$len 要生成的随机字符串长度
//$type 随机码类型:0,数字+大小写字母;1,数字;2,小写字母;3,大写字母;4,特殊字符;-1,数字+大小写字母+特殊字符
function createRandomCoder($len,$type = '0')
{$arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");if ($type == 0) {array_pop($arr);$string = implode("", $arr);} elseif ($type == "-1") {$string = implode("", $arr);} else {$string = $arr[$type];}$count = strlen($string) - 1;$code = '';for ($i = 0; $i < $len; $i++) {$code .= $string[rand(0, $count)];}return $code;
}//保存验证码
function saveCode($phone,$code,$time = 5)
{global $dsql;$created_at = time();$expire_at = time() + ($time * 60);$code = strtolower($code);$sql = "INSERT INTO `#@__sms`(`phone`,`code`,`created_at`,`expire_at`) VALUES ('$phone','$code','$created_at','$expire_at')";return $dsql->ExecuteNoneQuery($sql);
}//检查手机号,验证码
function validateCode($phone,$code)
{global $dsql;$code = strtolower($code);$current = time();$sql = "SELECT `id` FROM `#@__sms` WHERE `phone` LIKE '$phone' AND `code` LIKE '$code' AND `expire_at` > '$current' ";$row = $dsql->GetOne($sql);if(is_array($row)){return true;}else{return false;}
}//检查是否发送:防止恶意刷短信
//$phone 手机号
//$time 有效时间 (分钟)
function validatePremise($phone,$time = '1')
{global $dsql;$row = $dsql->GetOne("SELECT `id`,`expire_at` FROM `#@__sms` WHERE `phone` LIKE '$phone' ");if(is_array($row)){if( time() < $row['expire_at'] ){return false;}else{$dsql->ExecuteNoneQuery("DELETE FROM `#@__sms` WHERE id=".$row['id']);}}return true;
}