業務需求
- 同一手機號每日最多 5 次
- 同一手機號每日最多 3 個不同 IMEI
- 同一手機號 60 秒內不可重複發送
- 驗證碼 30 分鐘過期
核心類別 Api_Sms
class Api_Sms {
const EXPIRE_SEC = 1800; // 30 分鐘
const RESEND_SEC = 60; // 60 秒重發限制
const ONE_DAY_FREQ = 5; // 每日每手機號上限
const ONE_DAY_IMEI_COUNT = 3; // 每日每手機號不同 IMEI 上限
public $error = [];
/** 發送驗證碼 */
public function sendVerifyCode($mobile, $imei) {
if (!$this->isMobile($mobile)) {
$this->error = ['code' => -1, 'msg' => '手機號格式錯誤'];
return false;
}
$redis = Api_Common::redis();
$vcKey = 'VC_' . $mobile;
$limitKey = 'VC_LIMIT_' . $mobile;
// 重發限制檢查
$data = json_decode($redis->get($vcKey), true);
if ($data && time() < $data['resend_expire']) {
$this->error = ['code' => -1, 'msg' => '短信已在1分鐘內發出,請耐心等待'];
return false;
}
// 手機號+IMEI 發送頻率限制
$sendCnt = $redis->zScore($limitKey, $imei);
if ($sendCnt && $sendCnt >= self::ONE_DAY_FREQ) {
$this->error = ['code' => -1, 'msg' => '今日發送次數已達上限'];
return false;
}
$imeiCnt = $redis->zCard($limitKey);
if ($imeiCnt >= self::ONE_DAY_IMEI_COUNT && !$sendCnt) {
$this->error = ['code' => -1, 'msg' => '已超過驗證碼發送設備限制'];
return false;
}
// 產生/取得驗證碼
if (!$data) {
$vc = strval(rand(100000, 999999));
$data = ['vc' => $vc, 'resend_expire' => 0];
$redis->set($vcKey, json_encode($data));
$redis->expire($vcKey, self::EXPIRE_SEC);
}
$vc = $data['vc'];
// 發送簡訊(對接供應商 API)
$content = '安全驗證碼:' . $vc;
$result = $this->send($mobile, $content);
if ($result) {
// 更新重發時間
$data['resend_expire'] = time() + self::RESEND_SEC;
$ttl = $redis->ttl($vcKey);
$redis->set($vcKey, json_encode($data));
$redis->expire($vcKey, $ttl);
// 記錄發送次數與 IMEI
$redis->zIncrBy($limitKey, 1, $imei);
$redis->expireAt($limitKey, strtotime(date('Y-m-d', strtotime('+1 day'))));
}
return $result;
}
/** 實際發送介面(需對接供應商) */
public function send($mobile, $content) { return true; }
/** 手機號格式驗證 */
private function isMobile($mobile) {
return preg_match('/^1\d{10}$/', $mobile);
}
/** 驗證碼校驗 */
public function checkVerifyCode($mobile, $vc) {
$data = json_decode(Api_Common::redis()->get('VC_' . $mobile), true);
return $data && $data['vc'] === $vc;
}
/** 清除驗證碼 */
public function cleanVerifyCode($mobile) {
$redis = Api_Common::redis();
$redis->del('VC_' . $mobile);
$redis->del('VC_LIMIT_' . $mobile);
}
}
Redis 資料結構設計
VC_{mobile} (String, JSON):{"vc":"123456","resend_expire":1699999999},TTL 1800s
VC_LIMIT_{mobile} (Sorted Set):Member = IMEI, Score = 發送次數,TTL 至隔日 00:00
替代實作(純 PHP 陣列模擬,無 Redis)
// 另一網友提供的簡易版本,適用單機、低併發
// 略...
擴充建議
- 加入圖形驗證碼/滑塊驗證,防機器人濫發。
- 記錄發送日誌(手機、IMEI、IP、時間、結果)供風控分析。
- 支援多簡訊通道輪詢/容錯。
- 驗證碼長度、字元集可配置。