milan/whatsapp-cloud-api

第一个使用云托管版 WhatsApp 商务平台的 PHP SDK,用于发送和接收消息

dev-main 2024-06-25 18:55 UTC

This package is auto-updated.

Last update: 2024-09-25 19:35:45 UTC


README

重要:此包基于 netflie/whatsapp-cloud-api。此包增加了发送轮播模板和使用面向对象方法发送模板的支持

功能描述

此包使开发者能够在 PHP 代码中轻松访问 WhatsApp Cloud API 服务。

每月前 1,000 个会话 免费使用 WhatsApp Cloud API。一个会话。

入门指南

请根据官方指南的“开始使用”部分创建并配置您的 Facebook WhatsApp 应用程序。

最低要求 – 运行 SDK 需要 PHP >= 7.4 以及带有 OpenSSL 和 zlib 的 CURL >=7.19.4 的最新版本。

安装

composer require milan/whatsapp-cloud-api

快速示例

发送文本消息

<?php

// Require the Composer autoloader.
require 'vendor/autoload.php';

use Netflie\WhatsAppCloudApi\WhatsAppCloudApi;

// Instantiate the WhatsAppCloudApi super class.
$whatsapp_cloud_api = new WhatsAppCloudApi([
    'from_phone_number_id' => 'your-configured-from-phone-number-id',
    'access_token' => 'your-facebook-whatsapp-application-token',
]);

$whatsapp_cloud_api->sendTextMessage('34676104574', 'Hey there! I\'m using WhatsApp Cloud API. Visit https://www.netflie.es');

其他功能

此包基于 netflie/whatsapp-cloud-api

  • 带有参数的易于使用的模板
<?php

use Netflie\WhatsAppCloudApi\Message\Template\Component;
use Netflie\WhatsAppCloudApi\Message\Template\Components\BodyComponent;
use Netflie\WhatsAppCloudApi\Message\Template\Components\ButtonComponent;
use Netflie\WhatsAppCloudApi\Message\Template\Components\Buttons;
use Netflie\WhatsAppCloudApi\Message\Template\Components\HeaderComponent;
use Netflie\WhatsAppCloudApi\Message\Template\Parameters\Buttons\PayloadButton;
use Netflie\WhatsAppCloudApi\Message\Template\Parameters\Buttons\UrlButton;
use Netflie\WhatsAppCloudApi\Message\Template\Parameters\Text;
use Netflie\WhatsAppCloudApi\Message\Template\Parameters\Image;

...

$component_header = new HeaderComponent();
$component_header->addParameter(new Image('https://example.com/image.jpg')); //You can set a public Link or MediaId from Meta

$component_body = new BodyComponent();
$component_body->addParameter(new Text('*Mr Jones*'));

$component_buttons = new Buttons();
//You can set the order in the ButtonComponent or leave it blank or 0 to maintain the order as you add.
$component_buttons->addButton((new ButtonComponent())->setParameter(new PayloadButton('Yes'))); //Quick reply param Yes
$component_buttons->addButton((new ButtonComponent())->setParameter(new PayloadButton('No'))); //Quick reply param No 
$component_buttons->addButton((new ButtonComponent('url'))->setParameter(new UrlButton('123'))); //URL param https://example.com/user/123

$components = new Component($component_header, $component_body, $component_buttons);//The arguments not require a specific order
$whatsapp_cloud_api->sendTemplate('34676104574', 'sample_issue_resolution', 'en_US', $components); // Language is optional

...

支持的参数类型基于: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages/#parameter-object

  • 货币

  • 日期时间

  • 文档

  • 图片

  • 文本

  • 视频

  • 此包还增加了发送轮播模板的支持。

发送轮播模板消息

<?php

use Netflie\WhatsAppCloudApi\Message\Template\Component;
use Netflie\WhatsAppCloudApi\Message\Template\Components\BodyComponent;
use Netflie\WhatsAppCloudApi\Message\Template\Components\ButtonComponent;
use Netflie\WhatsAppCloudApi\Message\Template\Components\Buttons;
use Netflie\WhatsAppCloudApi\Message\Template\Components\HeaderComponent;
use Netflie\WhatsAppCloudApi\Message\Template\Parameters\Buttons\PayloadButton;
use Netflie\WhatsAppCloudApi\Message\Template\Parameters\Text;
use Netflie\WhatsAppCloudApi\Message\Template\Parameters\Image;

