📨 Facebook Notifications Channel for Laravel

Overview

Facebook Notifications Channel for Laravel

Latest Version on Packagist Software License SensioLabsInsight Quality Score Total Downloads

This package makes it easy to send notifications using the Facebook Messenger with Laravel.

Contents

Installation

You can install the package via composer:

composer require laravel-notification-channels/facebook

Setting up your Facebook Bot

Follow the Getting Started guide in order to create a Facebook Messenger app, a Facebook page and a page token, which is connecting both.

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:

// config/services.php
...
'facebook' => [
    'page-token' => env('FACEBOOK_PAGE_TOKEN', 'YOUR PAGE TOKEN HERE'),
    
    // Optional - Omit this if you want to use default version.
    'version'    => env('FACEBOOK_GRAPH_API_VERSION', '4.0')
    
    // Optional - If set, the appsecret_proof will be sent to verify your page-token.
    'app-secret' => env('FACEBOOK_APP_SECRET', '')
],
...

Usage

Let's take an invoice-paid-notification as an example. 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.

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

use NotificationChannels\Facebook\FacebookChannel;
use NotificationChannels\Facebook\FacebookMessage;
use NotificationChannels\Facebook\Components\Button;
use NotificationChannels\Facebook\Enums\NotificationType;

use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification
{
    public function via($notifiable)
    {
        return [FacebookChannel::class];
    }

    public function toFacebook($notifiable)
    {
        $url = url('/invoice/' . $this->invoice->id);

        return FacebookMessage::create()
            ->to($this->user->fb_messenger_user_id) // Optional
            ->text('One of your invoices has been paid!')
            ->isUpdate() // Optional
            ->isTypeRegular() // Optional
            // Alternate method to provide the notification type.
            // ->notificationType(NotificationType::REGULAR) // Optional
            ->buttons([
                Button::create('View Invoice', $url)->isTypeWebUrl(),
                Button::create('Call Us for Support!', '+1(212)555-2368')->isTypePhoneNumber(),
                Button::create('Start Chatting', ['invoice_id' => $this->invoice->id])->isTypePostback() // Custom payload sent back to your server
            ]); // Buttons are optional as well.
    }
}

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.

Laravel Facebook Notification Example

Message Examples

Basic Text Message

Send a basic text message to a user

return FacebookMessage::create('You have just paid your monthly fee! Thanks')
    ->to($this->user->fb_messenger_id);
Attachment Message

Send a file attachment to a user (Example is sending a pdf invoice)

return FacebookMessage::create()
    ->attach(AttachmentType::FILE, url('invoices/'.$this->invoice->id))
    ->to($this->user->fb_messenger_id);
Generic (Card Carousel) Message

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

return FacebookMessage::create()
    ->to($this->user->fb_messenger_id) // Optional
    ->cards([
        Card::create('Card No.1 Title')
            ->subtitle('An item description')
            ->url('items/'.$this->item[0]->id)
            ->image('items/'.$this->item[0]->id.'/image'),
        
        Card::create('Card No.2 Title')
            ->subtitle('An item description')
            ->url('items/'.$this->item[1]->id)
            ->image('items/'.$this->item[1]->id.'/image')
        // could add buttons using ->buttons($array of Button)
    ]); 

Routing a message

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:

...
/**
 * Route notifications for the Facebook channel.
 *
 * @return int
 */
public function routeNotificationForFacebook()
{
    return $this->fb_messenger_user_id;
}
...

Available Message methods

  • 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 for more information.
  • text(''): (string) Notification message.
  • isResponse(): Set messaging_type as RESPONSE.
  • isUpdate(): (default) Set messaging_type as UPDATE.
  • 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.
  • attach($attachment_type, $url): (AttachmentType, string) An attachment type (IMAGE, AUDIO, VIDEO, FILE) and the url of this attachment
  • 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.
  • 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.
  • 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.
  • 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).
  • isTypeRegular(): Helper method to create a notification type: REGULAR.
  • isTypeSilentPush(): Helper method to create a notification type: SILENT_PUSH.
  • isTypeNoPush(): Helper method to create a notification type: NO_PUSH.

Available Button methods

  • title(''): (string) Button Title.
  • data(''): (string) Button Data - It can be a web url, postback data or a formated phone number.
  • type(''): (string) Button Type - web_url, postback or phone_number. Use ButtonType enumerator for guaranteeing valid values
  • isTypeWebUrl(): Helper method to create a web_url type button.
  • isTypePhoneNumber(): Helper method to create a phone_number type button.
  • isTypePostback(): Helper method to create a postback type button.

Available Card methods

  • title(''): (string) Card Title.
  • subtitle(''): (string) Card Subtitle.
  • url(''): (string) Card Item Url.
  • image(''): (string) Card Image Url. Image ratio should be 1.91:1
  • 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.

Contributing

Please see CONTRIBUTING for details.

Credits

License

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

