Code Monkey home page Code Monkey logo

whatsapp-cloud-api's Introduction

What It Does

This package makes it easy for developers to access WhatsApp Cloud API service in their PHP code.

The first 1,000 conversations each month are free from WhatsApp Cloud API. A conversation.

Getting Started

Please create and configure your Facebook WhatsApp application following the "Get Stared" section of the official guide.

Minimum requirements – To run the SDK, your system will require PHP >= 7.4 with a recent version of CURL >=7.19.4 compiled with OpenSSL and zlib.

Installation

composer require netflie/whatsapp-cloud-api

Quick Examples

Send a text message

<?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');

Send a document

You can send documents in two ways: by uploading a file to the WhatsApp Cloud servers (where you will receive an identifier) or from a link to a document published on internet.

<?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);

Send a template message

<?php

$whatsapp_cloud_api->sendTemplate('34676104574', 'hello_world', 'en_US'); // If not specified, Language will be default to en_US and otherwise it will be required.

You also can build templates with parameters:

<?php

use Netflie\WhatsAppCloudApi\Message\Template\Component;

$component_header = [];

$component_body = [
    [
        'type' => 'text',
        'text' => '*Mr Jones*',
    ],
];

$component_buttons = [
    [
        'type' => 'button',
        'sub_type' => 'quick_reply',
        'index' => 0,
        'parameters' => [
            [
                'type' => 'text',
                'text' => 'Yes',
            ]
        ]
    ],
    [
        'type' => 'button',
        'sub_type' => 'quick_reply',
        'index' => 1,
        'parameters' => [
            [
                'type' => 'text',
                'text' => 'No',
            ]
        ]
    ]
];

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

Send an audio message

<?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);

Send an image message

<?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);

Send a video message

<?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>');

Send a sticker message

Stickers sample: 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);

Send a location message

<?php

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

Send a location request message

<?php

$body = 'Let\'s start with your pickup. You can either manually *enter an address* or *share your current location*.';
$whatsapp_cloud_api->sendLocationRequest('<destination-phone-number>', $body);

Send a contact message

<?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);

Send a list message

<?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
);

Send a CTA URL message

<?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.',
);

Send Catalog Message

<?php

$body = 'Hello! Thanks for your interest. Ordering is easy. Just visit our catalog and add items you\'d like to purchase.';
$footer = 'Best grocery deals on WhatsApp!';
$sku_thumbnail = '<product-sku-id>'; // product sku id to use as header thumbnail

$whatsapp_cloud_api->sendCatalog(
    '<destination-phone-number>',
    $body,
    $footer, // optional
    $sku_thumbnail // optional
);

Send a button reply message

<?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 
);

Send Multi Product Message

<?php

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

$rows_section_1 = [
    new Row('<product-sku-id>'),
    new Row('<product-sku-id>'),
    // etc
];

$rows_section_2 = [
    new Row('<product-sku-id>'),
    new Row('<product-sku-id>'),
    new Row('<product-sku-id>'),
    // etc
];

$sections = [
    new Section('Section 1', $rows_section_1),
    new Section('Section 2', $rows_section_2),
];

$action = new Action($sections);
$catalog_id = '<catalog-id>';
$header = 'Grocery Collections';
$body = 'Hello! Thanks for your interest. Here\'s what we can offer you under our grocery collection. Thank you for shopping with us.';
$footer = 'Subject to T&C';

$whatsapp_cloud_api->sendMultiProduct(
    '<destination-phone-number>',
    $catalog_id,
    $action,
    $header,
    $body,
    $footer // optional
);

Send Single Product Message

<?php

$catalog_id = '<catalog-id>';
$sku_id = '<product-sku-id>';
$body = 'Hello! Here\'s your requested product. Thanks for shopping with us.';
$footer = 'Subject to T&C';

$whatsapp_cloud_api->sendSingleProduct(
    '<destination-phone-number>',
    $catalog_id,
    $sku_id,
    $body, // body: optional
    $footer // footer: optional
);

Replying messages

You can reply a previous sent message:

<?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'
    );

React to a Message

You can react to a message from your conversations if you know the messageid

<?php

$whatsapp_cloud_api->sendReaction(
        '<destination-phone-number>',
        '<message-id-to-react-to>',
        '👍', // the emoji
    );

// Unreact to a message
$whatsapp_cloud_api->sendReaction(
        '<destination-phone-number>',
        '<message-id-to-unreact-to>'
    );

Media messages

Upload media resources

Media messages accept as identifiers an Internet URL pointing to a public resource (image, video, audio, etc.). When you try to send a media message from a URL you must instantiate the LinkID object.

You can also upload your media resources to WhatsApp servers and you will receive a resource identifier:

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

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

Download media resources

To download a media resource:

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

Message Response

WhatsAppCloudApi instance returns a Response class or a ResponseException if WhatsApp servers return an error.

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 verification

Add your webhook in your Meta App dashboard. You need to verify your 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 notifications

Webhook is now verified, you will start receiving notifications every time your customers send messages.

<?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");