...

/* Message bubble; can omit if template message bubble has no variables */
$component_body = new BodyComponent();
$component_body->addParameter(new Text('<BUBBLE_TEXT_VARIABLE>'));

$component_carousel = new CarouselComponent();
/* Carousel cards */
/**You can add maximum 10 cards. Each card use Header, Body and Buttons (max 2 buttons) components*/
$card_header = new HeaderComponent();
$card_header->addParameter(new Image("<HEADER_ASSET_ID_OR_LINK>")); //Card Header should has Image or Video
$card_body = new BodyComponent();
$card_body->addParameter(new Text("<CARD_BODY_VARIABLE>"));
$card_body->addParameter(new Text("<CARD_BODY_VARIABLE_2>"));
$card_buttons = new Buttons();
$card_buttons->addButton((new ButtonComponent())->setParameter(new PayloadButton("<QUICK_REPLY_BUTTON_PAYLOAD>")));
$card_buttons->addButton((new ButtonComponent('url'))->setParameter(new PayloadButton("<URL_BUTTON_PAYLOAD>")));

//You can use two ways for create Card 
/**USE ONLY ONE**/
/**Pass a Component instance in the constructor */
$card = new Card(new Component($card_header, $card_body, $card_buttons));

/**Add each component separatly with the method addComponent */
$card = new Card();
$card->addComponent($card_header);
$card->addComponent($card_body);
$card->addComponent($card_buttons);

$component_carousel->addCard($card);
/**END CAROUSEL TEMPALTE EXAMPLE */

$components = new Component($component_body, $component_carousel);
$whatsapp_cloud_api->sendTemplate('34676104574', 'sample_carousel_template', 'en_US', $components); // Language is optional

...

发送文档

您可以通过两种方式发送文档:将文件上传到 WhatsApp 云服务器(您将收到一个标识符)或从指向互联网上发布的文档的链接。

<?php

use Netflie\WhatsAppCloudApi\Message\Media\LinkID;
use Netflie\WhatsAppCloudApi\Message\Media\MediaObjectID;

$document_id = '341476474779872';
$document_name = 'whatsapp-cloud-api-from-id.pdf';
$document_caption = 'WhastApp API Cloud Guide';

// With the Media Object ID of some document upload on the WhatsApp Cloud servers
$media_id = new MediaObjectID($document_id);
$whatsapp_cloud_api->sendDocument('34676104574', $media_id, $document_name, $document_caption);

// Or
$document_link = 'https://netflie.es/wp-content/uploads/2022/05/image.png';
$link_id = new LinkID($document_link);
$whatsapp_cloud_api->sendDocument('34676104574', $link_id, $document_name, $document_caption);

发送模板消息

<?php

$whatsapp_cloud_api->sendTemplate('34676104574', 'hello_world', 'en_US'); // Language is optional

发送音频消息

<?php

use Netflie\WhatsAppCloudApi\Message\Media\LinkID;

$audio_link = 'https://netflie.es/wp-content/uploads/2022/05/file_example_OOG_1MG.ogg';
$link_id = new LinkID($audio_link);
$whatsapp_cloud_api->sendAudio('34676104574', $link_id);

发送图片消息

<?php

use Netflie\WhatsAppCloudApi\Message\Media\LinkID;
use Netflie\WhatsAppCloudApi\Message\Media\MediaObjectID;

$link_id = new LinkID('http(s)://image-url');
$whatsapp_cloud_api->sendImage('<destination-phone-number>', $link_id);

//or

$media_id = new MediaObjectID('<image-object-id>');
$whatsapp_cloud_api->sendImage('<destination-phone-number>', $media_id);

发送视频消息

<?php

use Netflie\WhatsAppCloudApi\Message\Media\LinkID;
use Netflie\WhatsAppCloudApi\Message\Media\MediaObjectID;

