承接 softlivery/whatsapp-cloud-api-client 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

softlivery/whatsapp-cloud-api-client

Composer 安装命令:

composer require softlivery/whatsapp-cloud-api-client

包简介

A client library for WhatsApp Cloud API.

README 文档

README

An open-source Whatsapp Cloud API client for PHP that simplifies webhook handling and event dispatching.

Features

  • Full message sending helpers (text, media, template, contacts, location, reaction, interactive).
  • Media operations (upload, fetch metadata, delete).
  • Template management and analytics helpers.
  • WABA operations (phone numbers, assigned users/partners, conversation analytics, profiles).
  • Parses and validates webhook payloads, including recent account events.
  • Verifies webhook challenges through Facebook's Hub Verification token.

Installation

You can install the package using composer:

composer require softlivery/whatsapp-cloud-api-client

OAuth Code Exchange Contract

For embedded signup flows, use OAuthHelper::exchangeCode($code, $redirectUri) to request:

  • GET /oauth/access_token
  • query params: client_id, client_secret, code, redirect_uri

redirect_uri behavior:

  • The library always includes redirect_uri in the request query.
  • Empty redirect_uri is currently allowed for compatibility.
  • For production stability, prefer sending the exact redirect URI configured in Meta/Facebook app settings.

Example:

<?php

use Softlivery\WhatsappCloudApiClient\Http\CurlHttpClient;
use Softlivery\WhatsappCloudApiClient\OAuthHelper;

$helper = new OAuthHelper(
    'your_meta_client_id',
    'your_meta_client_secret',
    new CurlHttpClient()
);

$response = $helper->exchangeCode($embeddedSignupCode, 'https://app.example.com/meta/callback');
$accessToken = $response->getAccessToken();

Webhook Handling Guide

When integrating the Whatsapp Cloud API webhook, there are typically two operations to handle:

  1. Handling Facebook's Webhook Verification.
  2. Parsing and validating webhook events received on the endpoint.

This library provides the WebhookEventHelper to aid with these tasks.

Using the WebhookEventHelper

The WebhookEventHelper provides the following key methods:

  • isHubVerifyTokenValid(string $hubVerifyToken): bool: Validates the verification token sent by Facebook during webhook setup.
  • validateAndParse(string $payload, array $serverHeaders): Event: Parses and validates incoming webhook payloads.

Using WhatsappCloudClient

<?php

use Softlivery\WhatsappCloudApiClient\WhatsappCloudClient;
use Softlivery\WhatsappCloudApiClient\Http\CurlHttpClient;

$httpClient = new CurlHttpClient(); // Graph base URL + v25.0 by default
$client = new WhatsappCloudClient($accessToken, $httpClient);

// Messages
$client->messages($phoneNumberId)->sendText('+15551234567', 'Hello');
$client->messages($phoneNumberId)->sendTemplate(
    '+15551234567',
    'order_update',
    'en_US',
    [['type' => 'body', 'parameters' => [['type' => 'text', 'text' => '12345']]]]
);

// Media
$mediaId = $client->media($phoneNumberId)->upload('/tmp/invoice.pdf', 'application/pdf')->getMediaId();

// Templates
$templates = $client->templates($wabaId)->list(['limit' => 20])->getData();
$client->templates($wabaId)->edit('template_id_123', [
    'category' => 'UTILITY',
    'components' => [['type' => 'BODY', 'text' => 'Updated body']],
]);

// WABA
$numbers = $client->waba($wabaId)->phoneNumbers()->getData();

Example of Webhook Usage

The following example demonstrates how to build a webhook handler using WebhookEventHelper. The solution includes lines for releasing the client connection before continuing request processing, allowing long-running operations to continue efficiently.

<?php

require 'vendor/autoload.php';

use Softlivery\WhatsappCloudApiClient\Webhook\WebhookEventHelper;
use Psr\Log\LoggerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Softlivery\WhatsappCloudApiClient\Events\WebhookEvent;
use Softlivery\WhatsappCloudApiClient\Exception\InvalidSignatureException;
use Softlivery\WhatsappCloudApiClient\Exception\InvalidVerificationTokenException;

// Assuming $logger and $dispatcher are already initialized (PSR-compliant implementations):
$logger = new YourLoggerImplementation();
$dispatcher = new YourEventDispatcherImplementation();

// Initialize the WebhookEventHelper
$helper = new WebhookEventHelper('your_verify_token', 'your_app_secret');

try {
    if (array_key_exists(WebhookEventHelper::HUB_VERIFY_TOKEN_KEY, $_GET)) {
        // Handle Webhook Verification
        $hubVerifyToken = $_GET[WebhookEventHelper::HUB_VERIFY_TOKEN_KEY];
        
        if ($helper->isHubVerifyTokenValid($hubVerifyToken)) {
            echo $_GET['hub_challenge'];
        } else {
            throw new InvalidVerificationTokenException('Invalid Hub Verify Token');
        }

        exit;
    }

    // Ensure the script continues processing even if the client disconnects
    ignore_user_abort(true);
    ob_start();

    // Handle Incoming Webhook Events
    $payload = file_get_contents('php://input'); // Retrieve webhook payload
    $event = $helper->validateAndParse($payload, $_SERVER); // Parse & validate payload

    // Send a response to the client and close the connection
    header("Connection: close");
    header("Content-Length: " . ob_get_length());
    ob_end_flush();
    flush();

    // Process the event after releasing the client connection
    $dispatcher->dispatch(new WebhookEvent($event));
} catch (InvalidVerificationTokenException $e) {
    $logger->error('Verification failed: ' . $e->getMessage());
} catch (InvalidSignatureException $e) {
    $logger->error('Security signature check failed: ' . $e->getMessage());
} catch (Exception $e) {
    $logger->error('An unexpected error occurred: ' . $e->getMessage());
}

Explanation of the Code

  1. Releasing the Client Connection:

    • The ignore_user_abort(true) ensures that the script execution will continue even if the client disconnects during processing.
    • The ob_start() enables output buffering, while the header, ob_end_flush(), and flush() commands ensure that the response is sent to the client as early as possible, effectively closing the connection from the client's perspective.
  2. Continue Processing After Releasing the Client:

    • After the client connection is closed, the server continues processing the webhook event in the same thread.
    • This is particularly useful when handling long-running tasks within the same request thread.
  3. Webhook Verification and Event Parsing:

    • The verification process ensures secure communication between Facebook and your server during webhook setup.
    • The payload is safely parsed and processed into an event object, which can then be dispatched for further handling.

Testing the Webhook Handler

You can test your webhook endpoint with tools like ngrok to expose a local development environment to a public URL. Once exposed, set up the webhook in the Facebook Developer Console and monitor the events.

License

This project is licensed under the Apache-2.0 License. See the LICENSE file for more details.

Contributing

Contributions are welcome! Feel free to open issues or submit pull requests.

Upgrade Notes

1.0.0

  • Removed legacy oAuthHelper.
  • Removed deprecated CodeExchangeApiRequest; use RequestFactory::exchangeCode.
  • Introduced canonical OAuthHelper naming.
  • Added deterministic tests for OAuth code exchange request construction.
  • redirect_uri remains allowed as empty string for compatibility, and is always included in the query.

softlivery/whatsapp-cloud-api-client 适用场景与选型建议

softlivery/whatsapp-cloud-api-client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 14 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 03 月 29 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 softlivery/whatsapp-cloud-api-client 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2025-03-29