phone; $type = $request->type ?? 1; $user_data = User::query()->where('phone', $request->phone)->first(); if ($user_data) return apiJsonError('您绑定的手机号已经存在!'); // 生成4位随机数,左侧补0 $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT); if (app()->environment('local')) { $code = '1234'; $content = "您的验证码是{$code}。如非本人操作,请忽略本短信"; event(new SendTextMessage($phone, $request->getClientIp(), $code, $content, $type)); } else { try { $content = "您的验证码${code},该验证码十分钟内有效,请勿泄漏于他人!"; /*$result = $easySms->send($phone, [ 'content' => $content ]);*/ $result = $easySms->send($phone, [ 'content' => $content, 'template' => 'SMS_199330236', //阿里云后台设置的短信模板ID 'data' => [ 'code' => $code //阿里云短信后台模板中的短信验证码变量code,要对应 ] ]); event(new SendTextMessage($phone, $request->getClientIp(), $code, $content, $type)); } catch (NoGatewayAvailableException $exception) { $message = $exception->getException('aliyun')->getMessage(); return apiJsonError('短信发送异常'); } } $key = 'verificationCode_' . NumberHelper::random('alnum'); $expiredAt = now()->addMinutes(10); // 缓存验证码 10分钟过期。 Cache::put($key, ['phone' => $phone, 'code' => $code], $expiredAt); return apiJson([ 'key' => $key, 'expired_at' => $expiredAt->toDateTimeString(), ], '验证码发送成功'); } }