Comments
  • Updated to include more Message types

    Updated to include more Message types

    Added more message types (basic text, button, generic, attachment) Changed API version to 2.7 Updated README to reflect changes Tweaked directory structure to include Components (Button, Card) Moved around Exceptions into better organised classes (mostly from Send Error to Message Error) Attempted to keep to style guide :)

    opened by davidpiesse 6
  • Currently only uses Button Template

    Currently only uses Button Template

    This currently only uses the Button Template for Facebook Messenger. Is this intentional to restrain its ability. For example we could also allow sending of

    • Attachments (files, images etc)
    • Generic message
    • Receipts
    • Basic text message with no buttons

    If you want this functionality I can add this but I will have to rip up a bit of code that forces it currently down the Button Template route.

    Another tweak I can add in:

    • Change API version to 2.7 (latest)
    opened by davidpiesse 5
  • TODO List

    TODO List

    • [x] Update SensioLabsInsight Link - Don't have control for this. @freekmurze please update.
    • [x] Submit to Packagist. CC: @freekmurze @themsaid @mpociot please submit.
    • [x] Explore other attachment templates like generic, receipt and others.
    • [x] Improve Code.
    • [x] Improve README Instructions.
    • [ ] Add Tests.

    Contributions are always welcome :)

    opened by irazasyed 5
  • How to get fb_messenger_user_id ?

    How to get fb_messenger_user_id ?

    Thanks for the great channel. @irazasyed

    I have a basic question, how do we get "fb_messenger_user_id"?

    Is there any way to get it and store it to 'users' table associated with user?

    Thanks in advance.

    opened by rajendrap123 4
  • Page scoped user id

    Page scoped user id

    Hello,

    I'm currently trying to send messages to facebook users. However I only have access to the app scoped user ids, which I got after a successful 'login with facebook' process.

    I've been researching this for hours and I can't find anything relevant or/and up to date to get the page scoped user id.

    Could you provide some help on how to proceed to get this ?

    Thanks,

    opened by nWidart 4
  • Laravel 8 Support

    Laravel 8 Support

    Laravel 8 has been released today and we need to update this repo to support it. See https://laravel.com/docs/8.x/upgrade & https://github.com/laravel-notification-channels/channels/issues/107

    opened by atymic 3
  • appsecret_proof requrired

    appsecret_proof requrired

    If I send a message via this package, I get the error from facebook that for the graph-api an appsecret_proof is required:

    NotificationChannels/Facebook/Exceptions/CouldNotSendNotification with message 'Facebook resonded with an error 100 - GraphMethodException API calls from the server require an appsecret_proof argument'

    If I attach it manually in the api method, the message is getting send. Is there a problem with my implementation or is this something new?

    I am happy to PR my changes if there is any demand for this.

    opened by pschocke 3
  • 100 - OAuthException (#100) param recipient must be non-empty

    100 - OAuthException (#100) param recipient must be non-empty

    Hi,

    Just made a fresh clone of this repo and I'm getting "100 - OAuthException (#100) param recipient must be non-empty error" in laravel logs whenever I try sending text message. Meanwhile the version fetched via composer require laravel-notification-channels/facebook works fine.

    opened by n-other 3
  • Use stable version and allow backport usage

    Use stable version and allow backport usage

    This PR makes use of the stable 5.3 version and also allows usage of the laravel-notification-channels/backport package, to use this notification channel with Laravel 5.1 and 5.2

    opened by mpociot 3
  • Installation Guide

    Installation Guide

    Hey,

    just tried it and it is working. Great work! Only one two things I that could be better:

    1.) Installation description If you're not into Facebook it is really hard to understand what is happening and what are we / you going to achieve. Where does the message pop up? Which chat window between who?

    I would also add some information about the "page-scoped User ID" what that is and where to get that. I got a chatbot already setup where I copied this ID, but I would not know where else I could get ip.

    2.) Optional to() method. What is happening if I don't use that method? I didn't get that.

    Cheers

    opened by christophrumpel 3
  • Messaging Phone Number

    Messaging Phone Number

    Is it possible to show an example on how to message someone using a phone number??

    return FacebookMessage::create() 
                ->to('+5521999823030')
                ->text('potato')
    

    The format is: "+1(212)555-2368"
    Correct?
    But Im trying to send a message to a non-US phone...

    Can someone tell me if using numbers from outside US is supported??

    Btw, my output is: "message": "Facebook responded with an error100 - OAuthException (#100) Param recipient[id] must be a valid ID string (e.g., "123")"

    opened by AlexandreMPDias 2
Releases(0.3.0)
  • 0.3.0(Feb 10, 2022)

    What's Changed

    • Laravel 9 Support.
    • Add support string payload to button element by @dostrog in https://github.com/laravel-notification-channels/facebook/pull/50
    • Add Image aspect ratio helper by @dostrog in https://github.com/laravel-notification-channels/facebook/pull/51

    New Contributors

    • @dostrog made their first contribution in https://github.com/laravel-notification-channels/facebook/pull/50

    Full Changelog: https://github.com/laravel-notification-channels/facebook/compare/0.2.1...0.3.0

    Source code(tar.gz)
    Source code(zip)
  • 0.2.1(Dec 6, 2020)

  • 0.2.0(Sep 7, 2020)

  • 0.1.0(Feb 26, 2020)

  • 0.0.4(Oct 10, 2019)

    • Laravel 6 Support.
    • Graph API version change config (You can optionally override default API version).
    • Messaging type support with methods.
    • Message tag support with enums.
    • Recipient type support with enums.
    • Notification type helpers.
    • Micro optimizations.
    • Typehint and return type declarations.
    • Cleanup and revisions to phpdoc blocks and others.
    Source code(tar.gz)
    Source code(zip)
  • 0.0.2(Feb 8, 2018)

  • 0.0.1(Aug 15, 2016)

