97 lines
2.9 KiB
PHP
97 lines
2.9 KiB
PHP
<?php
|
|
namespace App\Services;
|
|
|
|
use App\Contracts\SmsContract;
|
|
use Illuminate\Support\Str;
|
|
use App\Utils\Str as UtilsStr;
|
|
use App\Models\Message;
|
|
use App\Http\Response\ResponseJson;
|
|
use App\Jobs\SendPhoneCode;
|
|
use Overtrue\EasySms\EasySms;
|
|
|
|
class SmsService implements SmsContract
|
|
{
|
|
use ResponseJson;
|
|
|
|
public function sendCode($mobile, $scene)
|
|
{
|
|
try {
|
|
if (empty($mobile)) return false;
|
|
$code = UtilsStr::random(6, 1);
|
|
$sceneMethod = sprintf('get%sSceneTemplateId', Str::camel($scene));
|
|
$templateId = $this->$sceneMethod();
|
|
$data = [
|
|
'content' => str_replace('#code#', $code, $templateId),
|
|
'template' => $templateId,
|
|
'data' => ['code' => $code],
|
|
];
|
|
//一分钟内不能多次发送
|
|
$created_at = Message::where('phone', $mobile)->orderBy('id', 'desc')->value('created_at');
|
|
if ($created_at) {
|
|
$created_at = $created_at->toDateTimeString();
|
|
$result = time() - strtotime($created_at);
|
|
if ($result < 60) {
|
|
return ['code'=>1, 'msg'=>'操作频繁,等待一分钟后再试'];
|
|
}
|
|
}
|
|
\DB::beginTransaction();
|
|
$m = Message::create([
|
|
'phone'=>$mobile,
|
|
'code'=>$code,
|
|
'message'=>$data['content'],
|
|
'ip'=>request()->ip(),
|
|
'confirmed'=>0,
|
|
]);
|
|
$arr = [
|
|
'mobile'=>$mobile,
|
|
'data'=>$data,
|
|
];
|
|
$sms_config = config('sms');
|
|
$easySms = new EasySms($sms_config);
|
|
try {
|
|
$easySms->send($mobile, $data,['aliyun']);
|
|
\DB::commit();
|
|
return true;
|
|
}catch (\Exception $e) {
|
|
$error_msg = $e->getExceptions()['aliyun']->getMessage();
|
|
throw new \Exception($error_msg);
|
|
}
|
|
} catch (\Exception $e) {
|
|
$this->getError($e);
|
|
return false;
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected function getLoginSceneTemplateId()
|
|
{
|
|
$gateways = config('sms.gateways');
|
|
$supplier = config('sms.supplier', 'aliyun');
|
|
return $gateways[$supplier]['template']['login']?:'';
|
|
}
|
|
|
|
protected function getRegisterSceneTemplateId()
|
|
{
|
|
$gateways = config('sms.gateways');
|
|
$supplier = config('sms.supplier', 'aliyun');
|
|
return $gateways[$supplier]['template']['register']?:'';
|
|
}
|
|
|
|
protected function getPasswordResetSceneTemplateId()
|
|
{
|
|
$gateways = config('sms.gateways');
|
|
$supplier = config('sms.supplier', 'aliyun');
|
|
return $gateways[$supplier]['template']['password_reset']?:'';
|
|
}
|
|
|
|
protected function getMobileBindSceneTemplateId()
|
|
{
|
|
$gateways = config('sms.gateways');
|
|
$supplier = config('sms.supplier', 'aliyun');
|
|
return $gateways[$supplier]['template']['mobile_bind']?:'';
|
|
}
|
|
}
|