The Webhook::read function will return a Notification instance. Please, explore the different notifications availables.

Mark a message as read

When you receive an incoming message from Webhooks, you can mark the message as read by changing its status to read. Messages marked as read display two blue check marks alongside their timestamp.

Marking a message as read will also mark earlier messages in the conversation as read.

<?php

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

Get Business Profile

<?php

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

Update Business Profile

<?php

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

Fields list: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/business-profiles

Features

  • Send Text Messages
  • Send Documents
  • Send Templates with parameters
  • Send Audios
  • Send Images
  • Send Videos
  • Send Stickers
  • Send Locations
  • Send Location Request
  • Send Contacts
  • Send Lists
  • Send Buttons
  • Send Multi Product Message
  • Send Single Product
  • Upload media resources to WhatsApp servers
  • Download media resources from WhatsApp servers
  • Mark messages as read
  • React to a Message
  • Get/Update Business Profile
  • Webhook verification
  • Webhook notifications

Getting Help

Migration to v2

Please see UPGRADE for more information on how to upgrade to v2.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

composer unit-test

You also can run tests making real calls to the WhastApp Clou API. Please put your testing credentials on WhatsAppCloudApiTestConfiguration file.

composer integration-test

Contributing

Please see CONTRIBUTING for details.

License

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

Disclaimer

This package is not officially maintained by Facebook. WhatsApp and Facebook trademarks and logos are the property of Meta Platforms, Inc.

whatsapp-cloud-api's People

Contributors

aalbarca avatar aindot avatar angelomelonas avatar arneee avatar boynet avatar dazza-dev avatar dependabot[bot] avatar derrickobedgiu1 avatar donmbelembe avatar horatiua avatar ianrothmann avatar jfradj avatar jpsilvaa avatar limsenkeat avatar pravnyadv avatar robertripoll avatar vicenterusso avatar winkelco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

whatsapp-cloud-api's Issues

The type of message is not explicit

image

Hello

I was looking in the doc if there was any method that would allow to explicitly extract the type of message.

I get very confused when capturing a Media type message, since a Media type message can be an Image, a video, an audio, etc.

When processing these types I can't capture the specific type of message

I would really appreciate your help with this issue Alex Albarca @aalbarca

PHP Fatal error: Uncaught Netflie\WhatsAppCloudApi\Response\ResponseException

Hello,
I've observed a glitch in the list message functionality but I can't seem to trace the line throwing this error.
Apparently, all the fields are working fine except the footer for the LIST Message. It looks like you made it compulsory not to be NULL but the DOC has it as an Optional field. When I pass in the footer value I get the success message but when I don't I get an error message. Have a look at it below:

[03-Feb-2023 20:07:06 UTC] PHP Fatal error:  Uncaught Netflie\WhatsAppCloudApi\Response\ResponseException in /***********/vendor/netflie/whatsapp-cloud-api/src/Response.php:150
Stack trace:
#0 /*************/vendor/netflie/whatsapp-cloud-api/src/Client.php(62): Netflie\WhatsAppCloudApi\Response->throwException()
#1 /****************/vendor/netflie/whatsapp-cloud-api/src/WhatsAppCloudApi.php(278): Netflie\WhatsAppCloudApi\Client->sendMessage()
#2 /**********/public_html/*******/test.php(29): Netflie\WhatsAppCloudApi\WhatsAppCloudApi->sendList()
#3 {main}
  thrown in /*************/vendor/netflie/whatsapp-cloud-api/src/Response.php on line 150

I'm hoping the asterisks won't affect your identification of the issue as I did it to protect the path to my online directory
The error is for List Messages feature only

Error

build templates with parameters
Message: Class 'Component' not found

Can I make other users participate in the conversation?

I'm a backend devleoper, and after I have used my phone number as a Whatsapp Cloud API, I cannot seem to access it through my phone whatsapp application.

So I was wondering if I can use this PHP API to grant access to my client to see his customers interactions with the conversation? And also reply to them?

Thanks

Send message not working

Hello, i tried to use the class and send message but nothing happen and im not receiving any message.
i installed using composer and then include the class then i have this code

$whatsapp_cloud_api = new WhatsAppCloudApi([
'from_phone_number_id' => 'xx',
'access_token' => 'xx',
]);

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

am i wrong? btw i used the temporary token

How to install this package in Laravel?

When I run the composer command, I get those errors:

Info from https://repo.packagist.org: #StandWithUkraine
Using version ^1.3 for netflie/whatsapp-cloud-api
./composer.json has been updated
Running composer update netflie/whatsapp-cloud-api
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires netflie/whatsapp-cloud-api ^1.3 -> satisfiable by netflie/whatsapp-cloud-api[1.3.0].
    - netflie/whatsapp-cloud-api 1.3.0 requires guzzlehttp/guzzle ^7.0 -> found guzzlehttp/guzzle[dev-master, 7.0.0-beta.1, ..., 7.5.x-dev (alias of dev-master)] but it conflicts with your root composer.json require (^6.3).

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require netflie/whatsapp-cloud-api:*" to figure out if any version is installable, or "composer require netflie/whatsapp-cloud-api:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

