PHPackages                             tuantrinitri/zalo-laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. tuantrinitri/zalo-laravel

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

tuantrinitri/zalo-laravel
=========================

Complete Laravel package for Zalo integration including OAuth authentication and ZNS (Zalo Notification Service) with automatic token management and queue support

08PHPCI failing

Since Oct 5Pushed 7mo agoCompare

[ Source](https://github.com/tuantrinitri/zalo)[ Packagist](https://packagist.org/packages/tuantrinitri/zalo-laravel)[ RSS](/packages/tuantrinitri-zalo-laravel/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Zalo Laravel Package
====================

[](#zalo-laravel-package)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c054b90972329e8655feb41d0c7dad6fcf6ffe135dd1699eefffb5b3a8de7a00/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7475616e7472696e697472692f7a616c6f2d6c61726176656c2d696e74656772617465642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tuantrinitri/zalo-laravel-integrated)[![Total Downloads](https://camo.githubusercontent.com/ccb9409f80a82206913a872d08f3c197ba5046b174d390e17b84b32e4949f038/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7475616e7472696e697472692f7a616c6f2d6c61726176656c2d696e74656772617465642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tuantrinitri/zalo-laravel-integrated)[![License](https://camo.githubusercontent.com/f1ec95c223408208655203871a1788b89cde63d504db1d9e2c3e56b14045377f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7475616e7472696e697472692f7a616c6f2d6c61726176656c2d696e74656772617465642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tuantrinitri/zalo-laravel-integrated)

Package Laravel chuyên nghiệp cho tích hợp Zalo, cung cấp **OAuth Authentication** và **ZNS (Zalo Notification Service)** với quản lý token tự động, hỗ trợ queue background và tích hợp seamless với Laravel ecosystem.

📋 Mục lục
---------

[](#-mục-lục)

- [🚀 Tính năng](#-t%C3%ADnh-n%C4%83ng)
- [📋 Yêu cầu hệ thống](#-y%C3%AAu-c%E1%BA%A7u-h%E1%BB%87-th%E1%BB%91ng)
- [⚡ Cài đặt](#-c%C3%A0i-%C4%91%E1%BA%B7t)
- [⚙️ Cấu hình](#%EF%B8%8F-c%E1%BA%A5u-h%C3%ACnh)
- [🔐 OAuth Authentication](#-oauth-authentication)
- [📱 ZNS Notification Service](#-zns-notification-service)
- [🔑 Quản lý Token](#-qu%E1%BA%A3n-l%C3%BD-token)
- [🎯 Helper Functions](#-helper-functions)
- [🚀 Advanced Usage](#-advanced-usage)
- [✨ Best Practices](#-best-practices)
- [🔧 Troubleshooting](#-troubleshooting)
- [🤝 Contributing](#-contributing)
- [📄 License](#-license)

🚀 Tính năng
-----------

[](#-tính-năng)

### 🔐 Zalo OAuth Authentication

[](#-zalo-oauth-authentication)

- ✅ **OAuth 2.0 Flow hoàn chỉnh** với PKCE support
- ✅ **Lấy thông tin user** từ Zalo profile
- ✅ **Session management** tự động
- ✅ **Laravel-style configuration** quen thuộc
- ✅ **ZaloProviderUser class** để xử lý user data

### 📱 Zalo Notification Service (ZNS)

[](#-zalo-notification-service-zns)

- ✅ **Gửi notification template** theo chuẩn Zalo
- ✅ **Auto token refresh** không cần can thiệp thủ công
- ✅ **Queue support** cho background processing
- ✅ **Bulk messaging** gửi hàng loạt
- ✅ **Database token storage** an toàn
- ✅ **Retry mechanisms** và error handling thông minh

### 🛠️ Laravel Integration

[](#️-laravel-integration)

- ✅ **Auto-discovery** service provider và facades
- ✅ **Facade patterns** dễ sử dụng (`Zalo`, `ZaloZns`)
- ✅ **Helper functions** tiện lợi
- ✅ **Artisan commands** quản lý token
- ✅ **Migration files** cho database
- ✅ **Event system** comprehensive logging

### ⚡ Performance &amp; Security

[](#-performance--security)

- ✅ **Smart caching** token và template
- ✅ **Phone number validation** chuẩn Việt Nam
- ✅ **Rate limiting** tránh spam
- ✅ **Error logging** chi tiết cho debugging
- ✅ **Health checks** monitoring system

---

📋 Yêu cầu hệ thống
------------------

[](#-yêu-cầu-hệ-thống)

- **PHP:** 7.4+ (khuyến nghị 8.1+)
- **Laravel:** 8.0+ (hỗ trợ đến 11.x)
- **Database:** MySQL 5.7+, PostgreSQL 10+, hoặc SQLite 3.8+
- **Queue Driver:** Redis (khuyến nghị), Database, hoặc SQS
- **Extensions:** `ext-curl`, `ext-json`, `ext-mbstring`

### Tài khoản Zalo cần thiết:

[](#tài-khoản-zalo-cần-thiết)

- **Zalo Developer Account** với App ID/Secret
- **Zalo Official Account** (cho ZNS) với OA ID/Secret
- **ZNS Service** được kích hoạt và có template

---

⚡ Cài đặt
---------

[](#-cài-đặt)

### Bước 1: Install Package

[](#bước-1-install-package)

```
composer require tuantrinitri/zalo-laravel-integrated
```

### Bước 2: Laravel Auto-Discovery

[](#bước-2-laravel-auto-discovery)

Package sẽ tự động đăng ký. Với Laravel &lt; 5.5, thêm vào `config/app.php`:

```
'providers' => [
    // ...
    Tuantrinitri\\ZaloLaravel\\Providers\\ZaloServiceProvider::class,
],

'aliases' => [
    // ...
    'Zalo' => Tuantrinitri\\ZaloLaravel\\Facades\\Zalo::class,
    'ZaloZns' => Tuantrinitri\\ZaloLaravel\\Facades\\ZaloZns::class,
],
```

### Bước 3: Publish Files

[](#bước-3-publish-files)

```
# Publish configuration file
php artisan vendor:publish --tag="zalo-config"

# Publish và chạy migrations
php artisan vendor:publish --tag="zalo-migrations"
php artisan migrate
```

---

⚙️ Cấu hình
-----------

[](#️-cấu-hình)

### Environment Variables

[](#environment-variables)

Thêm vào file `.env`:

```
# === ZALO OAUTH CONFIGURATION ===
ZALO_APP_ID=1234567890123456789
ZALO_APP_SECRET=abcdef1234567890abcdef1234567890
ZALO_REDIRECT_URL=https://yourdomain.com/auth/zalo/callback

# === ZALO OFFICIAL ACCOUNT (OPTIONAL) ===
ZALO_OA_ID=9876543210987654321
ZALO_OA_SECRET=fedcba0987654321fedcba0987654321

# === ZALO ZNS CONFIGURATION ===
ZALO_ZNS_APP_ID=1111222233334444
ZALO_ZNS_SECRET_KEY=xyzkeyabcd1234567890
ZALO_ZNS_BASE_URL=https://business.openapi.zalo.me
ZALO_ZNS_TIMEOUT=30

# === QUEUE CONFIGURATION ===
ZALO_ZNS_QUEUE=zalo-notifications
ZALO_ZNS_MAX_TRIES=3
QUEUE_CONNECTION=redis
```

### Configuration File

[](#configuration-file)

File `config/zalo.php` được tạo với cấu trúc:

```
return [
    'oauth' => [
        'app_id' => env('ZALO_APP_ID'),
        'app_secret' => env('ZALO_APP_SECRET'),
        'url_callback' => env('ZALO_REDIRECT_URL')
    ],

    'oa' => [
        'id' => env('ZALO_OA_ID'),
        'secret' => env('ZALO_OA_SECRET'),
    ],

    'zns' => [
        'app_id' => env('ZALO_ZNS_APP_ID'),
        'secret_key' => env('ZALO_ZNS_SECRET_KEY'),
        'base_url' => env('ZALO_ZNS_BASE_URL', 'https://business.openapi.zalo.me'),
        'timeout' => env('ZALO_ZNS_TIMEOUT', 30),
        'queue_name' => env('ZALO_ZNS_QUEUE', 'default'),
        'max_tries' => env('ZALO_ZNS_MAX_TRIES', 3),

        // Template IDs
        'templates' => [
            'order_confirmation' => 'your_order_template_id',
            'appointment_reminder' => 'your_appointment_template_id',
            'payment_confirmation' => 'your_payment_template_id',
        ],
    ],
];
```

### Queue Setup (Khuyến nghị)

[](#queue-setup-khuyến-nghị)

```
# Cài đặt Redis
composer require predis/predis

# Cấu hình trong config/queue.php
'connections' => [
    'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue' => env('REDIS_QUEUE', 'default'),
        'retry_after' => 90,
        'block_for' => null,
    ],
],
```

---

🔐 OAuth Authentication
----------------------

[](#-oauth-authentication)

### Basic Login Flow

[](#basic-login-flow)

#### Tạo Routes

[](#tạo-routes)

```
// routes/web.php
use Illuminate\Http\Request;
use Tuantrinitri\ZaloLaravel\Facades\Zalo;

// Redirect đến Zalo login
Route::get('/auth/zalo', function () {
    try {
        $loginUrl = Zalo::loginZalo();
        return redirect($loginUrl);
    } catch (Exception $e) {
        return redirect('/login')
            ->with('error', 'Không thể kết nối đến Zalo. Vui lòng thử lại.');
    }
})->name('auth.zalo');

// Xử lý callback từ Zalo
Route::get('/auth/zalo/callback', function (Request $request) {
    try {
        $zaloUser = Zalo::getInfoUserThenLogin();

        if (empty($zaloUser) || !isset($zaloUser['id'])) {
            throw new Exception('Không lấy được thông tin người dùng từ Zalo');
        }

        // Tìm hoặc tạo user trong database
        $user = App\Models\User::updateOrCreate(
            ['zalo_id' => $zaloUser['id']],
            [
                'name' => $zaloUser['name'] ?? 'Zalo User',
                'email' => $zaloUser['id'] . '@zalo.local',
                'avatar' => $zaloUser['picture']['data']['url'] ?? null,
                'zalo_profile' => json_encode($zaloUser),
            ]
        );

        // Đăng nhập user
        Auth::login($user, true);

        return redirect()
            ->intended('/dashboard')
            ->with('success', 'Đăng nhập thành công với Zalo!');

    } catch (Exception $e) {
        Log::error('Zalo OAuth Error: ' . $e->getMessage());

        return redirect('/login')
            ->with('error', 'Đăng nhập thất bại. Vui lòng thử lại.');
    }
})->name('auth.zalo.callback');
```

#### Update User Model

[](#update-user-model)

Thêm migration cho Zalo fields:

```
// Migration: xxxx_add_zalo_fields_to_users_table.php
Schema::table('users', function (Blueprint $table) {
    $table->string('zalo_id')->nullable()->unique();
    $table->string('avatar')->nullable();
    $table->json('zalo_profile')->nullable();
});
```

Update User model:

```
// app/Models/User.php
protected $fillable = [
    'name', 'email', 'password', 'zalo_id', 'avatar', 'zalo_profile'
];

protected $casts = [
    'zalo_profile' => 'array',
];

public function hasZaloAccount(): bool
{
    return !is_null($this->zalo_id);
}
```

#### Login Button UI

[](#login-button-ui)

```

        Đăng nhập bằng Zalo

.btn-zalo {
    background: #0068ff;
    color: white;
    padding: 10px 20px;
    text-decoration: none;
    border-radius: 5px;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}
.btn-zalo:hover {
    background: #0056cc;
}

```

### Advanced OAuth Usage

[](#advanced-oauth-usage)

#### Custom Parameters

[](#custom-parameters)

```
use Tuantrinitri\ZaloLaravel\Facades\Zalo;

// Generate login URL with custom parameters
$metadata = Zalo::getLoginUrl(
    'https://yourdomain.com/custom-callback', // Custom callback URL
    'custom-state-data', // Custom state
    'custom-verifier' // Custom PKCE verifier
);

$loginUrl = $metadata['url'];
$state = $metadata['state'];
$codeVerifier = $metadata['code_verifier'];

// Store trong session để sử dụng sau
session([
    'zalo_verifier' => $codeVerifier,
    'zalo_state' => $state
]);
```

#### Get User Info từ Access Token

[](#get-user-info-từ-access-token)

```
// Nếu đã có access token
$accessToken = 'your_access_token';
$userProfile = Zalo::getInfoUserFromAccessToken($accessToken);

// Sử dụng helper tạo user object
$user = zalo_provider_user($userProfile);

echo $user->getId();
echo $user->getName();
echo $user->getEmail();
```

---

📱 ZNS Notification Service
--------------------------

[](#-zns-notification-service)

### Setup Token Ban Đầu

[](#setup-token-ban-đầu)

Trước khi sử dụng ZNS, cần setup token:

```
# Tạo artisan command để setup token
php artisan make:command SetupZnsToken
```

```
// app/Console/Commands/SetupZnsToken.php