$link_id = new LinkID('http(s)://video-url');
$whatsapp_cloud_api->sendVideo('<destination-phone-number>', $link_id, '<video-caption>');

//or

$media_id = new MediaObjectID('<image-object-id>');
$whatsapp_cloud_api->sendVideo('<destination-phone-number>', $media_id, '<video-caption>');

发送贴纸消息

贴纸示例: https://github.com/WhatsApp/stickers

<?php

use Netflie\WhatsAppCloudApi\Message\Media\LinkID;
use Netflie\WhatsAppCloudApi\Message\Media\MediaObjectID;

$link_id = new LinkID('http(s)://sticker-url');
$whatsapp_cloud_api->sendSticker('<destination-phone-number>', $link_id);

//or

$media_id = new MediaObjectID('<sticker-object-id>');
$whatsapp_cloud_api->sendSticker('<destination-phone-number>', $media_id);

发送位置消息

<?php

$whatsapp_cloud_api->sendLocation('<destination-phone-number>', $longitude, $latitude, $name, $address);

发送联系人消息

<?php

use Netflie\WhatsAppCloudApi\Message\Contact\ContactName;
use Netflie\WhatsAppCloudApi\Message\Contact\Phone;
use Netflie\WhatsAppCloudApi\Message\Contact\PhoneType;

$name = new ContactName('Adams', 'Smith');
$phone = new Phone('34676204577', PhoneType::CELL());

$whatsapp_cloud_api->sendContact('<destination-phone-number>', $name, $phone);

发送列表消息

<?php

use Netflie\WhatsAppCloudApi\Message\OptionsList\Row;
use Netflie\WhatsAppCloudApi\Message\OptionsList\Section;
use Netflie\WhatsAppCloudApi\Message\OptionsList\Action;

$rows = [
    new Row('1', '⭐️', "Experience wasn't good enough"),
    new Row('2', '⭐⭐️', "Experience could be better"),
    new Row('3', '⭐⭐⭐️', "Experience was ok"),
    new Row('4', '⭐⭐️⭐⭐', "Experience was good"),
    new Row('5', '⭐⭐️⭐⭐⭐️', "Experience was excellent"),
];
$sections = [new Section('Stars', $rows)];
$action = new Action('Submit', $sections);

$whatsapp_cloud_api->sendList(
    '<destination-phone-number>',
    'Rate your experience',
    'Please consider rating your shopping experience in our website',
    'Thanks for your time',
    $action
);

发送 CTA URL 消息

<?php

use Netflie\WhatsAppCloudApi\Message\CtaUrl\TitleHeader;

$header = new TitleHeader('Booking');

$whatsapp_cloud_api->sendCtaUrl(
    '<destination-phone-number>',
    'See Dates',
    'https://www.example.com',
    $header,
    'Tap the button below to see available dates.',
    'Dates subject to change.',
);

发送按钮回复消息

<?php

use Netflie\WhatsAppCloudApi\WhatsAppCloudApi;
use Netflie\WhatsAppCloudApi\Message\ButtonReply\Button;
use Netflie\WhatsAppCloudApi\Message\ButtonReply\ButtonAction;

$whatsapp_cloud_api = new WhatsAppCloudApi([
  'from_phone_number_id' => 'your-configured-from-phone-number-id',
  'access_token' => 'your-facebook-whatsapp-application-token' 
]);

$rows = [
    new Button('button-1', 'Yes'),
    new Button('button-2', 'No'),
    new Button('button-3', 'Not Now'),
];
$action = new ButtonAction($rows);

$whatsapp_cloud_api->sendButton(
    '<destination-phone-number>',
    'Would you like to rate us on Trustpilot?',
    $action,
    'RATE US', // Optional: Specify a header (type "text")
    'Please choose an option' // Optional: Specify a footer 
);

回复消息

您可以对之前发送的消息进行回复

<?php

$whatsapp_cloud_api
    ->replyTo('<whatsapp-message-id-to-reply>')
    ->sendTextMessage(
        '34676104574',
        'Hey there! I\'m using WhatsApp Cloud API. Visit https://www.netflie.es'
    );

媒体消息

上传媒体资源

