从0到1:使用Laravel Vonage Notification Channel构建用户注册短信验证系统

从0到1:使用Laravel Vonage Notification Channel构建用户注册短信验证系统

【免费下载链接】vonage-notification-channelVonage Notification Channel for Laravel.项目地址: https://gitcode.com/gh_mirrors/vo/vonage-notification-channel

在现代Web应用中,用户注册短信验证是保障账户安全的重要环节。本文将带你一步步使用Laravel Vonage Notification Channel构建一个完整的用户注册短信验证系统,无需复杂的第三方服务集成,让你轻松实现专业级的短信验证功能。

📋 准备工作:环境与依赖

在开始之前,请确保你的开发环境满足以下条件:

  • Laravel 8.x 或更高版本
  • PHP 7.4 或更高版本
  • Composer 包管理工具
  • Vonage(原Nexmo)账户及API凭证

首先,通过Composer安装Laravel Vonage Notification Channel包:

composer require laravel/vonage-notification-channel

安装完成后,服务提供商会自动注册。如果你需要手动注册,可以在config/app.php文件的providers数组中添加:

Illuminate\Notifications\VonageChannelServiceProvider::class,

🔑 Vonage账户配置

获取API凭证

  1. 访问Vonage官网注册并登录账户
  2. 在 dashboard 中创建新应用,获取API KeyAPI Secret
  3. 申请一个短信发送号码(SMS From Number

配置环境变量

打开项目根目录的.env文件,添加以下配置:

VONAGE_KEY=your_api_key VONAGE_SECRET=your_api_secret VONAGE_SMS_FROM=your_vonage_phone_number

配置文件位于config/vonage.php,你可以根据需要修改默认配置。该文件包含了短信发送号码、API凭证、签名密钥等重要配置项。

👤 创建用户模型与迁移

首先,创建用户模型和迁移文件(如果尚未创建):

php artisan make:model User -m

在迁移文件中添加手机号和验证字段:

Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->string('phone')->unique(); $table->string('verification_code'); $table->boolean('phone_verified')->default(false); $table->timestamps(); });

运行迁移:

php artisan migrate

📱 创建通知类

使用Artisan命令创建短信验证通知:

php artisan make:notification SmsVerificationNotification

编辑生成的通知类文件app/Notifications/SmsVerificationNotification.php

use Illuminate\Notifications\Notification; use Illuminate\Notifications\Messages\VonageMessage; class SmsVerificationNotification extends Notification { private $code; public function __construct($code) { $this->code = $code; } public function via($notifiable) { return ['vonage']; } public function toVonage($notifiable) { return (new VonageMessage) ->content("您的验证码是: {$this->code},有效期10分钟。"); } }

🔄 实现发送与验证逻辑

生成验证码

User模型中添加生成验证码的方法:

public function generateVerificationCode() { $this->verification_code = rand(100000, 999999); $this->save(); return $this->verification_code; }

发送验证码

创建注册控制器并添加发送验证码的方法:

use App\Models\User; use App\Notifications\SmsVerificationNotification; class RegisterController extends Controller { public function sendVerificationCode(Request $request) { $request->validate([ 'phone' => 'required|unique:users' ]); $user = User::firstOrCreate( ['phone' => $request->phone], ['name' => '新用户', 'email' => uniqid().'@example.com'] ); $code = $user->generateVerificationCode(); $user->notify(new SmsVerificationNotification($code)); return response()->json(['message' => '验证码已发送']); } }

验证验证码

添加验证验证码的方法:

public function verifyCode(Request $request) { $request->validate([ 'phone' => 'required', 'code' => 'required|digits:6' ]); $user = User::where('phone', $request->phone) ->where('verification_code', $request->code) ->first(); if (!$user) { return response()->json(['message' => '验证码错误'], 400); } $user->phone_verified = true; $user->save(); return response()->json(['message' => '验证成功']); }

🚀 配置路由

routes/api.php中添加路由:

Route::post('send-verification-code', [RegisterController::class, 'sendVerificationCode']); Route::post('verify-code', [RegisterController::class, 'verifyCode']);

✅ 测试验证流程

现在你可以使用Postman或其他API测试工具测试整个验证流程:

  1. 发送POST请求到/api/send-verification-code,参数phone=你的手机号
  2. 接收短信验证码
  3. 发送POST请求到/api/verify-code,参数phone=你的手机号&code=收到的验证码

⚙️ 高级配置与优化

自定义短信内容

你可以在config/vonage.php中配置默认的短信发送者信息,或在通知类中自定义短信内容和发送者。

处理发送失败

添加异常处理,确保在短信发送失败时能够妥善处理:

try { $user->notify(new SmsVerificationNotification($code)); } catch (\Exception $e) { // 记录日志或通知用户 Log::error('短信发送失败: ' . $e->getMessage()); return response()->json(['message' => '短信发送失败,请稍后重试'], 500); }

验证码过期时间

添加验证码过期逻辑,提高安全性:

// 在users表中添加verification_code_expires_at字段 public function generateVerificationCode() { $this->verification_code = rand(100000, 999999); $this->verification_code_expires_at = now()->addMinutes(10); $this->save(); return $this->verification_code; } // 验证时检查是否过期 $user = User::where('phone', $request->phone) ->where('verification_code', $request->code) ->where('verification_code_expires_at', '>', now()) ->first();

📝 总结

通过本文的教程,你已经成功使用Laravel Vonage Notification Channel构建了一个完整的用户注册短信验证系统。这个系统包括了验证码生成、发送、验证等核心功能,并且可以根据实际需求进行扩展和优化。

Laravel Vonage Notification Channel提供了简单而强大的API,让短信通知的集成变得轻松愉快。无论是用户验证、订单通知还是系统警报,它都能满足你的需求。

希望本文对你有所帮助,如果有任何问题或建议,请随时在评论区留言。祝你开发顺利!

【免费下载链接】vonage-notification-channelVonage Notification Channel for Laravel.项目地址: https://gitcode.com/gh_mirrors/vo/vonage-notification-channel

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考