teodoriu/laravel-whatsapp

Laravel 的 Whatsapp Business Cloud API 封装器。

v1.0.3 2024-07-12 10:54 UTC

This package is auto-updated.

Last update: 2024-09-12 11:21:46 UTC


README

Laravel 的 WhatsApp Business Cloud API 包。

安装

composer require teodoriu/laravel-whatsapp

配置

您需要在 .env 文件中设置 WHATSAPP_TOKENWHATSAPP_NUMBER_ID 的值。

有关进一步配置,请参阅 config/whatsapp.php。您可以通过将其复制到本地 config 目录或通过定义配置文件中使用的环境变量来修改配置。

php artisan vendor:publish --provider="Teodoriu\Whatsapp\WhatsappServiceProvider" --tag=config

用法

您可以向单个或多个客户发送消息。

use Teodoriu\Whatsapp\Messages;

Whatsapp::send('13333333333', Messages\TemplateMessage::create()
    ->name('one_time_password')
    ->language('en_US')
    ->body(Messages\Components\Body::create([
        Messages\Components\Parameters\Text::create('000000'),
    ])));

您还可以在会话中回复其他消息,类型不限(除反应消息外)。

use Teodoriu\Whatsapp\Messages\TextMessage;

Whatsapp::send('13333333333', TextMessage::create('Answer to your message')->respondTo('wamid.91n23...'));

发送模板消息

Whatsapp::send(
  phones: 13333333333,
  message: FlowMessage::create()
  ->name('template_name')
  ->language('language_code')
);

并且您可以标记消息为已读。

Whatsapp::markRead('wamid.91n23...');

默认情况下,消息将从 default_number_id 发送,如果您想使用其他号码,可以使用 Whatsapp::numberId() 或将别名添加到配置的 numbers 列表中并使用 Whatsapp::numberName()。您还可以使用 Whatsapp::token() 手动设置令牌,或者您可以同时设置令牌和 numberId 并使用 Whatsapp::client()

支持的消息

  • 文本消息
  • 媒体消息
  • 模板消息
  • 反应消息
  • 联系人消息
  • 交互式消息
  • 位置消息

媒体

您还可以使用 管理媒体

Whatsapp::uploadMedia(string $file, string $type = null, bool $retrieveAllData = true): \Teodoriu\Whatsapp\WhatsappMedia|string
Whatsapp::getMedia(string $mediaId, bool $download = false): \Teodoriu\Whatsapp\WhatsappMedia
Whatsapp::deleteMedia(\Teodoriu\Whatsapp\WhatsappMedia|string $id): bool
Whatsapp::downloadMedia(string|\Teodoriu\Whatsapp\WhatsappMedia $media): \Teodoriu\Whatsapp\WhatsappMedia

商业资料

有两种方法可以管理号码的商业资料。

Whatsapp::getProfile(): \Teodoriu\Whatsapp\BusinessProfile
Whatsapp::updateProfile(\Teodoriu\Whatsapp\BusinessProfile|array $data): bool

Webhooks

WhatsApp 允许您订阅 webhooks 来接收通知,最重要的是接收来自客户的消息。订阅和通知都由 WhatsApp/webhook 路由自动处理(您可以使用 WHATSAPP_WEBHOOK_PATH 环境变量更改路径)。

当您注册 webhook 时,meta 会发送一个订阅,这需要您设置的验证令牌,您需要通过 WHATSAPP_WEBHOOK_VERIFY_TOKEN 环境设置来设置它。当收到订阅意向时,将触发一个 Teodoriu\Whatsapp\Events\SubscriptionIntentReceived 事件,如果请求成功,还会触发 Teodoriu\Whatsapp\Events\SuccessfullySubscribed 事件。

另一方面,通知将触发一个带有全部有效载荷的 Teodoriu\Whatsapp\Events\WebhookReceived 事件,如果您想通过验证 sha256 签名来保护此路由,必须设置 WHATSAPP_WEBHOOK_SIGNATURE_VERIFY 为 true 并将 WHATSAPP_SECRET 设置为 WhatsApp 应用程序的密钥。

如果有效载荷无效,将触发一个 Teodoriu\Whatsapp\Events\UnprocessableWebhookPayload 事件,其中包含描述错误的异常。

如果您想知道何时触发特定通知,可以订阅这些事件

  • Teodoriu\Whatsapp\Events\WebhookEntry 通用条目
  • Teodoriu\Whatsapp\Events\MessagesReceived 用于 messages 条目

通知通道

此库支持通道通知,只需将 routeNotificationForWhatsapp() 函数添加到可通知的用户(它可以返回一个 WhatsApp_id 或一个包含它们的数组)

class User extends Authenticatable
{
    use Notifiable;

    /**
     * @return string|array
     */
    public function routeNotificationForWhatsapp(): string|array
    {
        return "{$this->phone_code}{$this->phone}";
    }
}

现在创建一个实现 toWhatsapp() 函数的通知

//...
use Teodoriu\Whatsapp\Messages\TemplateMessage;
use Teodoriu\Whatsapp\Messages\Components\Parameters;
use Teodoriu\Whatsapp\WhatsappChannel;

class VerificationCode extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(protected string $code)
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [WhatsappChannel::class];
    }

    /**
     * Get the message representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Teodoriu\Whatsapp\Messages\WhatsappMessage
     */
    public function toWhatsapp($notifiable)
    {
        return TemplateMessage::create('one_time_password')
            ->language('en_US')
            ->body([
                Parameters\Text::create('123456'),
            ]);
    }
}

现在您可以发送 WhatsApp 通知

$user->notify(new VerificationCode('12345678'));

配置文件

return [
    /**
     * The whatsapp token to be used.
     */
    'token' => env('WHATSAPP_TOKEN'),

    /**
     * The whatsapp's app secret code. Required for webhook request signature verification.
     */
    'secret' => env('WHATSAPP_SECRET'),

    /**
     * The default NUMBER ID used to send the messages.
     */
    'default_number_id' => env('WHATSAPP_NUMBER_ID'),

    /**
     * If you want to use other number id's you can add them here so you can call
     * `numberName` with the name you provide here and make it easier to change
     * the phone where the messages are sended.
     */
    'numbers' => [
        // 'fallback' => env('WHATSAPP_FALLBACK_NUMBER_ID'),
    ],

    'webhook' => [
        /**
         * Wether to enable the webhook routes
         */
        'enabled' => env('WHATSAPP_WEBHOOK_ENABLED', true),

        /**
         * The webhook path, by default "/whatsapp/webhook"
         */
        'path' => env('WHATSAPP_WEBHOOK_PATH', 'whatsapp'),

        /**
         * The webhook verification token.
         * For more information check https://developers.facebook.com/docs/graph-api/webhooks/getting-started#verification-requests
         */
        'verify_token' => env('WHATSAPP_WEBHOOK_VERIFY_TOKEN'),

        /**
         * Wether the webhook request signature should be verified or not.
         */
        'verify_signature' => env('WHATSAPP_WEBHOOK_SIGNATURE_VERIFY', false),
    ],
];

缺少的功能

  • 注册/注销/验证新电话号码

许可证

该项目受 MIT 许可证 许可。

文档

https://developers.facebook.com/docs/whatsapp/cloud-api https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#media-messages