How do we send/receive group messages?

Hello,

I'm new to this library (and whatsapp cloud api in general). I just want to know how to get notifications when a new message is sent in a group which includes the Whatsapp number linked to cloud api? Similarly, how to send a message to such groups?

Thanks!

Como validar conexión

Hola.

Cuando realizamos la conexión con:
$whatsapp_cloud_api = new WhatsAppCloudApi([ 'from_phone_number_id' => 'your-configured-from-phone-number-id', 'access_token' => 'your-facebook-whatsapp-application-token', ]);

¿Como podemos verificar que la conexión fue exitosa?

Unknown error

Hi am using the basic example for sendMessage but am getting this error which am not sure what is wrong

[2023-02-02 12:46:32] production.ERROR: {"exception":"[object] (Netflie\WhatsAppCloudApi\Response\ResponseException(code: 0): at /var/www/staging.loans/vendor/netflie/whatsapp-cloud-api/src/Response.php:150)
[stacktrace]
#0 /var/www/staging.loans/vendor/netflie/whatsapp-cloud-api/src/Client.php(62): Netflie\WhatsAppCloudApi\Response->throwException()
#1 /var/www/staging.loans/vendor/netflie/whatsapp-cloud-api/src/WhatsAppCloudApi.php(73): Netflie\WhatsAppCloudApi\Client->sendMessage()
#2 /var/www/staging.loans/app/Http/Controllers/WhatsappController.php(34): Netflie\WhatsAppCloudApi\WhatsAppCloudApi->sendTextMessage()
#3 /var/www/staging.loans/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): App\Http\Controllers\WhatsappController->index()
#4 /var/www/staging.loans/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\Routing\Controller->callAction()
#5 /var/www/staging.loans/vendor/laravel/framework/src/Illuminate/Routing/Route.php(262): Illuminate\Routing\ControllerDispatcher->dispatch()
#6 /var/www/staging.loans/vendor/laravel/framework/src/Illuminate/Routing/Route.php(205): Illuminate\Routing\Route->runController()
#7 /var/www/staging.loans/vendor/laravel/framework/src/Illuminate/Routing/Router.php(721): Illuminate\Routing\Route->run()
#8 /var/www/staging.loans/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Routing\Router->Illuminate\Routing\{closure}()

How can we receive messages

Hey, Netfile can you please help me ?
I'm able to send all types of messages but i cannot receive messages please help.

Manage Media not available

Hello Dear Friends,

As I am testing this code from last 10 to 15 days, but I didnt found the way to download media or Get Media Id from API.

That would be great if you this as a part of this plugin.

I have created the code to pull media which is sent by users to us + I have downloaded that media to local system.

I want that someone add these code in this repository

Missing parameters in Media Object Type

Hello,
I've been ignoring this minor issue of missing parameters in the media object I think because I haven't been frequently testing and using it as my main focus was on Text type. But I can confirm that there are missing parameters the object isn't returning for the media object. Below are examples of the cases:

CASE 1 FOR NORMAL DUMP:

{
    "object": "whatsapp_business_account",
    "entry": [
        {
            "id": "100822442994608",
            "changes": [
                {
                    "value": {
                        "messaging_product": "whatsapp",
                        "metadata": {
                            "display_phone_number": "**********",
                            "phone_number_id": "***********"
                        },
                        "contacts": [
                            {
                                "profile": {
                                    "name": "De Rick"
                                },
                                "wa_id": "25********"
                            }
                        ],
                        "messages": [
                            {
                                "from": "25*********",
                                "id": "wamid.HBgMMjU2NzQyMDMwNDAzFQIAEhgWM0VCMDlGNkEzQTI2REUyN0NGQzVCQwA=",
                                "timestamp": "1687370616",
                                "type": "document",
                                "document": {
                                    "filename": "Packet Tracer Guide.docx",
                                    "mime_type": "application\/vnd.openxmlformats-officedocument.wordprocessingml.document",
                                    "sha256": "EHebbB0CwZndBi9LvLB5PQVYPhHdJsnDxzmRpUv+KkY=",
                                    "id": "184921594550426"
                                }
                            }
                        ]
                    },
                    "field": "messages"
                }
            ]
        }
    ]
}

CASE 1 FOR LIB DUMP

Netflie\WhatsAppCloudApi\WebHook\Notification\Media Object
(
    [image_id] => 184921594550426
    [mime_type] => application/vnd.openxmlformats-officedocument.wordprocessingml.document
    [caption] => 
    [customer] => Netflie\WhatsAppCloudApi\WebHook\Notification\Support\Customer Object
        (
            [id] => **********
            [name] => De Rick
            [phone_number] => 25**********
        )

    [id] => wamid.HBgMMjU2NzQyMDMwNDAzFQIAEhgWM0VCMDlGNkEzQTI2REUyN0NGQzVCQwA=
    [business] => Netflie\WhatsAppCloudApi\WebHook\Notification\Support\Business Object
        (
            [phone_number_id] => ************
            [phone_number] => **********
        )

    [received_at] => DateTimeImmutable Object
        (
            [date] => 2023-06-21 21:03:36.000000
            [timezone_type] => 3
            [timezone] => Africa/Kampala
        )

)

The tests I made all include the "filename" parameter and "sha256". Is it possible to include these parameters in future versions of the LIB? Thank you. I'm always ready to test and provide immediate feedback.

No puedo enviar a números telefónicos dinámicos

Estoy intentando que el código lo envíe al número de teléfono que el usuario ingrese. Este número se almacena en una variable.

image

En el error si me lee el valor ingresado, pero no me lo toma como válido

image

No se me ocurre otra forma de como hacer que el código funcione.
(La última línea está repetida porque lo tengo que enviar a varios usuarios, si funciona, pero no con la variable)

Error when emoji is unselected

When a message is reacted with emoji and then remove reaction "emoji" field not exists

With request emoji:

array (
  'object' => 'whatsapp_business_account',
  'entry' => 
  array (
    0 => 
    array (
      'id' => 'xxxxx',
      'changes' => 
      array (
        0 => 
        array (
          'value' => 
          array (
            'messaging_product' => 'whatsapp',
            'metadata' => 
            array (
              'display_phone_number' => 'xxxxx',
              'phone_number_id' => 'xxxxxx',
            ),
            'contacts' => 
            array (
              0 => 
              array (
                'profile' => 
                array (
                  'name' => 'xxxxx',
                ),
                'wa_id' => 'xxxxxx',
              ),
            ),
            'messages' => 
            array (
              0 => 
              array (
                'from' => 'xxxxxx',
                'id' => 'wamid',
                'timestamp' => '1695199352',
                'type' => 'reaction',
                'reaction' => 
                array (
                  'message_id' => 'wamid',
                  'emoji' => '😮',
                ),
              ),
            ),
          ),
          'field' => 'messages',
        ),
      ),
    ),
  ),
)  

not exists request emoji:

array (
  'object' => 'whatsapp_business_account',
  'entry' => 
  array (
    0 => 
    array (
      'id' => 'XXXXXXX',
      'changes' => 
      array (
        0 => 
        array (
          'value' => 
          array (
            'messaging_product' => 'whatsapp',
            'metadata' => 
            array (
              'display_phone_number' => 'XXXXX',
              'phone_number_id' => 'XXXXXX',
            ),
            'contacts' => 
            array (
              0 => 
              array (
                'profile' => 
                array (
                  'name' => 'XXXX',
                ),
                'wa_id' => 'XXXXX',
              ),
            ),
            'messages' => 
            array (
              0 => 
              array (
                'from' => 'XXXXXX',
                'id' => 'wamid.,
                'timestamp' => '1695199360',
                'type' => 'reaction',
                'reaction' => 
                array (
                  'message_id' => 'wamid.',
                ),
              ),
            ),
          ),
          'field' => 'messages',
        ),
      ),
    ),
  ),
)  

Log error

local.ERROR: Undefined array key "emoji" {"exception":"[object] (ErrorException(code: 0): Undefined array key "emoji" at /Volumes/Dev/code/herflor/ecosystem/herflorti/vendor/netflie/whatsapp-cloud-api/src/WebHook/Notification/MessageNotificationFactory.php:29)

Download is not working

Discussed in #101

Originally posted by faizanpmba April 3, 2023
Following is my partial code but for some reason image is sending just fine but when I try to download the receiving image it just don't work at all and doing nothing. I expected for it to get downloaded somewhere in my directory and nothing is happening down there. Please let me know how to save the file into the directory?

require 'vendor/autoload.php';

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

$waimgId = $webhookData["entry"][0]["changes"][0]["value"]["messages"][0]["image"]["id"];
$whatsapp_cloud_api->sendTextMessage($senderNumber,  $waimgId);
$media_id = new MediaObjectID($waimgId);
$whatsapp_cloud_api->downloadMedia($media_id);

Webhook notifications 2.0 updated new version.

after your upgrading netflie, try to get notification ,

the Webhook verification is working good.

Webhook notifications not working.

kindly to the needful to solve this issue to guide ...thanks
below code :

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();

fwrite(STDOUT, print_r($webhook->read(json_decode($payload, true)), true) . "\n");

Send audio voice

Is it possible to send a voice audio instead of the attachment audio?

Captura de Tela 2022-10-11 às 14 55 00

I do not receive a message

Hi, I'm trying to receive messages, but I don't get anything, I already followed the steps you mentioned.
I do not mark any error,
I work it in php 8.1 with laravel 9

My version curl is
curl 7.68.0 (x86_64-pc-linux-gnu) libcurl/7.68.0 OpenSSL/1.1.1f zlib/1.2.11 brotli/1.0.7 libidn2/2.3.0 libpsl/0.21.0 (+libidn2/2.2.0) libssh/0.9.3/openssl/zlib nghttp2/1.40.0 librtmp/2.3
Release-Date: 2020-01-08
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp scp sftp smb smbs smtp smtps telnet tftp
Features: AsynchDNS brotli GSS-API HTTP2 HTTPS-proxy IDN IPv6 Kerberos Largefile libz NTLM NTLM_WB PSL SPNEGO SSL TLS-SRP UnixSockets

Send Reply to Text Message

According to the WhatsApp API documentation, it is possible to send a response message by including the context > message_id parameter in the request body. How to do this with your library?

{ "messaging_product": "whatsapp", "recipient_type": "individual", "to": "{{Recipient-Phone-Number}}", "context": { "message_id": "<MSGID_OF_PREV_MSG>" }, "type": "text", "text": { "preview_url": false, "body": "<TEXT_MSG_CONTENT>" } }

Subir archivos a Whatsapp Cloud

Hola.

La librería es capaz de enviar archivos median link o mediante el id que proporciona whatsapp cloud, pero... ¿tenéis algun ejemplo de como enviar el archivo para alojarlo en whatsapp cloud y recibir el id?.

Gracias.

Duplicate messages

Hi
Thanks for this nice lib. Sadly since moving from test to prod and all messages i send are sent twice...

Does anyone how to fix this issue?

Thanks in advance.

Kind regards

No puedo enviar mensaje

Estoy intentando usar el SDK, ya confirmé y si se envían los mensajes por la consola de Facebook, pero por mi web me aparecen distintos errores

Este es el código incrustado como está en la documentación
image

y este es el error
image

Si modifico para que encuentre el archivo:
image

Entonces me aparece lo siguiente:
image

Ya intente varias cosas, ya instale todo por composer y aun así no lo encuentra, descargue los archivos y los ingresé a la carpeta de mi proyecto y noté que no está la carpeta "vendor" y "autoload.php"

Cambie el nombre de la carpeta que decia whatsapp-app-cloud-api-main a WhatsAppCloudApi y me dice que no encuentra la clase
image

Template name does not exist in the translation

Hi,

I managed to use this package and all it's work, but after Facebook upgrade their API, I got the following error when I try to send a template!

Template name does not exist in the translation

I created new templates, and they all approved with the appropriate language but when I tried to test them, the error shows.

Any help, please?

error showing

Message: syntax error, unexpected 'WhatsAppCloudApiApp' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

Filename: /var/www/html/application/third_party/whatsapp/vendor/netflie/whatsapp-cloud-api/src/WhatsAppCloudApi.php

Line Number: 39

template message counld't be send ?

i try to send whatsapp template like header "documents"
body

"string text"

not working your code.

kindly let me know how to send message thorugh whatsapp template media with body content.

WebHook Verification?

Hello.

Does this library have verification to connect the Facebook WebHook? If so, how would it be?

Thanks.

Fecha recepción en el WebHook

Hola.

Tengo una duda que no consigo entender, aún leyendo la documentación. Por favor me gustaría saber si pueden aclararmela.

Cuando un usuario manda un mensaje este llega a Whatsapp y nos lo envía vía POST, y lo recibimos con la clase WebHook.

La documentación oficial dice que existen 3 fechas: delivered, read y sent.

Cuando recibimos el mensaje y lo queremos guardar en nuestra BBDD, el campo timestamp del mensaje lo recuperamos con la función receivedAt() ¿correcto?.

Pero no me queda claro si esa fecha pertenece a "sent" o a "delivered", o a cual.

¿Sabrían aclararme esta duda?.

Otra cosa que veo es que la fecha recibida con receivedAt() es una clase de DateTimeInmutable, donde también tenemos la zona horaria. Entiendo es la zona horaria desde donde se envió el mensaje, ¿Correcto?.

Nota: Escribo en Español por que creo que son españoles ¿verdad?.

Soy programador de FacturaScripts, un programa web de contabilidad y ERP. Mi intención es integrar su librería con nuestro software, para que puedan usarlo más usuario del sistema. Es un trabajo algo complejo con muchas opciones, las cuales en ocasiones tengo varias dudas a resolver y espero puedan ir ayudandome.

Muchas gracias, un saludo.

can

can't send massage

PHP Fatal error: Uncaught UnexpectedValueException: Value 'user_initiated'

Discussed in #76

Originally posted by derrickobedgiu1 January 29, 2023
The new version is having a typo somewhere:
PHP Fatal error: Uncaught UnexpectedValueException: Value 'user_initiated' is not part of the enum Netflie\WhatsAppCloudApi\WebHook\Notification\Support\ConversationType
Apparently instead of user_initiated, it's having customer_initiated
PATH: Netflie\WhatsAppCloudApi\WebHook\Notification\Support\ConversationType
I was using the previous version to send messages but all status updates about the conversation type the user initiated have been of type "user_initiated", even though the DOC says customer_initiated. Maybe these occur for certain status update types I haven't used yet

Sample status updates webhook payload I always receive :

{
    "object": "whatsapp_business_account",
    "entry": [
        {
            "id": "114392761549803",
            "changes": [
                {
                    "value": {
                        "messaging_product": "whatsapp",
                        "metadata": {
                            "display_phone_number": "256*********",
                            "phone_number_id": "112************"
                        },
                        "statuses": [
                            {
                                "id": "wamid.HBgMMjU2NzQyMDMwNDAzFQIAERgSQTYzODBCOTQ5RThGRDUzQTFEAA==",
                                "status": "sent",
                                "timestamp": "1674902805",
                                "recipient_id": "2567********",
                                "conversation": {
                                    "id": "f5e244bb2b0e4ee8065116ff20f5fe76",
                                    "expiration_timestamp": "1674926460",
                                    "origin": {
                                        "type": "user_initiated"
                                    }
                                },
                                "pricing": {
                                    "billable": true,
                                    "pricing_model": "CBP",
                                    "category": "user_initiated"
                                }
                            }
                        ]
                    },
                    "field": "messages"
                }
            ]
        }
    ]
}

feature to access all templates

for the next update, can there be a feature to access all templates, request templates, and add new numbers.

I think this will be very helpful

Fatal error: Uncaught Error: Class "Component"

Fatal error: Uncaught Error: Class "Component" not found in C:\xampp\htdocs\wpnew\b\whatsapp-cloud-api\test.php:49 Stack trace: #0 {main} thrown in C:\xampp\htdocs\wpnew\b\whatsapp-cloud-api\test.php on line 49

Error when message of type user_changed_number is received.

Error processing the webhook when a user changes its phone number.

Payload

Note: Personal data has been redacted with X

{
    "object": "whatsapp_business_account",
    "entry": [
        {
            "id": "108XXXXXXXXXXXX",
            "changes": [
                {
                    "value": {
                        "messaging_product": "whatsapp",
                        "metadata": {
                            "display_phone_number": "573XXXXXXXXX",
                            "phone_number_id": "10XXXXXXXXXXXXX"
                        },
                        "messages": [
                            {
                                "from": "573XXXXXXXXX",
                                "id": "wamid.HBgMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX==",
                                "timestamp": "1687834799",
                                "system": {
                                    "body": "User A changed from \\u200e573XXXXXXXXX to 573XXXXXXXXX\\u200e",
                                    "wa_id": "573XXXXXXXXX",
                                    "type": "user_changed_number"
                                },
                                "type": "system"
                            }
                        ]
                    },
                    "field": "messages"
                }
            ]
        }
    ]
}

Stack trace

exception: 'Undefined index: customer',

#0 /app/vendor/netflie/whatsapp-cloud-api/src/WebHook/Notification/MessageNotificationFactory.php(99): yii\\base\\ErrorHandler->handleError(8, \'Undefined index...\', \'/app/vendor/net...\', 99, Array)
#1 /app/vendor/netflie/whatsapp-cloud-api/src/WebHook/Notification/MessageNotificationFactory.php(9): Netflie\\WhatsAppCloudApi\\WebHook\\Notification\\MessageNotificationFactory->buildMessageNotification(Array, Array)
#2 /app/vendor/netflie/whatsapp-cloud-api/src/WebHook/NotificationFactory.php(29): Netflie\\WhatsAppCloudApi\\WebHook\\Notification\\MessageNotificationFactory->buildFromPayload(Array, Array, Array)
#3 /app/vendor/netflie/whatsapp-cloud-api/src/WebHook.php(32): Netflie\\WhatsAppCloudApi\\WebHook\\NotificationFactory->buildFromPayload(Array)
#4 /app/modules/Whatsapp/controllers/DefaultController.php(44): Netflie\\WhatsAppCloudApi\\WebHook->read(Array)
...

message instance retrieval / PSR HTTP message in VerificationRequest

thank you for this great project!

I have two suggestions/RFC's and would like to find out if this is supported.

  1. public getter for $message in Netflie\WhatsAppCloudApi\Request\MessageRequest:
    public function getMessage(): Message {
        return $this->message;
    }

Background: retrieving the message instance enables to log what is sent to the API.

  1. letting Netflie\WhatsAppCloudApi\WebHook\VerificationRequest return Psr\Http\Message\ResponseInterface instead of emitting the HTTP codes.
public function validate(array $payload): ResponseInterface
    {
        $mode = $payload['hub_mode'] ?? null;
        $token = $payload['hub_verify_token'] ?? null;
        $challenge = $payload['hub_challenge'] ?? '';

        if ('subscribe' !== $mode || $token !== $this->verify_token) {
            return new EmptyResponse(403);
        }

        return new TextResponse($challenge, 200);
    }

the EmptyResponse and TextResponse classes have to be implemented.

I would be ready to implement this if it is welcome. Please let me know what you think.

Curl error

local.ERROR: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://graph.facebook.com/v15.0/108949415252785/messages {"exception":"[object] (GuzzleHttp\Exception\RequestException(code: 0): cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://graph.facebook.com/v15.0/108949415252785/messages at D:\CODE\bumi_staging\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:211)
[stacktrace]

Am getting this error when receiving webhook message from whatsapp

No se mandan mensajes individuales sin plantilla

Hola.

Estoy probando la librería pero me es imposible enviar un mensaje individual, solo me funciona si uso una plantilla. Adjunto debajo mensaje de respuesta al enviar un mensaje individual usando sendTextMessage(), el mensaje nunca llega. ¿alguna idea?. Gracias.

ERROR: Argument #1 ($content) must be of type ?string, Netflie\WhatsAppCloudApi\Response given

I got this error on Laravel 9.52.4 and PHP 8.1, this is my code:

        $this->WhatsAppCloudApi = new WhatsAppCloudApi([
            'from_phone_number_id' => 'xxx',
            'access_token' => 'xxx',
        ]);

        $header = array();
        $body = array();
        $buttons = array();

        $body = [
            [
                'type' => 'text',
                'text' => '*Daniel*',
            ],
        ];

        $components = new Component($header, $body, $buttons);
        $response = $this->WhatsAppCloudApi->sendTemplate($numero, 'can_we_talk', 'pt_BR', $components);
[2023-03-23 13:50:43] local.ERROR: Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, Netflie\WhatsAppCloudApi\Response given, called in /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Http/Response.php on line 72 {"userId":1,"exception":"[object] (TypeError(code: 0): Symfony\\Component\\HttpFoundation\\Response::setContent(): Argument #1 ($content) must be of type ?string, Netflie\\WhatsAppCloudApi\\Response given, called in /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Http/Response.php on line 72 at /Users/dmontessi/Sites/caixa/vendor/symfony/http-foundation/Response.php:396)

[stacktrace]
#0 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Http/Response.php(72): Symfony\\Component\\HttpFoundation\\Response->setContent(Object(Netflie\\WhatsAppCloudApi\\Response))
#1 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Http/Response.php(35): Illuminate\\Http\\Response->setContent(Object(Netflie\\WhatsAppCloudApi\\Response))
#2 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Routing/Router.php(906): Illuminate\\Http\\Response->__construct(Object(Netflie\\WhatsAppCloudApi\\Response), 200, Array)
#3 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Routing/Router.php(875): Illuminate\\Routing\\Router::toResponse(Object(Illuminate\\Http\\Request), Object(Netflie\\WhatsAppCloudApi\\Response))
#4 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Routing/Router.php(798): Illuminate\\Routing\\Router->prepareResponse(Object(Illuminate\\Http\\Request), Object(Netflie\\WhatsAppCloudApi\\Response))
#5 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#6 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(50): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#7 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Routing\\Middleware\\SubstituteBindings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#8 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(44): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#9 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Auth\\Middleware\\Authenticate->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#10 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(78): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#11 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#12 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#13 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#14 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(121): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#15 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(64): Illuminate\\Session\\Middleware\\StartSession->handleStatefulRequest(Object(Illuminate\\Http\\Request), Object(Illuminate\\Session\\Store), Object(Closure))
#16 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Session\\Middleware\\StartSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#17 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#18 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#19 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(67): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#20 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Cookie\\Middleware\\EncryptCookies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#21 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#22 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Routing/Router.php(799): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#23 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Routing/Router.php(776): Illuminate\\Routing\\Router->runRouteWithinStack(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request))
#24 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Routing/Router.php(740): Illuminate\\Routing\\Router->runRoute(Object(Illuminate\\Http\\Request), Object(Illuminate\\Routing\\Route))
#25 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Routing/Router.php(729): Illuminate\\Routing\\Router->dispatchToRoute(Object(Illuminate\\Http\\Request))
#26 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(190): Illuminate\\Routing\\Router->dispatch(Object(Illuminate\\Http\\Request))
#27 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}(Object(Illuminate\\Http\\Request))
#28 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#29 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull.php(31): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#30 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#31 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(21): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#32 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TrimStrings.php(40): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#33 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\TrimStrings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#34 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#35 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#36 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/PreventRequestsDuringMaintenance.php(86): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#37 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Foundation\\Http\\Middleware\\PreventRequestsDuringMaintenance->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#38 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Http/Middleware/HandleCors.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#39 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Http\\Middleware\\HandleCors->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#40 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Http/Middleware/TrustProxies.php(39): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#41 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(180): Illuminate\\Http\\Middleware\\TrustProxies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#42 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(116): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#43 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(165): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#44 /Users/dmontessi/Sites/caixa/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(134): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#45 /Users/dmontessi/Sites/caixa/public/index.php(52): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#46 {main}
"} 

New types of conversation category break the webhook processing.

Facebook rolled out today June 1 conversation based pricing and with it the category types.

https://developers.facebook.com/docs/whatsapp/updates-to-pricing

Therefore it started sengind this data in the webhooks:

{
    "object": "whatsapp_business_account",
    "entry": [
        {
            "id": "108536708899139",
            "changes": [
                {
                    "value": {
                        "messaging_product": "whatsapp",
                        "metadata": {
                            // redacted
                            "display_phone_number": "5XXXXXXXXXXX",
                            // redacted
                            "phone_number_id": "1XXXXXXXXXXXXXX"
                        },
                        "statuses": [
                            {
                                "id": "wamid.HBgMNTczMjEyMjMyNzczFQIAERgSMzE3RUQ4MTdDQzU2OTZDRTRDAA==",
                                "status": "delivered",
                                "timestamp": "1685626673",
                                // redacted
                                "recipient_id": "5XXXXXXXXXXX",
                                "conversation": {
                                    "id": "d488be6b630353e08249383a9a699f64",
                                    "origin": {
                                        "type": "authentication"
                                    }
                                },
                                "pricing": {
                                    "billable": true,
                                    "pricing_model": "CBP",
                                    "category": "authentication"
                                }
                            }
                        ]
                    },
                    "field": "messages"
                }
            ]
        }
    ]
}

This makes the webhook->read() throw erros not recognizing the type of conversation.


[2023-06-01 13:37:59][LOGGED_OUT][req-64789f37982b5][error][UnexpectedValueException] UnexpectedValueException: Value 
'authentication' is not part of the enum Netflie\WhatsAppCloudApi\WebHook\Notification\Support\ConversationType in /ap
p/vendor/myclabs/php-enum/src/Enum.php:245
Stack trace:
#0 /app/vendor/myclabs/php-enum/src/Enum.php(73): MyCLabs\Enum\Enum::assertValidValueReturningKey('authentication')
#1 /app/vendor/netflie/whatsapp-cloud-api/src/WebHook/Notification/Support/Conversation.php(16): MyCLabs\Enum\Enum->__
construct('authentication')
#2 /app/vendor/netflie/whatsapp-cloud-api/src/WebHook/Notification/StatusNotificationFactory.php(21): Netflie\WhatsApp
CloudApi\WebHook\Notification\Support\Conversation->__construct('d488be6b630353e...', 'authentication', NULL)
#3 /app/vendor/netflie/whatsapp-cloud-api/src/WebHook/NotificationFactory.php(33): Netflie\WhatsAppCloudApi\WebHook\No
tification\StatusNotificationFactory->buildFromPayload(Array, Array)
#4 /app/vendor/netflie/whatsapp-cloud-api/src/WebHook.php(32): Netflie\WhatsAppCloudApi\WebHook\NotificationFactory->b
uildFromPayload(Array)
#5 /app/modules/Whatsapp/controllers/DefaultController.php(44): Netflie\WhatsAppCloudApi\WebHook->read(Array)

Facing issue with Undefined variable: whatsapp_cloud_api

Notice: Undefined variable: whatsapp_cloud_api in E:\xampp_7.4.6\xampp\htdocs\whatsapp_api\wa_cloud_api\index.php on line 14

Fatal error: Uncaught Error: Call to a member function sendDocument() on null in E:\xampp_7.4.6\xampp\htdocs\whatsapp_api\wa_cloud_api\index.php:14 Stack trace: #0 {main} thrown in E:\xampp_7.4.6\xampp\htdocs\whatsapp_api\wa_cloud_api\index.php on line 14

A forwarded message does not contain an ID in the message context

First of all, thank you for this excellent library!

I would like to report a bug that I found. If a voice note (media message) is forwarded, it does not contain the id field in $message['context']['id'], resulting in the following exception:

{
  "message": "Uncaught PHP Exception TypeError: \"Netflie\\WhatsAppCloudApi\\WebHook\\Notification\\Support\\Context::__construct(): Argument #1 ($replying_to_message_id) must be of type string, null given, called in /app/vendor/netflie/whatsapp-cloud-api/src/WebHook/Notification/MessageNotificationFactory.php on line 131\" at /app/vendor/netflie/whatsapp-cloud-api/src/WebHook/Notification/Support/Context.php line 13",
  "context": {
    "exception": {
      "class": "TypeError",
      "message": "Netflie\\WhatsAppCloudApi\\WebHook\\Notification\\Support\\Context::__construct(): Argument #1 ($replying_to_message_id) must be of type string, null given, called in /app/vendor/netflie/whatsapp-cloud-api/src/WebHook/Notification/MessageNotificationFactory.php on line 131",
      "code": 0,
      "file": "/app/vendor/netflie/whatsapp-cloud-api/src/WebHook/Notification/Support/Context.php:13"
    }
  }
}

Would a solution be to make the id field in the Context object optional? Then the code would be:

$notification->withContext(new Support\Context(
    $message['context']['id'] ?? null,
    $message['context']['forwarded'] ?? false,
    $referred_product ?? null
));

I'd be happy to open a pull request for this 👍🏼

PHP Fatal error: Uncaught UnexpectedValueException: Value 'user_initiated'

Discussed in #76

Originally posted by derrickobedgiu1 January 29, 2023
The new version is having a typo somewhere:
PHP Fatal error: Uncaught UnexpectedValueException: Value 'user_initiated' is not part of the enum Netflie\WhatsAppCloudApi\WebHook\Notification\Support\ConversationType
Apparently instead of user_initiated, it's having customer_initiated
PATH: Netflie\WhatsAppCloudApi\WebHook\Notification\Support\ConversationType

Support php version 7.0?

Any possibility to make a release that can run on php version 7.0? Our system runs on this version..

Great work!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.