trungdv/zalo-otp
Composer 安装命令:
composer require trungdv/zalo-otp
包简介
Zalo OTP Package for Laravel - Send and verify OTP via Zalo API
README 文档
README
A Laravel package for integrating with Zalo ZNS (Zalo Notification Service) API, enabling you to send OTP and transactional messages via Zalo platform.
Features
- 🚀 Easy integration with Laravel applications
- 📱 Send OTP messages via Zalo ZNS
- 🔄 Access token refresh functionality
- 📊 Message delivery status tracking
- ⚡ Automatic error handling with custom exceptions
- 🛡️ Type-safe error codes
- 🔧 Configurable timeout and retry settings
Requirements
- PHP >= 8.1
- Laravel >= 9.0
- GuzzleHttp >= 7.0
Installation
1. Install package
composer require trungdv/zalo-otp
2. Publish config file
php artisan vendor:publish --tag=config
3. Configure in .env
# Zalo OTP Configuration ZALO_OTP_BASE_URL=https://oauth.zaloapp.com/v4/ ZALO_OTP_BUSINESS_BASE_URL=https://business.openapi.zalo.me/ ZALO_OTP_APP_ID=your_app_id ZALO_OTP_APP_SECRET=your_app_secret ZALO_OTP_TIMEOUT=30 ZALO_OTP_RETRY_ATTEMPTS=3
Configuration
The config file is published at config/zalo-otp.php:
return [ 'base_url' => env('ZALO_OTP_BASE_URL', 'https://oauth.zaloapp.com/v4/'), 'bussiness_base_url' => env('ZALO_OTP_BUSINESS_BASE_URL', 'https://business.openapi.zalo.me/'), 'app_id' => env('ZALO_OTP_APP_ID'), 'app_secret' => env('ZALO_OTP_APP_SECRET'), 'timeout' => env('ZALO_OTP_TIMEOUT', 30), 'retry_attempts' => env('ZALO_OTP_RETRY_ATTEMPTS', 3), ];
Usage
Sending OTP
Send an OTP message to a phone number using a pre-configured Zalo ZNS template.
use TrungDV\ZaloOtp\Facades\ZaloOtp; use TrungDV\ZaloOtp\Exceptions\ZaloException; try { // Get instance $client = ZaloOtp::getInstance(); // Send OTP $result = $client ->setAuthorization('your_access_token') ->sendOtp([ 'phone' => '0123456789', 'template_id' => 'your_template_id', 'template_data' => [ 'otp' => '123456', 'expire_time' => '5 phút' ] ]); // Handle successful response echo "Message sent successfully!"; echo "Message ID: " . $result['data']['msg_id']; } catch (ZaloException $e) { // Handle Zalo API errors echo "Error Code: " . $e->getZaloErrorCode(); echo "Error Message: " . $e->getMessage(); echo "Error Detail: " . $e->getZaloErrorDetail(); }
Testing Mode
If you want to test sending messages without actually delivering them to users, you can add the "mode": "development" option in the params when calling sendOtp().
Important Note: The development mode will only work when the recipient phone number has an admin role in your Zalo Official Account. Regular phone numbers will not receive messages in development mode.
try { $result = $client ->setAuthorization('your_access_token') ->sendOtp([ 'phone' => '0123456789', // Must be an admin phone number 'mode' => 'development', // Testing mode 'template_id' => 'your_template_id', 'template_data' => [ 'otp' => '123456' ] ]); } catch (ZaloException $e) { // Handle errors }
Refreshing Access Token
Refresh your Zalo access token using a refresh token.
use TrungDV\ZaloOtp\Facades\ZaloOtp; use TrungDV\ZaloOtp\Exceptions\ZaloException; try { // Get instance $client = ZaloOtp::getInstance(); // Set refresh token and refresh $result = $client ->setRefreshToken('your_refresh_token') ->refreshToken(); // Get new access token $newAccessToken = $result['access_token']; $newRefreshToken = $result['refresh_token']; $expiresIn = $result['expires_in']; // Store tokens for future use // ... } catch (ZaloException $e) { // Handle token refresh errors echo "Failed to refresh token: " . $e->getMessage(); }
Checking Message Status
Check the delivery status of a sent message.
use TrungDV\ZaloOtp\Facades\ZaloOtp; use TrungDV\ZaloOtp\Exceptions\ZaloException; try { // Get instance $client = ZaloOtp::getInstance(); // Get message status $result = $client ->setAuthorization('your_access_token') ->getStatusMessage([ 'message_id' => '1234567890', 'phone' => '0123456789' ]); // Check delivery status $status = $result['data']['status']; $sentTime = $result['data']['sent_time']; echo "Message Status: " . $status; } catch (ZaloException $e) { // Handle errors echo "Failed to get message status: " . $e->getMessage(); }
Error Handling
The package provides comprehensive error handling through the ZaloException class. All API methods automatically validate responses and throw exceptions when errors occur.
Exception Methods
try { $result = $client->sendOtp([...]); } catch (ZaloException $e) { // Get Zalo error code (integer) $errorCode = $e->getZaloErrorCode(); // Get user-friendly error message (in Vietnamese) $message = $e->getMessage(); // Get detailed error message from Zalo API $detail = $e->getZaloErrorDetail(); // Get all error data as array $errorData = $e->toArray(); /* [ 'zalo_error_code' => -108, 'zalo_error_detail' => 'Phone number is invalid', 'message' => 'Số điện thoại không hợp lệ' ] */ }
Common Error Codes
| Error Code | Description |
|---|---|
0 |
Success |
-100 |
Unknown error |
-108 |
Invalid phone number |
-115 |
Out of quota (insufficient balance) |
-124 |
Invalid access token |
-144 |
Daily ZNS quota exceeded |
For a complete list of error codes, check the ZaloErrorCode enum in src/Consts/ZaloErrorCode.php.
Response Format
All methods return an array containing the parsed JSON response from Zalo API:
Successful Response Example
[
'error' => 0,
'message' => 'Success',
'data' => [
'msg_id' => '1234567890',
'sent_time' => '2024-01-01 12:00:00',
// ... other data
]
]
Advanced Usage
Phone Number Formatting
The package automatically formats Vietnamese phone numbers from 0xxx format to 84xxx format:
// Both formats are accepted $client->sendOtp(['phone' => '0123456789', ...]); // Automatically converts to 84123456789 $client->sendOtp(['phone' => '84123456789', ...]); // Already in correct format
Custom Headers
You can set custom headers for your requests:
$client->setHeaders([ 'Custom-Header' => 'value' ]);
Debug Mode
For debugging purposes, you can generate a cURL command from your requests:
$curlCommand = $client->toCurlFromPendingRequest( $request, 'POST', 'https://api.zalo.me/endpoint', ['param' => 'value'] ); echo $curlCommand;
License
MIT License. See LICENSE file for more details.
Contributing
- Fork repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Create Pull Request
Support
If you encounter any issues or have questions, please:
- Create an issue on GitHub Issues
- Contact: trungdv@fabbi.io
Testing
Before using in production, test your integration in development mode:
// Send to admin phone numbers only $result = $client->sendOtp([ 'phone' => 'admin_phone', 'mode' => 'development', // ... ]);
Security
- Never commit your
.envfile or expose yourZALO_OTP_APP_SECRET - Store access tokens securely (database with encryption, cache with proper TTL)
- Implement rate limiting for OTP sending to prevent abuse
- Validate phone numbers before sending OTP
Changelog
See CHANGELOG.md for detailed version history.
Latest Changes
v1.0.4
- ✨ Added automatic error handling with
ZaloException - ✨ Integrated error handling directly into
ZaloClient - 🔥 Removed separate helpers file
- 📝 Improved documentation with comprehensive examples
- 🛡️ Type-safe error codes with
ZaloErrorCodeenum
v1.0.0
- 🎉 Initial release
- ✅ Send OTP via Zalo ZNS
- ✅ Refresh access token
- ✅ Get message delivery status
- ✅ Support for HTTP methods (GET, POST, PUT, PATCH)
- ✅ Facade support
- ✅ Service Container integration
trungdv/zalo-otp 适用场景与选型建议
trungdv/zalo-otp 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 27 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 10 月 22 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「sms」 「notification」 「laravel」 「otp」 「zalo」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 trungdv/zalo-otp 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 trungdv/zalo-otp 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 trungdv/zalo-otp 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
This package makes it easy to send notifications via AfricasTalking with Laravel
Apple Push Notification & Feedback Provider
A PSR-7 compatible library for making CRUD API endpoints
Throttle notifications on a per-channel basis
SDK for payment gateway PlatbaMobilom.sk for PHP7.0
Extensible library for building notifications and sending them via different delivery channels.
统计信息
- 总下载量: 27
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 21
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-10-22