input('email'); $validator = Validator::make($request->all(), [ 'email' => 'required|email', ]); if ($validator->fails()) { return $this->error($validator->errors()->first()); } $code = rand(1000, 9999); $notice = '本次验证码是' . '【 ' . $code . ' 】 ' . '有效期 5 分钟'; $subject = '邮箱验证通知'; try { Mail::raw($notice, function ($message) use ($email, $subject) { $message->subject($subject); $message->to($email); }); $mailCode = new MailCode(); $mailCode->account = $email; $mailCode->code = $code; $mailCode->state = 0; $mailCode->created_at = date('Y-m-d H:i:s'); $mailCode->save(); return $this->success(); } catch (\Exception $e) { return $this->error($e->getMessage()); } } //判断邮箱验证码 5分钟有效期 (这不是个API接口:哪里需要就放到哪里验证) public static function isEmailCodeRight($email, $code) { $result = MailCode::query() ->where('account', $email) ->where('code', $code) ->where('state', 0) ->where('created_at', '>', Carbon::now()->subMinutes(5)) ->orderBy('id', 'desc') ->first(); if (!$result) { return false; } $result->state = 1; //验证通过就失效 $result->save(); return true; } /** * @return void * 邮箱验证 */ public function emailVerify(Request $request){ if(empty($request->email)){ return $this->error("邮箱不能为空!"); // 邮箱不能为空 } if(empty($request->code)){ return $this->error("验证码不能为空!"); // 邮箱不能为空 } if(!self::isEmailCodeRight($request->email,$request->code)){ return $this->error("验证码验证失败!"); } return $this->success("验证码验证成功!"); } /** * @param $email * @param $title * @param $notice * @return bool * 邮箱发送通知 */ public static function sendNotice($email = null,$title = null, $notice = null) { try { Mail::raw($notice, function ($message) use ($email, $title) { $message->subject($title); $message->to($email); }); return true; } catch (\Exception $e) { return false; } } }