You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
3.3 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Http\Controllers\API;
use App\Services\TencentSmsApiService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class SmsController
{
public $Lifespan=1;//验证码有效期单位分钟
public function SendCode(Request $request)
{
$phoneNumber = $request->input('tel');
$code = $this->generateCode();
$service = new TencentSmsApiService();
$cha=DB::table('sms')->where(['phone'=>$phoneNumber])->orderBy('id','desc')->first();
if(!!$cha){
$specificTimeTimestamp = strtotime($cha->created_at);
// 计算一分钟之后的时间戳
$oneMinuteLaterTimestamp = strtotime('+1 minute', $specificTimeTimestamp);
if($oneMinuteLaterTimestamp>time()){
return \Yz::echoError1('请稍后再试');
}
}
$end_time = strtotime('+'.$this->Lifespan.' minute', time());
$in=DB::table('sms')->insert([
'code'=>$code,
'phone'=>$phoneNumber,
'status'=>0,
'lifespan'=>$this->Lifespan,
'end_time'=>date('Y-m-d H:i:s', $end_time)
]);
if($in){
$params = [$code,(string)$this->Lifespan];
$ss= $service->send($phoneNumber,"2564483", $params);
return \Yz::Return(true,'短信验证码发送成功');
}
}
//校验短信验证码
public function CheckCode($phone,$code)
{
$nowtime=date('Y-m-d H:i:s');
$cha=DB::table('sms')->where(['phone'=>$phone,'code'=>$code,'status'=>0,['end_time','>',$nowtime]])->first();
if(!!$cha){
$u=DB::table('sms')->where(['id'=>$cha->id])->update([
'status'=>1
]);
if($u){
return true;
}
}else{
return false;
}
}
// 生成随机验证码
function generateCode($length = 4) {
$characters = '0123456789';
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $characters[rand(0, strlen($characters) - 1)];
}
return $code;
}
public function CallBack(Request $request)
{
// 1. 解析 JSON 数据 (腾讯云回调是数组格式)
$dataList = json_decode($request->getContent(), true);
// 兼容:如果不是数组,强制转为数组
if (!is_array($dataList)) {
$dataList = $dataList ? [$dataList] : [];
}
foreach ($dataList as $item) {
$sid = $item['sid'] ?? null;
// 2. 只有当 sid 存在时才处理
if ($sid) {
// 3. 查找并更新:找到就存 JSON找不到自动忽略 (update 影响行数为 0)
DB::table('sms_log')
->where('sid', $sid)
->update([
'callback_content' => json_encode($item, JSON_UNESCAPED_UNICODE),
'updated_at' => now()
]);
}
}
// 4. 必须按文档返回特定格式,否则腾讯云会重试
return response()->json(['result' => 0, 'errmsg' => 'OK']);
}
public function TestSend()
{
$service = new TencentSmsApiService();
$ss= $service->send('19933509886',"2567513", ["小明","转入"]);
}
}