短信接口在业务中是必然会有的,那么怎么保证接口被刷呢?
我简单总结一下我的想法
public function get_code(){
$phone = $_REQUEST['tel'];
$token_key = $_REQUEST['token_key'];
$key='marain';
$now=date('Y-m-d');
$signkey=md5($key.$now.$phone.'marain');
if ($token_key !== $signkey){
$result = array();
$result['code'] =400;
$result['msg'] ='4001:令牌错误';
$result['info'] = '';
echo json_encode($result);
exit();
}
if ($phone==''){
$result = array();
$result['code'] =400;
$result['msg'] ='4002:电话不能为空';
$result['info'] = '';
echo json_encode($result);
exit();
}
if (!preg_match("/^1[34578]\d{9}$/", $phone)){
$result = array();
$result['code'] =400;
$result['msg'] ='4003:电话格式不正确';
$result['info'] = '';
echo json_encode($result);
exit();
}
$ip=get_client_ip();
$where_ip['create_ip']=$ip;
$sms_data = M('App_sms')->where($where_ip)->select();
$today_date = date('Y-m-d');
$total_onoip_count=0;
foreach ($sms_data as $k1=>$v1){
if(substr($v1['create_time'],0,10) == $today_date){
$total_onoip_count++;
}
}
if (count($sms_data) > 500){
}
if ($total_onoip_count> 100){
}
$where_who['tel_number']=$phone;
$sms_data = M('App_sms')->where($where_who)->order("id desc")->select();
if(empty($sms_data)){
$code = $this->_create_code();
$this->send_sms($phone, $code, $ip);
$result = array();
$result['code'] =200;
$result['msg'] ='获取成功';
$result['info'] = $code;
echo json_encode($result);
exit();
}
$total_send_count = 0;
foreach($sms_data as $key1=>$row1){
if(empty($key1)){
$last_send_time = $row1['create_time'];
}
if(substr($row1['create_time'],0,10) == $today_date){
$total_send_count++;
$code = $row1['code'];
}
}
if(empty($code)) $code = $this->_create_code();
if((strtotime($last_send_time) + 60) > time()){
$result['code'] =400;
$result['msg'] ='4004:获取失败,请不要频繁获取';
$result['info'] = '';
}else{
if($total_send_count < 30){
$this->send_sms($phone, $code, $ip);
$result['code'] =200;
$result['msg'] ='获取成功';
$result['info'] = $code;
}else{
$result['code'] =400;
$result['msg'] ='4005:获取失败,每人每天只能获取三十次验证码';
$result['info'] = '';
}
}
echo json_encode($result);
exit();
}
public function _create_code($length=4,$type="number"){
$array = array(
'number' => '01234567',
'string' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'mixed' => '01234567ABCDEFGHIJKLMNOPQRSTUVWXYZ',
);
$string = $array[$type];
$count = strlen($string)-1;
$rand = '';
for ($i = 0; $i < $length; $i++) {
$rand .= $string[mt_rand(0, $count)];
}
return $rand;
}
private function send_sms($mobile, $code, $ip){
if(empty($mobile) || empty($code) || empty($ip)) return false;
$content = '您的注册验证码是'.$code;
$url='发送短信接口'
$data = array();
$data['tel_number'] = $mobile;
$data['content'] = $content;
$data['code'] = $code;
$data['create_time'] = date('Y-m-d H:i:s');
$data['create_ip'] = get_client_ip();
$data['send_result'] = $send_result;
$insertid = M('App_sms')->add($data);
if($insertid) return true;
return false;
}