Owner
Laravel Notification Channels
A collection of custom notification drivers for Laravel
Laravel Notification Channels
Notion.so notifications channel for Laravel

Installation composer require astroshippers/notion-notification-channel Usage Inside eloquent model: public function routeNotificationForNotion(): arr

AstroShippers 3 Jul 4, 2022
@Authy notification channel for @Laravel, with the ability to send in-app, sms, and call verification tokens.

Authy Notification Channel for Laravel Authy notification channel for Laravel, with the ability to send in-app, sms, and call verification tokens. Tab

Laravel Notification Channels 57 Dec 19, 2022
Google Chat - Laravel Notification Channel

Google Chat - Laravel Notification Channel This package makes it easy to send notifications using Google Chat , (formerly known as Hangouts Chat) with

Laravel Notification Channels 36 Dec 6, 2022
Laravel SMS Notification Channel

Laravel SMS Notification Channel Installation composer require guangda/laravel-sms-notification-channel env 配置 SMS_PROVIDER=yunpian SMS_SIGNATURE=【签名

Guangda 6 Dec 29, 2021
Lark Notification Channel for laravel.

Lark notifications channel for Laravel This package makes it easy to send Lark using the Laravel notification system. Supports 5.5+, 6.x, 7.x and 8.x.

null 1 Nov 3, 2021
An SMS notification channel for the PHP framework Laravel.

Laravel SMS notification channel An SMS notification channel for the PHP framework Laravel. Supported SMS gateways: 46elks Cellsynt Telenor SMS Pro Tw

Andreas 2 Jan 22, 2022
Laravel FCM (Firebase Cloud Messaging) Notification Channel

Laravel FCM Notification Laravel FCM (Firebase Cloud Messaging) Notification Channel Use this package to send push notifications via Laravel to Fireba

Vishal Dudhatra 3 Jul 3, 2022
Laravel Security Notifications

This package adds security notifications to warn your users when significant security events occur so that they aren't the next victim of an attacker.

Anteris 5 Feb 8, 2022
Laravel package to launch toast notifications.

Laravel package to launch toast notifications. This package provides assistance when using toast notifications. Using the iziTOAST package, which allo

Anthony Medina 7 Nov 25, 2022
Laravel Subscribable Notifications

Laravel Subscribable Notifications This package allows you to subscribe your app Users to your app Notifications and dispatch them without specifying

Andrés Santibáñez 132 Nov 10, 2022
Larafirebase is a package thats offers you to send push notifications or custom messages via Firebase in Laravel.

Introduction Larafirebase is a package thats offers you to send push notifications or custom messages via Firebase in Laravel. Firebase Cloud Messagin

Kutia Software Company 264 Jan 7, 2023
Flexible Flash notifications for Laravel

Introduction Laravel Notify is a package that lets you add custom notifications to your project. A diverse range of notification design is available.

Arthur Monney 1.2k Dec 26, 2022
A package to simplify automating future notifications and reminders in Laravel

Laravel Snooze Schedule future notifications and reminders in Laravel Why use this package? Ever wanted to schedule a future notification to go out at

Thomas Kane 720 Jan 7, 2023
Push Notifications using Laravel

laravel-push-notification Push Notifications using Laravel PushNotification::send(['deviceToken1', 'deviceToken2',..], 'Notification Message', 'Action

Webelight Solutions 26 Jul 22, 2022
Laravel package to enable sending push notifications to devices

Laravel Push Notification Package to enable sending push notifications to devices Installation Update your composer.json file to include this package

Davi Nunes 1.2k Sep 27, 2022
Send Firebase push notifications with Laravel php framework.

FCM Notification Channel for Laravel Send Firebase push notifications with Laravel php framework. Installation You can install this package via compos

Ankur Kumar 23 Oct 31, 2022
This package makes it easy to send notifications using RocketChat with Laravel 9.0+.

laravel-rocket-chat-notifications Introduction This package makes it easy to send notifications using RocketChat with Laravel 9.0+. Contents Installat

Team Nifty GmbH 25 Dec 1, 2022
This package makes it easy to send web push notifications with Laravel.

Web push notifications channel for Laravel This package makes it easy to send web push notifications with Laravel. Installation You can install the pa

Laravel Notification Channels 564 Jan 3, 2023
Event subscriber for Laravel notifications.

Laravel Notification Event Subscriber This package allows you to run any kind of actions while a notification is being sent or after it has been sent

Turan Karatuğ 76 Dec 30, 2022