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

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

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

chat/whatsapp-integration

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

chat/whatsapp-integration 适用场景与选型建议

chat/whatsapp-integration 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 149 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 10 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「messaging」 「twilio」 「laravel」 「whatsapp」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 chat/whatsapp-integration 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 chat/whatsapp-integration 我们能提供哪些服务?
定制开发 / 二次开发

基于 chat/whatsapp-integration 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

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