├── .editorconfig ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json └── src ├── Components ├── Button.php └── Card.php ├── Enums ├── AttachmentType.php ├── ButtonType.php ├── ImageAspectRatioType.php ├── MessageTag.php ├── MessagingType.php ├── NotificationType.php └── RecipientType.php ├── Exceptions ├── CouldNotCreateButton.php ├── CouldNotCreateCard.php ├── CouldNotCreateMessage.php └── CouldNotSendNotification.php ├── Facebook.php ├── FacebookChannel.php ├── FacebookMessage.php ├── FacebookServiceProvider.php └── Traits └── HasButtons.php /.editorconfig: -------------------------------------------------------------------------------- 1 | ; This file is for unifying the coding style for different editors and IDEs. 2 | ; More information at http://editorconfig.org 3 | 4 | root = true 5 | 6 | [*] 7 | charset = utf-8 8 | indent_size = 4 9 | indent_style = space 10 | end_of_line = lf 11 | insert_final_newline = true 12 | trim_trailing_whitespace = true 13 | 14 | [*.md] 15 | trim_trailing_whitespace = false 16 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file 4 | 5 | ## 1.0.0 - 201X-XX-XX 6 | 7 | - initial release 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | 3 | Copyright (c) Irfaq Syed 4 | 5 | > Permission is hereby granted, free of charge, to any person obtaining a copy 6 | > of this software and associated documentation files (the "Software"), to deal 7 | > in the Software without restriction, including without limitation the rights 8 | > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | > copies of the Software, and to permit persons to whom the Software is 10 | > furnished to do so, subject to the following conditions: 11 | > 12 | > The above copyright notice and this permission notice shall be included in 13 | > all copies or substantial portions of the Software. 14 | > 15 | > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | > THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Facebook Notifications Channel for Laravel 2 | 3 | [![Join PHP Chat][ico-phpchat]][link-phpchat] 4 | [![Chat on Telegram][ico-telegram]][link-telegram] 5 | [![Latest Version on Packagist][ico-version]][link-packagist] 6 | [![Software License][ico-license]](LICENSE.md) 7 | [![Quality Score][ico-code-quality]][link-code-quality] 8 | [![Total Downloads][ico-downloads]][link-packagist] 9 | 10 | This package makes it easy to send notifications using the [Facebook Messenger](https://developers.facebook.com/docs/messenger-platform/product-overview) with Laravel. 11 | 12 | ## Contents 13 | 14 | - [Installation](#installation) 15 | - [Setting up your Facebook Bot](#setting-up-your-facebook-bot) 16 | - [Usage](#usage) 17 | - [Available Message methods](#available-message-methods) 18 | - [Available Button methods](#available-button-methods) 19 | - [Available Card methods](#available-card-methods) 20 | - [Contributing](#contributing) 21 | - [Credits](#credits) 22 | - [License](#license) 23 | 24 | 25 | ## Installation 26 | 27 | You can install the package via composer: 28 | 29 | ``` bash 30 | composer require laravel-notification-channels/facebook 31 | ``` 32 | 33 | ## Setting up your Facebook Bot 34 | 35 | Follow the [Getting Started](https://developers.facebook.com/docs/messenger-platform/quickstart) guide in order to create a Facebook Messenger app, a Facebook page and a page token, which is connecting both. 36 | 37 | Next we need to add this token to our Laravel configurations. Create a new Facebook section inside `config/services.php` and place the page token there: 38 | 39 | ```php 40 | // config/services.php 41 | ... 42 | 'facebook' => [ 43 | 'page-token' => env('FACEBOOK_PAGE_TOKEN', 'YOUR PAGE TOKEN HERE'), 44 | 45 | // Optional - Omit this if you want to use default version. 46 | 'version' => env('FACEBOOK_GRAPH_API_VERSION', '4.0') 47 | 48 | // Optional - If set, the appsecret_proof will be sent to verify your page-token. 49 | 'app-secret' => env('FACEBOOK_APP_SECRET', '') 50 | ], 51 | ... 52 | ``` 53 | 54 | ## Usage 55 | 56 | Let's take an invoice-paid-notification as an example. 57 | You can now use the Facebook channel in your `via()` method, inside the InvoicePaid class. The `to($userId)` method defines the Facebook user, you want to send the notification to. 58 | 59 | Based on the details you add (text, attachments etc.) will determine automatically the type of message to be sent. For example if you only add `text()` then it will be a basic message; using `attach()` will turn this into a attachment message. Having `buttons` or `cards` will change this to the `Button Template` and `Generic Template` respectivily 60 | 61 | ```php 62 | use NotificationChannels\Facebook\FacebookChannel; 63 | use NotificationChannels\Facebook\FacebookMessage; 64 | use NotificationChannels\Facebook\Components\Button; 65 | use NotificationChannels\Facebook\Enums\NotificationType; 66 | 67 | use Illuminate\Notifications\Notification; 68 | 69 | class InvoicePaid extends Notification 70 | { 71 | public function via($notifiable) 72 | { 73 | return [FacebookChannel::class]; 74 | } 75 | 76 | public function toFacebook($notifiable) 77 | { 78 | $url = url('/invoice/' . $this->invoice->id); 79 | 80 | return FacebookMessage::create() 81 | ->to($notifiable->fb_messenger_user_id) // Optional 82 | ->text('One of your invoices has been paid!') 83 | ->isUpdate() // Optional 84 | ->isTypeRegular() // Optional 85 | // Alternate method to provide the notification type. 86 | // ->notificationType(NotificationType::REGULAR) // Optional 87 | ->buttons([ 88 | Button::create('View Invoice', $url)->isTypeWebUrl(), 89 | Button::create('Call Us for Support!', '+1(212)555-2368')->isTypePhoneNumber(), 90 | Button::create('Start Chatting', ['invoice_id' => $this->invoice->id])->isTypePostback() // Custom payload sent back to your server 91 | ]); // Buttons are optional as well. 92 | } 93 | } 94 | ``` 95 | 96 | The notification will be sent from your Facebook page, whose page token you have configured earlier. Here's a screenshot preview of the notification inside the chat window. 97 | 98 | ![Laravel Facebook Notification Example](https://cloud.githubusercontent.com/assets/1915268/17666125/58d6b66c-631c-11e6-9380-0400832b2e48.png) 99 | 100 | #### Message Examples 101 | 102 | ##### Basic Text Message 103 | 104 | Send a basic text message to a user 105 | ```php 106 | return FacebookMessage::create('You have just paid your monthly fee! Thanks') 107 | ->to($notifiable->fb_messenger_user_id); 108 | ``` 109 | ##### Attachment Message 110 | 111 | Send a file attachment to a user (Example is sending a pdf invoice) 112 | 113 | ```php 114 | return FacebookMessage::create() 115 | ->attach(AttachmentType::FILE, url('invoices/'.$this->invoice->id)) 116 | ->to($notifiable->fb_messenger_user_id); 117 | ``` 118 | 119 | ##### Generic (Card Carousel) Message 120 | 121 | Send a set of cards / items to a user displayed in a carousel (Example is sending a set of links). Note you can also add up to three buttons per card 122 | 123 | ```php 124 | return FacebookMessage::create() 125 | ->to($notifiable->fb_messenger_user_id) // Optional 126 | ->cards([ 127 | Card::create('Card No.1 Title') 128 | ->subtitle('An item description') 129 | ->url('items/'.$this->item[0]->id) 130 | ->image('items/'.$this->item[0]->id.'/image'), 131 | 132 | Card::create('Card No.2 Title') 133 | ->subtitle('An item description') 134 | ->url('items/'.$this->item[1]->id) 135 | ->image('items/'.$this->item[1]->id.'/image') 136 | // could add buttons using ->buttons($array of Button) 137 | ]); 138 | ``` 139 | 140 | ### Routing a message 141 | 142 | You can either send the notification by providing with the page-scoped user id (PSID) of the recipient to the `to($userId)` method like shown in the above example or add a `routeNotificationForFacebook()` method in your notifiable model: 143 | 144 | ```php 145 | ... 146 | /** 147 | * Route notifications for the Facebook channel. 148 | * 149 | * @return int 150 | */ 151 | public function routeNotificationForFacebook() 152 | { 153 | return $this->fb_messenger_user_id; 154 | } 155 | ... 156 | ``` 157 | 158 | ### Available Message methods 159 | 160 | - `to($recipient, $type)`: (string|array) Recipient's page-scoped User `id`, `phone_number`, `user_ref`, `post_id` or `comment_id` (as one of the supported types - Use `Enums\RecipientType` to make it easier). Phone number supported format `+1(212)555-2368`. **NOTE:** Sending a message to phone numbers requires the `pages_messaging_phone_number` permission. Refer [docs](https://developers.facebook.com/docs/messenger-platform/send-api-reference#phone_number) for more information. 161 | - `text('')`: (string) Notification message. 162 | - `isResponse()`: Set `messaging_type` as `RESPONSE`. 163 | - `isUpdate()`: (default) Set `messaging_type` as `UPDATE`. 164 | - `isMessageTag($messageTag)`: (string) Set `messaging_type` as `MESSAGE_TAG`, you can refer and make use of the `NotificationChannels\Facebook\Enums\MessageTag` to make it easier to work with the message tag. 165 | - `attach($attachment_type, $url)`: (AttachmentType, string) An attachment type (IMAGE, AUDIO, VIDEO, FILE) and the url of this attachment 166 | - `buttons($buttons = [])`: (array) An array of "Call to Action" buttons (Created using `NotificationChannels\Facebook\Components\Button::create()`). You can add up to 3 buttons of one of the following types: `web_url`, `postback` or `phone_number`. See Button methods below for more details. 167 | - `cards($cards = [])`: (array) An array of item cards to be displayed in a carousel (Created using `NotificationChannels\Facebook\Components\Card::create()`). You can add up to 10 cards. See Card methods below for more details. 168 | - `notificationType('')`: (string) Push Notification type: `REGULAR` will emit a sound/vibration and a phone notification; `SILENT_PUSH` will just emit a phone notification, `NO_PUSH` will not emit either. You can make use of `NotificationType::REGULAR`, `NotificationType::SILENT_PUSH` and `NotificationType::NO_PUSH` to make it easier to work with the type. This is an optional method, defaults to `REGULAR` type. 169 | - `imageAspectRatio('')`: (string) Image Aspect Ratio if Card with `image_url` present. You can use of `ImageAspectRatioType::SQUARE` or `ImageAspectRatioType::HORIZONTAL`. This is an optional method, defaults to `ImageAspectRatioType::HORIZONTAL` aspect ratio (image should be 1.91:1). 170 | - `isTypeRegular()`: Helper method to create a notification type: `REGULAR`. 171 | - `isTypeSilentPush()`: Helper method to create a notification type: `SILENT_PUSH`. 172 | - `isTypeNoPush()`: Helper method to create a notification type: `NO_PUSH`. 173 | 174 | ### Available Button methods 175 | 176 | - `title('')`: (string) Button Title. 177 | - `data('')`: (string) Button Data - It can be a web url, postback data or a formated phone number. 178 | - `type('')`: (string) Button Type - `web_url`, `postback` or `phone_number`. Use `ButtonType` enumerator for guaranteeing valid values 179 | - `isTypeWebUrl()`: Helper method to create a `web_url` type button. 180 | - `isTypePhoneNumber()`: Helper method to create a `phone_number` type button. 181 | - `isTypePostback()`: Helper method to create a `postback` type button. 182 | 183 | ### Available Card methods 184 | 185 | - `title('')`: (string) Card Title. 186 | - `subtitle('')`: (string) Card Subtitle. 187 | - `url('')`: (string) Card Item Url. 188 | - `image('')`: (string) Card Image Url. Image ratio should be 1.91:1 189 | - `buttons($buttons = [])`: (array) An array of "Call to Action" buttons (Created using `NotificationChannels\Facebook\Components\Button::create()`). You can add up to 3 buttons of one of the following types: `web_url`, `postback` or `phone_number`. See Button methods above for more details. 190 | 191 | ## Contributing 192 | 193 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 194 | 195 | ## Credits 196 | 197 | - [Irfaq Syed][link-author] 198 | - [All Contributors][link-contributors] 199 | 200 | ## License 201 | 202 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 203 | 204 | [ico-phpchat]: https://img.shields.io/badge/Slack-PHP%20Chat-5c6aaa.svg?style=flat-square&logo=slack&labelColor=4A154B 205 | [ico-telegram]: https://img.shields.io/badge/@PHPChatCo-2CA5E0.svg?style=flat-square&logo=telegram&label=Telegram 206 | [ico-version]: https://img.shields.io/packagist/v/laravel-notification-channels/facebook.svg?style=flat-square 207 | [ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square 208 | [ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/laravel-notification-channels/facebook.svg?style=flat-square 209 | [ico-code-quality]: https://img.shields.io/scrutinizer/g/laravel-notification-channels/facebook.svg?style=flat-square 210 | [ico-downloads]: https://img.shields.io/packagist/dt/laravel-notification-channels/facebook.svg?style=flat-square 211 | 212 | [link-phpchat]: https://phpchat.co/?ref=laravel-channel-facebook 213 | [link-telegram]: https://t.me/PHPChatCo 214 | [link-repo]: https://github.com/laravel-notification-channels/facebook 215 | [link-packagist]: https://packagist.org/packages/laravel-notification-channels/facebook 216 | [link-scrutinizer]: https://scrutinizer-ci.com/g/laravel-notification-channels/facebook/code-structure 217 | [link-code-quality]: https://scrutinizer-ci.com/g/laravel-notification-channels/facebook 218 | [link-author]: https://github.com/irazasyed 219 | [link-contributors]: ../../contributors 220 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "laravel-notification-channels/facebook", 3 | "description": "Facebook Notifications Channel for Laravel", 4 | "homepage": "https://github.com/laravel-notification-channels/facebook", 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "Irfaq Syed", 9 | "email": "github@lukonet.net", 10 | "homepage": "https://lukonet.com", 11 | "role": "Developer" 12 | } 13 | ], 14 | "require": { 15 | "php": "^8.1", 16 | "guzzlehttp/guzzle": "^7.2", 17 | "illuminate/notifications": "^10.0 || ^11.0", 18 | "illuminate/support": "^10.0 || ^11.0" 19 | }, 20 | "require-dev": { 21 | "mockery/mockery": "^1.4.4", 22 | "phpunit/phpunit": "^10.5 || ^11.0" 23 | }, 24 | "autoload": { 25 | "psr-4": { 26 | "NotificationChannels\\Facebook\\": "src" 27 | } 28 | }, 29 | "autoload-dev": { 30 | "psr-4": { 31 | "NotificationChannels\\Facebook\\Test\\": "tests" 32 | } 33 | }, 34 | "scripts": { 35 | "test": "phpunit" 36 | }, 37 | "config": { 38 | "sort-packages": true 39 | }, 40 | "extra": { 41 | "laravel": { 42 | "providers": [ 43 | "NotificationChannels\\Facebook\\FacebookServiceProvider" 44 | ] 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Components/Button.php: -------------------------------------------------------------------------------- 1 | title = $title; 34 | $this->data = $data; 35 | $this->payload['type'] = $type; 36 | } 37 | 38 | /** 39 | * Create a button. 40 | * 41 | * @param array|string $data 42 | * 43 | * @return static 44 | */ 45 | public static function create(string $title = '', $data = null, string $type = ButtonType::WEB_URL): self 46 | { 47 | return new static($title, $data, $type); 48 | } 49 | 50 | /** 51 | * Set Button Title. 52 | * 53 | * @return $this 54 | * 55 | * @throws CouldNotCreateButton 56 | */ 57 | public function title(string $title): self 58 | { 59 | if (blank($title)) { 60 | throw CouldNotCreateButton::titleNotProvided(); 61 | } 62 | 63 | if (mb_strlen($title) > 20) { 64 | throw CouldNotCreateButton::titleLimitExceeded($title); 65 | } 66 | 67 | $this->payload['title'] = $title; 68 | 69 | return $this; 70 | } 71 | 72 | /** 73 | * Set a URL for the button. 74 | * 75 | * @return $this 76 | * 77 | * @throws CouldNotCreateButton 78 | */ 79 | public function url(string $url): self 80 | { 81 | if (blank($url)) { 82 | throw CouldNotCreateButton::urlNotProvided(); 83 | } 84 | 85 | if (!filter_var($url, FILTER_VALIDATE_URL)) { 86 | throw CouldNotCreateButton::invalidUrlProvided($url); 87 | } 88 | 89 | $this->payload['url'] = $url; 90 | $this->isTypeWebUrl(); 91 | 92 | return $this; 93 | } 94 | 95 | /** 96 | * @return $this 97 | * 98 | * @throws CouldNotCreateButton 99 | */ 100 | public function phone(string $phone): self 101 | { 102 | if (blank($phone)) { 103 | throw CouldNotCreateButton::phoneNumberNotProvided(); 104 | } 105 | 106 | if (is_string($phone) && !Str::startsWith($phone, '+')) { 107 | throw CouldNotCreateButton::invalidPhoneNumberProvided($phone); 108 | } 109 | 110 | $this->payload['payload'] = $phone; 111 | $this->isTypePhoneNumber(); 112 | 113 | return $this; 114 | } 115 | 116 | /** 117 | * @param mixed $postback 118 | * 119 | * @return $this 120 | * 121 | * @throws CouldNotCreateButton|\JsonException 122 | */ 123 | public function postback($postback): self 124 | { 125 | if (blank($postback)) { 126 | throw CouldNotCreateButton::postbackNotProvided(); 127 | } 128 | 129 | $this->payload['payload'] = is_string($postback) ? $postback : json_encode($postback, JSON_THROW_ON_ERROR); 130 | $this->isTypePostback(); 131 | 132 | return $this; 133 | } 134 | 135 | /** 136 | * Set Button Type. 137 | * 138 | * @param string $type Possible Values: "web_url", "postback" or "phone_number". Default: "web_url" 139 | * 140 | * @return $this 141 | */ 142 | public function type(string $type): self 143 | { 144 | $this->payload['type'] = $type; 145 | 146 | return $this; 147 | } 148 | 149 | /** 150 | * Set button type as web_url. 151 | * 152 | * @return $this 153 | */ 154 | public function isTypeWebUrl(): self 155 | { 156 | $this->payload['type'] = ButtonType::WEB_URL; 157 | 158 | return $this; 159 | } 160 | 161 | /** 162 | * Set button type as postback. 163 | * 164 | * @return $this 165 | */ 166 | public function isTypePostback(): self 167 | { 168 | $this->payload['type'] = ButtonType::POSTBACK; 169 | 170 | return $this; 171 | } 172 | 173 | /** 174 | * Set button type as phone_number. 175 | * 176 | * @return $this 177 | */ 178 | public function isTypePhoneNumber(): self 179 | { 180 | $this->payload['type'] = ButtonType::PHONE_NUMBER; 181 | 182 | return $this; 183 | } 184 | 185 | /** 186 | * Builds payload and returns an array. 187 | * 188 | * @throws CouldNotCreateButton 189 | */ 190 | public function toArray(): array 191 | { 192 | $this->title($this->title); 193 | $this->makePayload($this->data); 194 | 195 | return $this->payload; 196 | } 197 | 198 | /** 199 | * Convert the object into something JSON serializable. 200 | * 201 | * @return mixed 202 | * 203 | * @throws CouldNotCreateButton 204 | */ 205 | public function jsonSerialize() 206 | { 207 | return $this->toArray(); 208 | } 209 | 210 | /** 211 | * Determine Button Type. 212 | */ 213 | protected function isType(string $type): bool 214 | { 215 | return isset($this->payload['type']) && $type === $this->payload['type']; 216 | } 217 | 218 | /** 219 | * Make payload by data and type. 220 | * 221 | * @param mixed $data 222 | * 223 | * @return $this 224 | * 225 | * @throws CouldNotCreateButton 226 | */ 227 | protected function makePayload($data): self 228 | { 229 | if (blank($data)) { 230 | return $this; 231 | } 232 | 233 | switch ($this->payload['type']) { 234 | case ButtonType::WEB_URL: 235 | $this->url($data); 236 | 237 | break; 238 | 239 | case ButtonType::PHONE_NUMBER: 240 | $this->phone($data); 241 | 242 | break; 243 | 244 | case ButtonType::POSTBACK: 245 | $this->postback($data); 246 | 247 | break; 248 | } 249 | 250 | if (isset($this->payload['payload']) && mb_strlen($this->payload['payload']) > 1000) { 251 | throw CouldNotCreateButton::payloadLimitExceeded($this->payload['payload']); 252 | } 253 | 254 | return $this; 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /src/Components/Card.php: -------------------------------------------------------------------------------- 1 | title($title); 27 | } 28 | } 29 | 30 | /** 31 | * Create a Card. 32 | * 33 | * @return static 34 | * 35 | * @throws CouldNotCreateCard 36 | */ 37 | public static function create(string $title = ''): self 38 | { 39 | return new static($title); 40 | } 41 | 42 | /** 43 | * Set Button Title. 44 | * 45 | * @return $this 46 | * 47 | * @throws CouldNotCreateCard 48 | */ 49 | public function title(string $title): self 50 | { 51 | if (mb_strlen($title) > 80) { 52 | throw CouldNotCreateCard::titleLimitExceeded($title); 53 | } 54 | 55 | $this->payload['title'] = $title; 56 | 57 | return $this; 58 | } 59 | 60 | /** 61 | * Set Card Item Url. 62 | * 63 | * @return $this 64 | */ 65 | public function url(string $itemUrl): self 66 | { 67 | $this->payload['item_url'] = $itemUrl; 68 | 69 | return $this; 70 | } 71 | 72 | /** 73 | * Set Card Image Url. 74 | * 75 | * @param string $imageUrl Default image ratio is 1.91:1 76 | * 77 | * @return $this 78 | */ 79 | public function image(string $imageUrl): self 80 | { 81 | $this->payload['image_url'] = $imageUrl; 82 | 83 | return $this; 84 | } 85 | 86 | /** 87 | * Set Card Subtitle. 88 | * 89 | * @return $this 90 | * 91 | * @throws CouldNotCreateCard 92 | */ 93 | public function subtitle(string $subtitle): self 94 | { 95 | if (mb_strlen($subtitle) > 80) { 96 | throw CouldNotCreateCard::subtitleLimitExceeded($subtitle); 97 | } 98 | 99 | $this->payload['subtitle'] = $subtitle; 100 | 101 | return $this; 102 | } 103 | 104 | /** 105 | * Returns a payload for API request. 106 | * 107 | * @throws CouldNotCreateCard 108 | */ 109 | public function toArray(): array 110 | { 111 | if (!isset($this->payload['title'])) { 112 | throw CouldNotCreateCard::titleNotProvided(); 113 | } 114 | 115 | if (count($this->buttons) > 0) { 116 | $this->payload['buttons'] = $this->buttons; 117 | } 118 | 119 | return $this->payload; 120 | } 121 | 122 | /** 123 | * Convert the object into something JSON serializable. 124 | * 125 | * @return mixed 126 | * 127 | * @throws CouldNotCreateCard 128 | */ 129 | public function jsonSerialize() 130 | { 131 | return $this->toArray(); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/Enums/AttachmentType.php: -------------------------------------------------------------------------------- 1 | 24 hours to resolve). 65 | * 66 | * DISALLOWED: 67 | * - Automated messages. 68 | * - Content unrelated to user inquiry. 69 | */ 70 | public const HUMAN_AGENT = 'HUMAN_AGENT'; 71 | } 72 | -------------------------------------------------------------------------------- /src/Enums/MessagingType.php: -------------------------------------------------------------------------------- 1 | hasResponse()) { 20 | $result = json_decode($exception->getResponse()->getBody(), false); 21 | 22 | return new static("Facebook responded with an error `{$result->error->code} - {$result->error->type} {$result->error->message}`"); 23 | } 24 | 25 | return new static('Facebook responded with an error'); 26 | } 27 | 28 | /** 29 | * Thrown when there's no page token provided. 30 | * 31 | * @return static 32 | */ 33 | public static function facebookPageTokenNotProvided(string $message): self 34 | { 35 | return new static($message); 36 | } 37 | 38 | /** 39 | * Thrown when we're unable to communicate with Telegram. 40 | * 41 | * @return static 42 | */ 43 | public static function couldNotCommunicateWithFacebook(\Exception $exception): self 44 | { 45 | return new static('The communication with Facebook failed. Reason: '.$exception->getMessage()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Facebook.php: -------------------------------------------------------------------------------- 1 | token = $token; 31 | 32 | $this->http = $httpClient; 33 | } 34 | 35 | /** 36 | * Set Default Graph API Version. 37 | * 38 | * @param mixed $graphApiVersion 39 | */ 40 | public function setGraphApiVersion($graphApiVersion): self 41 | { 42 | $this->graphApiVersion = $graphApiVersion; 43 | 44 | return $this; 45 | } 46 | 47 | /** 48 | * Set App Secret to generate appsecret_proof. 49 | * 50 | * @param string $secret 51 | */ 52 | public function setSecret($secret = null): self 53 | { 54 | $this->secret = $secret; 55 | 56 | return $this; 57 | } 58 | 59 | /** 60 | * Send text message. 61 | * 62 | * @throws GuzzleException 63 | * @throws CouldNotSendNotification 64 | */ 65 | public function send(array $params): ResponseInterface 66 | { 67 | return $this->post('me/messages', $params); 68 | } 69 | 70 | /** 71 | * @throws GuzzleException 72 | * @throws CouldNotSendNotification 73 | */ 74 | public function get(string $endpoint, array $params = []): ResponseInterface 75 | { 76 | return $this->api($endpoint, ['query' => $params]); 77 | } 78 | 79 | /** 80 | * @throws GuzzleException 81 | * @throws CouldNotSendNotification 82 | */ 83 | public function post(string $endpoint, array $params = []): ResponseInterface 84 | { 85 | return $this->api($endpoint, ['json' => $params], 'POST'); 86 | } 87 | 88 | /** 89 | * Get HttpClient. 90 | */ 91 | protected function httpClient(): HttpClient 92 | { 93 | return $this->http ?? new HttpClient(); 94 | } 95 | 96 | /** 97 | * Send an API request and return response. 98 | * 99 | * @param string $method 100 | * 101 | * @return mixed|ResponseInterface 102 | * 103 | * @throws GuzzleException 104 | * @throws CouldNotSendNotification 105 | */ 106 | protected function api(string $endpoint, array $options, $method = 'GET') 107 | { 108 | if (empty($this->token)) { 109 | throw CouldNotSendNotification::facebookPageTokenNotProvided('You must provide your Facebook Page token to make any API requests.'); 110 | } 111 | 112 | $url = "https://graph.facebook.com/v{$this->graphApiVersion}/{$endpoint}?access_token={$this->token}"; 113 | 114 | if ($this->secret) { 115 | $appsecret_proof = hash_hmac('sha256', $this->token, $this->secret); 116 | 117 | $url .= "&appsecret_proof={$appsecret_proof}"; 118 | } 119 | 120 | try { 121 | return $this->httpClient()->request($method, $url, $options); 122 | } catch (ClientException $exception) { 123 | throw CouldNotSendNotification::facebookRespondedWithAnError($exception); 124 | } catch (\Exception $exception) { 125 | throw CouldNotSendNotification::couldNotCommunicateWithFacebook($exception); 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/FacebookChannel.php: -------------------------------------------------------------------------------- 1 | fb = $fb; 24 | } 25 | 26 | /** 27 | * Send the given notification. 28 | * 29 | * @param mixed $notifiable 30 | * 31 | * @throws CouldNotCreateMessage 32 | * @throws CouldNotSendNotification 33 | * @throws GuzzleException 34 | */ 35 | public function send($notifiable, Notification $notification): array 36 | { 37 | $message = $notification->toFacebook($notifiable); 38 | 39 | if (is_string($message)) { 40 | $message = FacebookMessage::create($message); 41 | } 42 | 43 | if ($message->toNotGiven()) { 44 | if (!$to = $notifiable->routeNotificationFor('facebook')) { 45 | throw CouldNotCreateMessage::recipientNotProvided(); 46 | } 47 | 48 | $message->to($to); 49 | } 50 | 51 | $response = $this->fb->send($message->toArray()); 52 | 53 | return json_decode($response->getBody()->getContents(), true); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/FacebookMessage.php: -------------------------------------------------------------------------------- 1 | text($text); 66 | } 67 | } 68 | 69 | /** 70 | * @return static 71 | * 72 | * @throws CouldNotCreateMessage 73 | */ 74 | public static function create(string $text = ''): self 75 | { 76 | return new static($text); 77 | } 78 | 79 | /** 80 | * Recipient's PSID or Phone Number. 81 | * 82 | * The id must be an ID that was retrieved through the 83 | * Messenger entry points or through the Messenger webhooks. 84 | * 85 | * @param array|string $recipient ID of recipient or Phone number of the recipient with the format 86 | * +1(212)555-2368 87 | * @param string $type recipient Type: id, user_ref, phone_number, post_id, comment_id 88 | * 89 | * @return $this 90 | */ 91 | public function to($recipient, string $type = RecipientType::ID): self 92 | { 93 | if (is_array($recipient)) { 94 | [$type, $recipient] = $recipient; 95 | } 96 | 97 | $this->recipient = $recipient; 98 | $this->recipientType = $type; 99 | 100 | return $this; 101 | } 102 | 103 | /** 104 | * Notification text. 105 | * 106 | * @return $this 107 | * 108 | * @throws CouldNotCreateMessage 109 | */ 110 | public function text(string $text): self 111 | { 112 | if (mb_strlen($text) > 320) { 113 | throw CouldNotCreateMessage::textTooLong(); 114 | } 115 | 116 | $this->text = $text; 117 | $this->hasText = true; 118 | 119 | return $this; 120 | } 121 | 122 | /** 123 | * Add Attachment. 124 | * 125 | * @return $this 126 | * 127 | * @throws CouldNotCreateMessage 128 | */ 129 | public function attach(string $attachmentType, string $url): self 130 | { 131 | $attachmentTypes = [ 132 | AttachmentType::FILE, 133 | AttachmentType::IMAGE, 134 | AttachmentType::VIDEO, 135 | AttachmentType::AUDIO, 136 | ]; 137 | 138 | if (!in_array($attachmentType, $attachmentTypes, false)) { 139 | throw CouldNotCreateMessage::invalidAttachmentType(); 140 | } 141 | 142 | if (blank($url)) { 143 | throw CouldNotCreateMessage::urlNotProvided(); 144 | } 145 | 146 | $this->attachmentType = $attachmentType; 147 | $this->attachmentUrl = $url; 148 | $this->hasAttachment = true; 149 | 150 | return $this; 151 | } 152 | 153 | /** 154 | * Push notification type. 155 | * 156 | * @param string $notificationType Possible values: REGULAR, SILENT_PUSH, NO_PUSH 157 | * 158 | * @return $this 159 | * 160 | * @throws CouldNotCreateMessage 161 | */ 162 | public function notificationType(string $notificationType): self 163 | { 164 | $notificationTypes = [ 165 | NotificationType::REGULAR, 166 | NotificationType::SILENT_PUSH, 167 | NotificationType::NO_PUSH, 168 | ]; 169 | 170 | if (!in_array($notificationType, $notificationTypes, false)) { 171 | throw CouldNotCreateMessage::invalidNotificationType(); 172 | } 173 | 174 | $this->notificationType = $notificationType; 175 | 176 | return $this; 177 | } 178 | 179 | public function imageAspectRatio(string $imageAspectRatio): self 180 | { 181 | $imageAspectRatios = [ 182 | ImageAspectRatioType::SQUARE, 183 | ImageAspectRatioType::HORIZONTAL, 184 | ]; 185 | 186 | if (!in_array($imageAspectRatio, $imageAspectRatios, false)) { 187 | throw CouldNotCreateMessage::invalidImageAspectRatio(); 188 | } 189 | 190 | foreach ($this->cards as $card) { 191 | if (array_key_exists('image_url', $card->toArray())) { 192 | $this->hasImageUrl = true; 193 | 194 | break; 195 | } 196 | } 197 | 198 | if (!$this->hasImageUrl) { 199 | return $this; 200 | } 201 | 202 | $this->imageAspectRatio = $imageAspectRatio; 203 | 204 | return $this; 205 | } 206 | 207 | /** 208 | * Helper to set notification type as REGULAR. 209 | * 210 | * @return $this 211 | */ 212 | public function isTypeRegular(): self 213 | { 214 | $this->notificationType = NotificationType::REGULAR; 215 | 216 | return $this; 217 | } 218 | 219 | /** 220 | * Helper to set notification type as SILENT_PUSH. 221 | * 222 | * @return $this 223 | */ 224 | public function isTypeSilentPush(): self 225 | { 226 | $this->notificationType = NotificationType::SILENT_PUSH; 227 | 228 | return $this; 229 | } 230 | 231 | /** 232 | * Helper to set notification type as NO_PUSH. 233 | * 234 | * @return $this 235 | */ 236 | public function isTypeNoPush(): self 237 | { 238 | $this->notificationType = NotificationType::NO_PUSH; 239 | 240 | return $this; 241 | } 242 | 243 | /** 244 | * Helper to set messaging type as RESPONSE. 245 | * 246 | * @return $this 247 | */ 248 | public function isResponse(): self 249 | { 250 | $this->messagingType = MessagingType::RESPONSE; 251 | 252 | return $this; 253 | } 254 | 255 | /** 256 | * Helper to set messaging type as UPDATE. 257 | * 258 | * @return $this 259 | */ 260 | public function isUpdate(): self 261 | { 262 | $this->messagingType = MessagingType::UPDATE; 263 | 264 | return $this; 265 | } 266 | 267 | /** 268 | * Helper to set messaging type as MESSAGE_TAG. 269 | * 270 | * @param mixed $messageTag 271 | * 272 | * @return $this 273 | */ 274 | public function isMessageTag($messageTag): self 275 | { 276 | $this->messagingType = MessagingType::MESSAGE_TAG; 277 | $this->messageTag = $messageTag; 278 | 279 | return $this; 280 | } 281 | 282 | /** 283 | * Add up to 10 cards to be displayed in a carousel. 284 | * 285 | * @return $this 286 | * 287 | * @throws CouldNotCreateMessage 288 | */ 289 | public function cards(array $cards): self 290 | { 291 | if (count($cards) > 10) { 292 | throw CouldNotCreateMessage::messageCardsLimitExceeded(); 293 | } 294 | 295 | $this->cards = $cards; 296 | 297 | return $this; 298 | } 299 | 300 | /** 301 | * Determine if user id is not given. 302 | */ 303 | public function toNotGiven(): bool 304 | { 305 | return !isset($this->recipient); 306 | } 307 | 308 | /** 309 | * Convert the object into something JSON serializable. 310 | * 311 | * @return mixed 312 | * 313 | * @throws CouldNotCreateMessage 314 | */ 315 | public function jsonSerialize() 316 | { 317 | return $this->toArray(); 318 | } 319 | 320 | /** 321 | * Returns message payload for JSON conversion. 322 | * 323 | * @throws CouldNotCreateMessage 324 | */ 325 | public function toArray(): array 326 | { 327 | if ($this->hasAttachment) { 328 | return $this->attachmentMessageToArray(); 329 | } 330 | 331 | if ($this->hasText) { 332 | // check if it has buttons 333 | if (count($this->buttons) > 0) { 334 | return $this->buttonMessageToArray(); 335 | } 336 | 337 | return $this->textMessageToArray(); 338 | } 339 | 340 | if (count($this->cards) > 0) { 341 | return $this->genericMessageToArray(); 342 | } 343 | 344 | throw CouldNotCreateMessage::dataNotProvided(); 345 | } 346 | 347 | /** 348 | * Returns message for simple text message. 349 | */ 350 | protected function textMessageToArray(): array 351 | { 352 | $message = []; 353 | $message['recipient'][$this->recipientType] = $this->recipient; 354 | $message['notification_type'] = $this->notificationType; 355 | $message['message']['text'] = $this->text; 356 | $message['messaging_type'] = $this->messagingType; 357 | 358 | if (filled($this->messageTag)) { 359 | $message['tag'] = $this->messageTag; 360 | } 361 | 362 | return $message; 363 | } 364 | 365 | /** 366 | * Returns message for attachment message. 367 | */ 368 | protected function attachmentMessageToArray(): array 369 | { 370 | $message = []; 371 | $message['recipient'][$this->recipientType] = $this->recipient; 372 | $message['notification_type'] = $this->notificationType; 373 | $message['message']['attachment']['type'] = $this->attachmentType; 374 | $message['message']['attachment']['payload']['url'] = $this->attachmentUrl; 375 | $message['messaging_type'] = $this->messagingType; 376 | 377 | if (filled($this->messageTag)) { 378 | $message['tag'] = $this->messageTag; 379 | } 380 | 381 | return $message; 382 | } 383 | 384 | /** 385 | * Returns message for Generic Template message. 386 | */ 387 | protected function genericMessageToArray(): array 388 | { 389 | $message = []; 390 | $message['recipient'][$this->recipientType] = $this->recipient; 391 | $message['notification_type'] = $this->notificationType; 392 | $message['message']['attachment']['type'] = 'template'; 393 | $message['message']['attachment']['payload']['template_type'] = 'generic'; 394 | $message['message']['attachment']['payload']['elements'] = $this->cards; 395 | $message['messaging_type'] = $this->messagingType; 396 | 397 | if ($this->hasImageUrl) { 398 | $message['message']['attachment']['payload']['image_aspect_ratio'] = $this->imageAspectRatio; 399 | } 400 | 401 | if (filled($this->messageTag)) { 402 | $message['tag'] = $this->messageTag; 403 | } 404 | 405 | return $message; 406 | } 407 | 408 | /** 409 | * Returns message for Button Template message. 410 | */ 411 | protected function buttonMessageToArray(): array 412 | { 413 | $message = []; 414 | $message['recipient'][$this->recipientType] = $this->recipient; 415 | $message['notification_type'] = $this->notificationType; 416 | $message['message']['attachment']['type'] = 'template'; 417 | $message['message']['attachment']['payload']['template_type'] = 'button'; 418 | $message['message']['attachment']['payload']['text'] = $this->text; 419 | $message['message']['attachment']['payload']['buttons'] = $this->buttons; 420 | $message['messaging_type'] = $this->messagingType; 421 | 422 | if (filled($this->messageTag)) { 423 | $message['tag'] = $this->messageTag; 424 | } 425 | 426 | return $message; 427 | } 428 | } 429 | -------------------------------------------------------------------------------- /src/FacebookServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->when(FacebookChannel::class) 18 | ->needs(Facebook::class) 19 | ->give(static function () { 20 | $facebook = new Facebook(config('services.facebook.page-token')); 21 | 22 | return $facebook 23 | ->setGraphApiVersion(config('services.facebook.version', '4.0')) 24 | ->setSecret(config('services.facebook.app-secret')) 25 | ; 26 | }) 27 | ; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Traits/HasButtons.php: -------------------------------------------------------------------------------- 1 | 3) { 25 | throw CouldNotCreateMessage::messageButtonsLimitExceeded(); 26 | } 27 | 28 | $this->buttons = $buttons; 29 | 30 | return $this; 31 | } 32 | } 33 | --------------------------------------------------------------------------------