媒体消息接受作为标识符的指向公共资源的 Internet URL(图像、视频、音频等)。当您尝试从 URL 发送媒体消息时,必须实例化 LinkID 对象。

您还可以将您的媒体资源上传到 WhatsApp 服务器,您将收到资源标识符

$response = $whatsapp_cloud_api->uploadMedia('my-image.png');

$media_id = new MediaObjectID($response->decodedBody()['id']);
$whatsapp_cloud_api->sendImage('<destination-phone-number>', $media_id);

下载媒体资源

要下载媒体资源

$response = $whatsapp_cloud_api->downloadMedia('<media-id>');

消息响应

WhatsAppCloudApi 实例在 WhatsApp 服务器返回错误时返回一个 Response 类或 ResponseException。

try {
    $response = $this->whatsapp_app_cloud_api->sendTextMessage(
        '<destination-phone-number>,
        'Hey there! I\'m using WhatsApp Cloud API. Visit https://www.netflie.es',
        true
    );
} catch (\Netflie\WhatsAppCloudApi\Response\ResponseException $e) {
    print_r($e->response()); // You can still check the Response returned from Meta servers
}

Webhooks

Webhook 验证

在您的 Meta App 仪表板中添加您的 webhook。您需要验证您的 webhook

<?php
require 'vendor/autoload.php';

use Netflie\WhatsAppCloudApi\WebHook;

// Instantiate the WhatsAppCloudApi super class.
$webhook = new WebHook();

echo $webhook->verify($_GET, "<the-verify-token-defined-in-your-app-dashboard>");

Webhook 通知

Webhook 已验证,您将开始在客户发送消息时收到通知。

<?php
require 'vendor/autoload.php';
define('STDOUT', fopen('php://stdout', 'w'));

use Netflie\WhatsAppCloudApi\WebHook;


$payload = file_get_contents('php://input');
fwrite(STDOUT, print_r($payload, true) . "\n");

// Instantiate the Webhook super class.
$webhook = new WebHook();

// Read the first message
fwrite(STDOUT, print_r($webhook->read(json_decode($payload, true)), true) . "\n");

//Read all messages in case Meta decided to batch them
fwrite(STDOUT, print_r($webhook->readAll(json_decode($payload, true)), true) . "\n");

Webhook::read 函数将返回一个 Notification 实例。请,探索 可用的不同通知。

标记消息为已读

当您从Webhooks收到传入消息时,您可以将其状态更改为已读来标记消息已读。标记为已读的消息会在其时间戳旁边显示两个蓝色勾选标记。

将消息标记为已读也会将对话中较早的消息标记为已读。

<?php

$whatsapp_cloud_api->markMessageAsRead('<message-id>');

获取企业资料

<?php

$whatsapp_cloud_api->businessProfile('<fields>');

更新企业资料

<?php

$whatsapp_cloud_api->updateBusinessProfile([
    'about' => '<about_text>',
    'email' => '<email>'
]);

字段列表: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles

功能

  • 发送文本消息
  • 发送文档
  • 发送带参数的模板
  • 发送音频
  • 发送图片
  • 发送视频
  • 发送贴纸
  • 发送位置
  • 发送联系人
  • 发送列表
  • 发送按钮
  • 将媒体资源上传到WhatsApp服务器
  • 从WhatsApp服务器下载媒体资源
  • 标记消息为已读
  • 获取/更新企业资料
  • Webhook 验证
  • Webhook 通知

寻求帮助

迁移到v2

有关如何升级到v2的更多信息,请参阅UPGRADE

更新日志

有关最近更改的更多信息,请参阅CHANGELOG

测试

composer unit-test

您还可以运行测试,通过调用WhatsApp Cloud API进行实际调用。请将您的测试凭据放在WhatsAppCloudApiTestConfiguration文件中。

composer integration-test

贡献

有关详细信息,请参阅CONTRIBUTING

许可

MIT许可证(MIT)。有关更多信息,请参阅许可文件。有关更多信息,请参阅许可文件

免责声明

此包不是由Facebook官方维护的。WhatsApp和Facebook商标和徽标是Meta Platforms,Inc.的财产。