chat/whatsapp-integration 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

chat/whatsapp-integration

最新稳定版本:2.0.4

Composer 安装命令:

composer require chat/whatsapp-integration

包简介

A package for integrating WhatsApp features into Laravel 5.8 applications.

README 文档

README

This is a Composer package that integrates basic WhatsApp features into laravel apps using WhatsApp API with Twilio as the Business provider.This package handles the functionalities for sending WhatsApp messages and handling incoming messages in Laravel 5.8+ applications.

Latest Stable Version License

Table of Contents

Features

  • Send WhatsApp messages
  • Template message support
  • Media message handling
  • Webhook processing
  • Rate limiting
  • Comprehensive error handling
  • Validation
  • Easy integration

Requirements

  • PHP >= 7.1.3
  • Laravel >= 5.8
  • Twilio Account with WhatsApp capabilities
  • Composer

Installation

  1. Install the package via Composer:
composer require chat/whatsapp-integration
  1. Add the service provider in config/app.php (Laravel will auto-discover it):
'providers' => [
    // ...
    Chat\WhatsappIntegration\WhatsAppIntegrationServiceProvider::class,
]

Configuration

  1. Publish the configuration file:
php artisan vendor:publish --provider="Chat\WhatsappIntegration\WhatsAppIntegrationServiceProvider" --tag="whatsapp-config"
  1. Add the following to your .env file:
TWILIO_ACCOUNT_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_FROM_NUMBER=your_whatsapp_number  # Format: +1234567890

Usage

Basic Usage

use Chat\WhatsappIntegration\WhatsApp;
use Chat\WhatsappIntegration\Exceptions\WhatsAppException;

public function sendMessage(WhatsApp $whatsapp)
{
    try {
        $result = $whatsapp->sendMessage(
            '+1234567890',  // recipient's number
            'Hello from Laravel!'
        );
        
        // Success
        $messageSid = $result->sid;
        $status = $result->status;
        
    } catch (WhatsAppException $e) {
        // Handle error
        logger()->error('WhatsApp Error: ' . $e->getMessage());
    }
}

Template Messages

try {
    $result = $whatsapp->sendMessage(
        '+1234567890',
        'Your order has been confirmed',
        'HX350d429d32e64a552466cafecbe95f3c', // template ID
        json_encode(['1' => 'today', '2' => '3pm']) // variables
    );
} catch (WhatsAppException $e) {
    // Handle error
}

Handling Webhooks

try {
    $result = $whatsapp->handleWebhook(
        $request->all(),
        $request->fullUrl(),
        $request->header('X-Twilio-Signature')
    );
    
    $messageBody = $result['Body'];
    $fromNumber = $result['From'];
    $mediaUrls = $result['MediaUrls'];
    
} catch (WhatsAppException $e) {
    // Handle error
}

API Integration Examples

Here's how to integrate the package with your Laravel application's API:

  1. Create a controller:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Chat\WhatsappIntegration\WhatsApp;
use Chat\WhatsappIntegration\Exceptions\WhatsAppException;

class WhatsAppController extends Controller
{
    protected $whatsapp;

    public function __construct(WhatsApp $whatsapp)
    {
        $this->whatsapp = $whatsapp;
    }

    public function sendMessage(Request $request)
    {
        $request->validate([
            'to' => 'required|string',
            'message' => 'required|string'
        ]);

        try {
            $result = $this->whatsapp->sendMessage(
                $request->to,
                $request->message
            );

            return response()->json([
                'success' => true,
                'message_sid' => $result->sid,
                'status' => $result->status
            ]);
        } catch (WhatsAppException $e) {
            return response()->json([
                'success' => false,
                'error' => $e->getMessage()
            ], 400);
        }
    }

    public function handleWebhook(Request $request)
    {
        try {
            $result = $this->whatsapp->handleWebhook(
                $request->all(),
                $request->fullUrl(),
                $request->header('X-Twilio-Signature')
            );

            return response()->json(['status' => 'success']);
        } catch (WhatsAppException $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ], 400);
        }
    }
}
  1. Define routes in routes/api.php:
Route::prefix('whatsapp')->group(function () {
    Route::post('/send', [WhatsAppController::class, 'sendMessage']);
    Route::post('/webhook', [WhatsAppController::class, 'handleWebhook']);
});

Error Handling

The package provides several exception types:

try {
    $result = $whatsapp->sendMessage($to, $message);
} catch (ValidationException $e) {
    // Handle validation errors (invalid phone number, template, etc.)
} catch (RateLimitException $e) {
    // Handle rate limiting
} catch (ConnectionException $e) {
    // Handle Twilio API connection issues
} catch (WhatsAppException $e) {
    // Handle other WhatsApp-related errors
}

Common error scenarios:

  • Invalid phone number format (must be E.164: +1234567890)
  • Invalid template ID format
  • Invalid template variables
  • Rate limiting exceeded
  • Authentication errors
  • Invalid webhook signatures

Testing

  1. Set up your test environment:
cp .env.example .env.testing
  1. Configure test credentials in .env.testing:
TWILIO_ACCOUNT_SID=your_test_sid
TWILIO_AUTH_TOKEN=your_test_token
TWILIO_FROM_NUMBER=your_test_number
  1. Run all tests:
vendor/bin/phpunit

Run specific test suites:

# Integration tests
vendor/bin/phpunit tests/Integration/WhatsAppIntegrationTest.php

# Unit tests with mocking
vendor/bin/phpunit tests/Unit/WhatsAppMockTest.php

License

The MIT License (MIT). Please see License File for more information.

Credits

统计信息

  • 总下载量: 111
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-10-23