短信接口API
我用的FLEA,可能大家都没听说过,但原理是一样的,大家适当参考下吧。
-
token和client_token我是配置在一个config文件里的
array(
\’token\’ => \’ aaaa\’,
\’param\’ =>array(
\’url\’ => \’http://\’, // 短信接口地址
\’method\’=>\’sms.send\’, // 接口名称 自己定义的
\’client_token\’ => \’bbbbbbb\’,
)
),
);
?>
2.api接口
<?php
FLEA::loadClass(\'TMIS_Controller\');
class Controller_Org_Sms extends TMIS_Controller {
var $_json;//从json文件载入后的对象
var $_arr_method=array();//所有的方法名列表
var $_method;//当前的方法
var $_params;//当前参数
var $_success;//是否成功
var $_msg;//失败的错误信息,或者成功后的结果json
// var $_modelExample;
function __construct() {
// $this->_modelExample = & FLEA::getSingleton(\'Model_Jichu_Message\'); 这个是记录发送短信的信息内容,发送人,时间等的表,如果不需要存数据库,可以不用
$this->_url = "发送短信的url";
}
/**
* 生成签名的算法,这个算法应该每个短信接口的网站都有自己的算法规则,我这里是互亿的签名算法
*/
private function getSign($params ,$token_client = \'\'){
//签名步骤一:按字典序排序参数
ksort($params , SORT_STRING);
$string = http_build_query($params);
//签名步骤二:在string后加入Token
$string = $string . "&client_token=".$token_client;
return strtoupper(md5($string));
}
//发送短信的接口
public function sendSms($params = array()){
$data = array(
\'to\' =>$params[\'to\'],
\'content\' =>$params[\'content\'],
\'curtime\' =>time()-1,
);
return $this->callApi($data);
}
function callApi($post) {
require "Config/sms_config.php";
$arrSMS = $sms_config[\'SMS\'];
$param = $arrSMS[\'param\'];
$url = $param[\'url\'];
$token = $arrSMS[\'token\'];
$post[\'client_token\'] = $arrSMS[\'param\'][\'client_token\'];
$post[\'method\'] = $arrSMS[\'param\'][\'method\'];
$post[\'sign\'] = $this->getSign($post ,$token);
//curl post 请求
$objRequest = FLEA::getSingleton(\'Api_Httprequest\'); //调用第三步Api_Httprequest类
$result = $objRequest->post($post,$url);
$result = json_decode($result ,1);
return $result;
}
}
?>
3.curl 的 post请求和get请求封装成一个类
<?php
/*********************************************************************\
* Remark :用curl模拟http请求,用来访问api,一般在api的调用方被包含
\*********************************************************************/
class Api_Httprequest{
//post方式提交数据,注意post_data不能有嵌套的数组
public function post($post_data,$url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL,$url);
//设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上, 0为直接输出屏幕,非0则不输出
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//为了支持cookie
//curl_setopt($ch, CURLOPT_COOKIEJAR, \'cookie.txt\');
/*
// POST数据
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
*/
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
//curl_excc会输出内容,而$result只是状态标记
$result = curl_exec($ch);
$errorCode = curl_errno($ch);
//释放curl句柄
curl_close($ch);
if(0 !== $errorCode) {
$this->_success = false;
$this->writeLog($url ,$post_data);
return false;
}
$this->_success = true;
$this->_msg = $result;
$this->writeLog($url ,$post_data);
// $result = ob_get_contents();
// ob_end_clean();
return $result;
}
function get($query,$url) {
$info = parse_url($url);#print_r($info);exit;
$fp = fsockopen($info["host"], 80, $errno, $errstr, 3);
$head = "GET ".$info[\'path\']."?".$info["query"]." HTTP/1.0\r\n";
$head .= "Host: ".$info[\'host\']."\r\n";
$head .= "\r\n";
$write = fputs($fp, $head);
while (!feof($fp)) {
$line = fread($fp,4096);
echo $line;
}
}
}
?>
4.前台传值代码
</div>
<button type="submit" id="submit" tabindex="4">登 录</button>
<script type="text/javascript">
//点击获取验证码按钮
$(\'.action-get-verifycode\').click(function(e){
e.preventDefault();
var el = document.getElementById(\'username\') ;
var elp = document.getElementById(\'password\') ;
if(this.hasClass(\'disabled\')) return false;
sendVerify(this,\'username\' + \'=\' + el.value + \'&password\' + \'=\' + elp.value);
});
function sendVerify(el,data) {
var url = el.href;
var textCont = el.getElement(\'span span\');
el.addClass(\'disabled\');
// $(el).find(\'span\').attr(\'disabled\',true);
// $(el).attr(\'disabled\',true);
textCont.innerHTML = el.innerText + \'(<i>0</i> )\';
var ttt = textCont.getElement(\'i\');
var cd = new countdown(textCont.getElement(\'i\'), {
start: 60,
secondOnly: true,
callback: function(e) {
el.removeClass(\'disabled\');
textCont.innerHTML = \'重发验证码\';
}
});
Query.send(url, el, data, function(rs) {
if(rs.success) {
cd.stop();
el.removeClass(\'disabled\');
textCont.innerHTML = \'重发验证码\';
}else{
cd.stop();
el.removeClass(\'disabled\');
textCont.innerHTML = \'获取验证码\';
}
});
}
5.验证用户名,密码,短信发送次数等,然后 调用方法:
//随机取6位字符数
public function randomkeys($length){
$key = \’\’;
$pattern = \’1234567890\’; //字符池
for($i=0;$i<$length;$i++){
$key .= $pattern{mt_rand(0,9)}; //生成php随机数
}
return $key;
}
//设置session保存时间
public function start_session($expire = 0) {
if ($expire == 0) {
$expire = ini_get(\’session.gc_maxlifetime\’);
} else{
ini_set(\’session.gc_maxlifetime\’, $expire);
}
session_start();
setcookie(session_name(), session_id(), time() + $expire, “/”);
}
从前台传入用户名和密码,判断是否正确
function actionSetVcode(){
//判断是否填写用户名
if($_POST[\'username\']){
$p[\'username\']=$_POST[\'username\'];
}else{
$msg = "无效用户名!";
echo json_encode(array(\'success\'=>false,\'msg\'=>$msg));
exit;
}
$m=FLEA::getSingleton(\'Model_Acm_User\');//加载用户的数据库
//判断用户名和密码是否一致
$str = " SELECT passwd from acm_userdb where userName=\'{$p[\'username\']}\'";
$passwd = $m->findBySql($str);
if($passwd[0][\'passwd\']!=$_POST[\'password\']){
$msg = "用户名和密码不一致!";
echo json_encode(array(\'success\'=>false,\'msg\'=>$msg));
exit;
}
//判断用户是否绑定手机号
$sql = "SELECT phone from acm_userdb where userName=\'{$p[\'username\']}\'";
$rs = $m->findBySql($sql);
if(!$rs[0][\'phone\'] && $p[\'username\']!=\'admin\'){
$msg = "对应用户可能没绑定手机号!";
echo json_encode(array(\'success\'=>false,\'msg\'=>$msg));
exit;
}
$_SESSION[\'count\'] = isset($_SESSION[\'count\'])?$_SESSION[\'count\']:0;
if($_SESSION[\'count\']>=3){
$msg = "今日发送次数已用完";
echo json_encode(array(\'success\'=>false,\'msg\'=>$msg));
exit;
}
if( time() - $_SESSION[\'lastmodify\'] < 120 ){
$msg = \'2分钟发送一次,还没到两分钟则不进行发送\';
echo json_encode(array(\'success\'=>false,\'msg\'=>$msg));
exit;
}
$vcode = $this->randomkeys(6);//取得随机6位数验证码
$mobile = $rs[0][\'phone\'];
$time_sess = 3600 * 3;//设置验证码有效时间
$this->start_session($time_sess);
$_SESSION[\'VcodeforLogin\'] = $vcode;
$_SESSION[\'mobileforLogin\'] = $mobile;
$_SESSION[\'username\'] = $_POST[\'username\'];
$_SESSION[\'password\'] = $_POST[\'password\'];
$_SESSION[\'count\'] ++;
$_SESSION[\'lastmodify\'] = time();
$content = "您的验证码是:".$vcode."。请不要把验证码泄露给其他人。";
$Sms = FLEA::getSingleton(\'Controller_Org_Sms\');//加载api控制器接口
$result = $Sms->sendSms(array(\'to\'=>$mobile ,\'content\'=>$content));//调用sendSms方法,$mobile是发送给谁,$content是发送的内容,
$result = json_decode($result,1);
$arr = array(\'success\'=>true);
echo json_encode($arr);exit;//
}
6.点击登录,传用户名,密码,填写的验证码和发送的验证码是否一致;
//确定按钮点击后效果
$(\’#form_login\’).submit(function(){
var verify = $(\'#verify\').val();
var username = $(\'#username\').val();
var password = $(\'#password\').val();
//填写验证码
var url = "?controller=Login&action=loginIndex";
var param = {
\'username\':username,
\'password\':password,
\'verify\':verify
};
$(\'#submit\').attr(\'disabled\',true);
$.ajax({
type: "POST",
url: url,
data: param,
dataType: \'json\',
async: false,//同步操作
success:function(json){
console.log(json);
if(json.success==false){
showError(json.msg);
setTimeout(function(){
$(\'#submit\').attr(\'disabled\',false);
$(\'#submit\').text(\'登 录\');
}, 500);
return false;
}else{
showMsg(\'登陆成功\');
}
},
});
var urls = "?controller=Main&action=Index";
setTimeout(function(){window.location.href=urls;}, 500);
return false;
$(\'#submit\').attr(\'disabled\',true);
$(\'#submit\').text(\'登录中…\');
$(this).ajaxSubmit({
\'data\':{\'is_ajax\':true},
success:function(t,b,f){
var json = eval("("+t+")");
if(json.success==true){
showMsg(\'登陆成功\');
setTimeout(function(){window.location.href=json.href;}, 500);
}else{
showError(json.msg);
setTimeout(function(){
$(\'#submit\').attr(\'disabled\',false);
$(\'#submit\').text(\'登 录\');
}, 500);
}
}
});
return false;
});