Code Monkey home page Code Monkey logo

exponent-server-sdk-php's Introduction

exponent-server-sdk-php

Server-side library for working with Expo push notifications using PHP

Latest Stable Version License Total Downloads

Usage

  • Require the package in your project
composer require alymosul/exponent-server-sdk-php
  • In a php file
    require_once __DIR__.'/vendor/autoload.php';
    
    $channelName = 'news';
    $recipient= 'ExponentPushToken[unique]';
    
    // You can quickly bootup an expo instance
    $expo = \ExponentPhpSDK\Expo::normalSetup();
    
    // Subscribe the recipient to the server
    $expo->subscribe($channelName, $recipient);
    
    // Build the notification data
    $notification = ['body' => 'Hello World!'];
    
    // Notify an interest with a notification
    $expo->notify([$channelName], $notification);

Data can be added to notifications by providing it as a JSON object. For example:

// Build the notification data
$notification = ['body' => 'Hello World!', 'data'=> json_encode(array('someData' => 'goes here'))];

Channel name

You can use channels to send a notification to only one user, or to a group of users:

One recipient

In order to target one recipient (and avoid sending a notification to the wrong recipient), use a channel name specific to each user:

$channelName = 'user_528491';
$recipient = 'ExponentPushToken[unique]';

// …

// Subscribe the recipient to the server
$expo->subscribe($channelName, $recipient);

// …

// Notify an interest with a notification, only one recipient will receive it
$expo->notify([$channelName], $notification);

Several recipients

Declare a channel name that will be shared between the recipients:

$channelName = 'group_4815';

$recipient1 = 'ExponentPushToken[unique1]';
$recipient2 = 'ExponentPushToken[unique2]';

// …

// Subscribe the recipients to the server
$expo->subscribe($channelName, $recipient1);
$expo->subscribe($channelName, $recipient2);

// …

// Notify an interest with a notification, the 2 recipients will receive it
$expo->notify([$channelName], $notification);
// Build the notification data
$notification = ['body' => 'Hello World!', 'data'=> json_encode(array('someData' => 'goes here'))];

Additional security

If you set up enhanced security in your Expo Dashboard (as described here), you will need to attach an authorization token to each push request:

    // ...
    
    // Bootup an expo instance
    $expo = \ExponentPhpSDK\Expo::normalSetup();
    
    // Fetch your access token from where you stored it
    $accessToken = 'your_expo_access_token';
    
    // The access token will be attached to every push request you make hereafter
    $expo->setAccessToken($accessToken);
    
    // Notify an interest with a notification
    $expo->notify([$channelName], $notification);

TODO

  • Need to create tests

Laravel driver

exponent-server-sdk-php's People

Contributors

aleksandarsavic95 avatar alexislefebvre avatar alymosul avatar brynnb avatar cvele avatar dannyfeliz avatar francesco-laricchia avatar happyfacade avatar kylekatarnls avatar olaalsaker avatar patrickkivits avatar rodolfobarretoweb avatar saveyourtime avatar theunnicked 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

exponent-server-sdk-php's Issues

Default object from empty value

Getting this error in production

[2021-06-11 04:46:41] staging.ERROR: Creating default object from empty value {"userId":1,"exception":"[object] (ErrorException(code: 0): Creating default object from empty value at /var/app/current/vendor/alymosul/exponent-server-sdk-php/lib/Repositories/ExpoFileDriver.php:49)
[stacktrace]
#0 /var/app/current/vendor/alymosul/exponent-server-sdk-php/lib/Repositories/ExpoFileDriver.php(49): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'Creating defaul...', '/var/app/curren...', 49, Array)
#1 /var/app/current/vendor/alymosul/exponent-server-sdk-php/lib/ExpoRegistrar.php(41): ExponentPhpSDK\Repositories\ExpoFileDriver->store('User_xxxxx', 'ExponentPushTok...')
#2 /var/app/current/vendor/alymosul/exponent-server-sdk-php/lib/Expo.php(60): ExponentPhpSDK\ExpoRegistrar->registerInterest('User_xxxxx', 'ExponentPushTok...')
#3 /var/app/current/app/Http/Controllers/PushNotifier.php(170): ExponentPhpSDK\Expo->subscribe('User_xxxxx', 'ExponentPushTok...')

What's causing this?

I saw a previous thread suggesting to delete a tokens.json file but I can't find one?

PHP 5 Compatible

Is there a version compatible with PHP 5.6. Because lots of systems are still using 5.6 version. My PHP project is based on 5.6, Kindly help setup this SDK on 5.6

I can't understand why giving this

my code sends notifications only that it gives me an error at the end and I can't understand why someone can explain it to me?

Fatal error: Uncaught ExponentPhpSDK\Exceptions\ExpoException: "ExponentPushToken[unique]" is not a registered push notification recipient in C:\xampp\htdocs\teste\login\vendor\alymosul\exponent-server-sdk-php\lib\Exceptions\ExpoException.php:24 Stack trace: #0 C:\xampp\htdocs\teste\login\vendor\alymosul\exponent-server-sdk-php\lib\Expo.php(116): ExponentPhpSDK\Exceptions\ExpoException::failedCompletelyException(Array) #1 C:\xampp\htdocs\teste\login\index.php(24): ExponentPhpSDK\Expo->notify(Array, Array) #2 {main} thrown in C:\xampp\htdocs\teste\login\vendor\alymosul\exponent-server-sdk-php\lib\Exceptions\ExpoException.php on line 24

if you can help me, I would be very grateful!

New release

Hi there. :-) Thanks for your work, great to have a library for this. Do you have any plans on releasing a new version? When installing with composer, I get 1.1.2, which is now nearly one year old and does not contain some important fixes. Thanks!

Urgent - Please release version 1.1.2 - composer doesn't update the code

After many days of research and cache invalidation, I am pretty sure that composer will not pull any changes made after the date of version release.
In other words, version 1.1.1 will not include the code pushed after the 26th of September (note the since word below).
image

Therefore, I am asking You to make a release of version 1.1.2, since that is the only way for me to fix notification bugs in my production environment.
This is urgent, so please act quickly :)

Thank You for Your time.

Best regards,
Aleksandar

getInterest() fails with must be of type array, integer given

I noticed that my app was crashing if I was not passing an array as the interest to the notify function

I have been doing this for over a year now and not until, now when I had time to investigate, did I find out why

Here is a sample code from my project.

This one is how I want the code to look

public function send()
{
    $this->body();
    // Send the notification using Expo for Apple and Android
    $expo = Expo::normalSetup();

    $interestDetails = [$this->uniqueId, $this->to];

    // Subscribe the recipient to the server
    $expo->subscribe($interestDetails[0], $interestDetails[1]);

    // Build the notification data
    $notification = [
        'title' => $this->subject,
        'body'  => $this->body,
        'badge' => 1,
        'data'  => json_encode([
            'messageType' => $this->subject,
            'message'     => $this->body,
        ])
    ];

    if ($this->playSound) {
        $notification['sound'] = 'default';
    }

    // Notify an interest with a notification
    $response = $expo->notify($interestDetails[0], $notification);
}

This is how I had to modify the notify function call to make it work

public function send()
{
    ...

    // Notify an interest with a notification
    $response = $expo->notify([$interestDetails[0]], $notification);
}

Why was this happening?

ANSWER:

Expo notify function checks if the value passed is a string and if it is, it puts the string in an array and uses that as the interest

    public function notify($interests, array $data, $debug = false)
    {
        $postData = [];

        if (is_string($interests)) {    // What happens if it is an integer?
            $interests = [$interests];
        }

        if (count($interests) == 0) {
            throw new ExpoException('Interests array must not be empty.');
        }

        // Gets the expo tokens for the interests
        $recipients = $this->registrar->getInterests($interests);

        foreach ($recipients as $token) {
            $postData[] = $data + ['to' => $token];
        }

        $ch = $this->prepareCurl();

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));

        $response = $this->executeCurl($ch);

        // If the notification failed completely, throw an exception with the details
        if (!$debug && $this->failedCompletely($response, $interests)) {
            throw ExpoException::failedCompletelyException($response);
        }

        return $response;
    }

In my case, I am using the table primary key id as the unique identifier and that is an integer field. If you pass an integer field to the notify function it leads to problems. Here is the error...

<strong>Message:</strong> Argument 1 passed to ExponentPhpSDK\ExpoRegistrar::getInterests() must be of the type array, integer given, called in /<path>/<to>/<project>/vendor/alymosul/exponent-server-sdk-php/lib/Expo.php on line 100

In my app, which is a slimphp app, it would lead to a 500 server error

The reason this happens is because the if statement is skipped since it is not a string and then we call getInterest() which give us an error but not an exception. You throw an exception if there is an empty token but nothing for an interest related error

It would be nice if either some documentation is added to make sure it states to pass a string (for the unique id) or support integers or throw a proper exception if an integer is passed because you do not want this to be a possibility. In that case updating the "snippet" code in the README to have the exception would be nice

It is your library so you can handle this as you want but please provide a solution for this.

Handle more than 100 recipients when sending notifications

Error occurs whenever notification is being sent to over 100 recipients.

Unexpected response was received from Expo API. (ExponentPhpSDK\\Exceptions\\UnexpectedResponseException(code: 500): Unexpected response was received from Expo API. at .../vendor/alymosul/exponent-server-sdk-php/lib/Expo.php:221)

Exploring further, here's the actual error message

You can send a maximum of 100 notifications per request (received 7768); divide your requests. {"userId":5,"exception":"[object] (ExponentPhpSDK\\Exceptions\\UnexpectedResponseException(code: 500): You can send a maximum of 100 notifications per request (received 7768); divide your requests. at .../vendor/alymosul/exponent-server-sdk-php/lib/Expo.php:221)

Can't get exact error details from ExpoException

The doc page for expo's push notifications lists four kinds of error to be returned from the service, DeviceNotRegistered, MessageTooBig, MessageRateExceeded, and InvalidCredentials, but the ExpoException class doesn't provide a proper way to detect these, it only exposes the error message.

I'd rather not be regexping through the error messages; would you be able to add a way to retrieve this detail from the exception object? https://docs.expo.io/versions/latest/guides/push-notifications/#receipt-response-format

Badge clearing not working

I am noticing that if I set the badge number to 1, the app will remain on 1 even after the notification is viewed. This seems broken to me

Send data with notification

I am trying to send data with notification on a laravel backend to a react-native expo app. I managed to successfully send a notification, however, I can't seem to be able to send data (or don't know how).

So far here is my implementation :

$interestDetails = [$this->userId, $token];

// You can quickly bootup an expo instance
$expo = Expo::normalSetup();

// Subscribe the recipient to the server
$expo->subscribe($interestDetails[0], $interestDetails[1]);

// Build the notification data
$notification = ['body' => 'Hello World!', 'data' => ['message' => 'my message']];

// Notify an interest with a notification
$expo->notify($interestDetails[0], $notification);

Is sending data currently supported ? If so, how to send it ?

Thank you,

File write in `vendor/` breaks notification pushes

It looks like the library try to create a file in the vendor/ directory: #6

This breaks our app because we built a Docker image and the vendor/ directory is not writable.

I think that it's not a good idea to write a temporary file in vendor/.

Can we configure another path?

We may use sys_get_temp_dir() in order to get a writable path.

Storage tokens file for multiple app servers

We are currently using this package and have three app servers behind a load balancer. I did some source diving here and noticed the expo push tokens are stored in a local file (storage/tokens.json). I believe this can be problematic with multiple app servers as each app server will have different token subscriptions based on where the load balancer directs traffic.

I don't believe this package handles situations where there are multiple app servers. Any insights?

Thanks!

requires: php: >=7.0

I do not understand why you requires php7 (there are no deps) ! could you downgrade to php 5.6 -to support mor hosting-? or let me know if it is possible maybe i could fork it and do it by myself, thanks

an notify exception occurs on certain tokens

An notify exception occurs on certain tokens.
Error message is "\Exceptions\UnexpectedResponseException(code: 500):
Unexpected response was received from Expo API".

The causative token ends in "_lD]".
If you register multiple tokens including this one and send push notifications, an error will occur.
But Push notifications will not fail if only this token is used.
Is it possible that "_lD]" has been changed to some kind of control character?

souce code

    // EXPOセットアップ
    $expo = Expo::normalSetup();

    foreach ($expoPushTokens as $expoPushToken) {

        // EXPO登録
        Log::debug('subscribe expo', ['channel' => $channel, 'expo_push_token' => $expoPushToken]);

        try {
            $expo->subscribe($channel, $expoPushToken);
        } catch (\Exception $ex) {
            Log::error('subscribe exception', [$ex]);
            try {
                // EXPO解除
                $expo->unsubscribe($channel);
            } catch (\Exception $ex) {
                Log::error('subscribe->unsubscribe exception', [$ex]);
                return;
            }
            return;
        }
    }

    $notification = [
        'title' => $title,
        'body' => $body,
        'data' => json_encode($data),
        '_displayInForeground' => true,
    ];

    try {
        // プッシュ通知
        $expo->notify([$channel], $notification);
    } catch (\Exception $ex) {

   // ↓Location of error
Log::error('notify exception', [$ex]);
}

    try {
        // EXPO解除
        $expo->unsubscribe($channel);
    } catch (\Exception $ex) {
        Log::error('unsubscribe exception', [$ex]);
        return;
    }

Android users not receiving notifications reliably

I have this issue in production where Android users specifically are not receiving notifications properly. iOS on the other hand receives notifications each time they are pushed. I have them running in batches in the background with a delay for each job. This makes sure that the Expo API is not bombarded with requests, all jobs pass without any failure, meaning, the notifications are sent through.

I have also manually tried to send a notification to a specific android device, subscribing only that device to a channel, but it never goes through. Even though the response status is OK. Any thoughts on this?

“Attempt to assign property "newmessage6089" on null” because of a corrupted repository?

Our error log showed this:

Attempt to assign property "newmessage6089" on null

I'm pretty sure that the error comes from these lines:

// First token for this key
$storageInstance->{$key} = [$value];

And

$file = file_get_contents($this->storage);
return json_decode($file);

It looks like json_decode returned null because the file wasn't a valid JSON (sadly we didn't saved the file because we were in a rush to fix the issue).

The code may check that the content is a valid JSON before returning it:

$file = file_get_contents($this->storage);

try {
    return json_decode($file, null, 16, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
    return([]);
}

It would start on a fresh repository, I think it's the safest option.

Permission Denied

When I do a request to the api with a token, I got this error:

fopen(/var/www/html/vendor/alymosul/exponent-server-sdk-php/lib/Repositories/../../storage/tokens.json): Failed to open stream: Permission denied

I've a tried changing the permissions and its not working. I'm also on Docker and permissions should not be a problem.

Unexpected response was received from Expo API

Suddeny without changes in the code my console task that sends push notifications is crashing:

image

As I said, my code is OK, I tried checking the fields and the expotoken, but everything seems right.

Any ideas?

Working locally and giving 500 error on the server

Hello. We are using this repo in our project. There is no problem in local tests, but when we perform it on the server, we get a 500 error. Our server has ssl. As far as we guessed, exec_curl is not working. what do you think we should do?

Composer package is not up-to-date

Hello,

If I do:

compose require alymosul/exponent-server-sdk-php:1.1.2

Composer works alright and think it has downloaded the version 1.1.2 but in fact it's an older release, probably 1.1.1. We see that by the fact the setStorage method is not available, even though it was added on version 1.1.2.

On packagist we see the latest commit is c3fec55.

I'm assuming it's a problem of branch tagging but I could be wrong.

Empty value

I’m having this issue I. Production. Not sure if it’s to do with the volume of messages i’m Sending.

Any thoughts?

ErrorException: Creating default object from empty value in
/vendor/alymosul/exponent-server-sdk-php/lib/Repositories/ExpoFileDriver.php:49

TypeError: Argument 1 passed to ExponentPhpSDK\Expo::failedCompletely() must be of the type array

We had a type error from this library, I'm pretty sure that is it due to an error from Expo API, maybe when it doesn't respond or respond an error.

Stacktrace of the error:

TypeError: Argument 1 passed to ExponentPhpSDK\Expo::failedCompletely() must be of the type array, null given, called in /app/vendor/alymosul/exponent-server-sdk-php/lib/Expo.php on line 113
#18 vendor/alymosul/exponent-server-sdk-php/lib/Expo.php(128): failedCompletely
#17 vendor/alymosul/exponent-server-sdk-php/lib/Expo.php(113): notify
#16 [project's code …]
#1 vendor/symfony/console/Application.php(145): run
#0 bin/console(39): null

Line that trigger the error:

if (!$debug && $this->failedCompletely($response, $interests)) {

Code:

$response = $this->executeCurl($ch);

// If the notification failed completely, throw an exception with the details
if (!$debug && $this->failedCompletely($response, $interests)) {
    throw ExpoException::failedCompletelyException($response);
}

If $response is not an array, calling $this->failedCompletely($response, $interests) will fail because the first argument must be an array.

We can replicate the bug by changing value of $response: $response = null;. Then try to send a notification and you will have the same error.

Multiple Notification send at once

it sends multiple notifications at once, my code is as follow

<?php
   require_once('./vendor/autoload.php');
   require_once('./includes_/mysql_functions.php');


 $msg = 'Aloo';
$key = "ExponentPushToken[OcavxbB6AsB5wr_Ep7Fxhn]";
$title = "title";
  
  try{
      $expo = \ExponentPhpSDK\Expo::normalSetup();
  // Build the notification data
  $notification = ['to' => $key,'title' => $title,'body' => $msg];
  // Notify an interest with a notification
 $expo->notify('https://exp.host/--/api/v2/push/send',$notification);
  	
  $status = 'success';
}catch(Exception $e){
	echo $e;
}
  echo $status;
  ?>

interests vs recipients? FailedCompletely called even if most pushes went out ok.

I'm not sure what the original purpose of interests was , however I am using it to group a set of push messages together, say for a specific topic or even just by timestamp. This lets me essentially track the messages sent as a batch. which works great. Kinda simulates FCM topics.

$timestamp = date(DATE_ATOM);
 foreach ($db->query($sql) as $row) {
        //gather tokens from database and start pushing to expo server
        $expo->subscribe($timestamp, $row['token']);
    }
//send push
  $results = $expo->notify($timestamp, $notification);
 //delete the batch
 $expo->unsubscribe($timestamp);

however if i have one invalid push token in my database, it triggers fail completely, which I would think to mean fail completely is if not a single message was delivered. the code however is assuming that every device has its own interest, which then calls into question, what was interest for? I already have a unique recipient value, namely the expo push token.

private function failedCompletely(array $response, array **$interests**)
[..]

so instead of getting this:

0: {status: "ok", id: "440fec28-0696-4e40-b9c7-4396d06dc578"}
1: {id: "217f6c0c-9109-4445-bddc-cea0059cef53", status: "ok"}
2: {status: "error", message: ""ExponentPushToken[iCWoARH_b_IqDfTnnB7Nmr]" is not a registered push notification recipient"

Which i can work with, i get a complete failure exception on this batch, even though the message was indeed successfully sent to valid devices.

To get this working i changed this line in Expo.php:

if (!$debug && $this->failedCompletely($response, **$recipients**)) {
            throw ExpoException::failedCompletelyException($response);
        }

Tokens storage file not found

Hi guys, under windows 10 i get this error:

Fatal error: Uncaught Exception: Tokens storage file not found. in \vendor\alymosul\exponent-server-sdk-php\lib\Repositories\ExpoFileDriver.php on line 137

// You can quickly bootup an expo instance
$expo = \ExponentPhpSDK\Expo::normalSetup();

$channelName = 'user_528491';
$recipient = 'ExponentPushToken[xxxx]';

// // Build the notification data
$notification = ['body' => 'Hello World!', 'data'=> json_encode(array('someData' => 'goes here'))];

// // Notify an interest with a notification
$test= $expo->notify($channelName, $notification);

Change the storage folder

I have a project in Docker, and when I try to register an user with suscribe, it throws an error. I find that It throws an error about it cannot find the file tokens.json in the vendor folder.

It seems like is an issue with the permissions, composer generates the vendor folder with readonly permissions (and root as user).

Is possible add a parameter to configure the default folder where is going to be saved the tokens.json file?

Concept of channels

Question regarding the concept behind channels, I couldn't find corresponding implementation on expo side where they provide a pub / sub pattern with topics.

Is this an internal implementation via the package? ie. channelName

    $channelName = 'news';
    $recipient= 'ExponentPushToken[unique]';
    
    // You can quickly bootup an expo instance
    $expo = \ExponentPhpSDK\Expo::normalSetup();
    
    // Subscribe the recipient to the server
    $expo->subscribe($channelName, $recipient);
    

DeployBot problem

I have a project, using the DeployBot, every deploy in the develop or production, a new dir as created and the project builded in this folder.

The big problem: tokens.json
In any deploy made, a fresh install of the dependecies are made, and i lose my tokens.json.

I'll try do something here and send!

Urgent - Could not register the token provided for the interest, due to internal error.

Hi,
I have got following error. Can you please explain why is it ?

"Could not register the token provided for the interest, due to internal error."

And I have check the ExpoFileDriver.php file. So there has a variable called
private $storage = __DIR__.'/../../storage/tokens.json';

I have checked that storage folder and but I can not see any tokens.json file. Why is it ?

Typo in class Expo, in function notify

The current part of code, that checks whether the sending has completely failed working incorrect.

Here is this part:
if (!$debug && $this->failedCompletely($response, $interests)) { throw ExpoException::failedCompletelyException($response); }

if (!$debug && $this->failedCompletely($response, $interests)) {

It must be replace on:
if (!$debug && $this->failedCompletely($response, $recipients)) { throw ExpoException::failedCompletelyException($response); }

In fact, the function (failedCompletely) is called with the wrong parameter ($interests), correct parameter - $recipients. Also, local variables in the function (failedCompletely) must be renamed.

Because the main idea of ​​the function (failedCompletely) is to compare the total number of recipients with the number of failures to send a notification (and not with the number of interests/channels).

This code gives an exception (indicating that the entire function failed) if the number of failures in the mass sending list matches the number of interests. For example, when sending 50 by the recipient from one interest, one unsuccessful sending from 50 will lead to an exception.

Title nor body received in react native notification

Hello,
I am using laravel on the backend and this package to send notifications -> https://github.com/Alymosul/laravel-exponent-push-notifications

Everything works fine except that the title and body from the backend are not present in react native notification object that I received.

I don't get any errors but here's the data that's being sent to expo api.

In Expo.php notify function I dumped $postData to see what's actually sent to the api and he's what I get:

dump(json_encode($postData));

"[{"title":"Foo","body":"Message body!","sound":"default","badge":0,"ttl":0,"channelId":"Default","data":"{}","to":"ExponentPushToken[4ZVpodNvEJCxVUv-xxH8Rf]"}]"

Here's what I received in react native application.

{"userText":null,"isMultiple":false,"remote":true,"actionId":null,"notificationId":-1663189389,"data":{},"origin":"received"}

I never got this title nor body values when I received the notification. So, I am not sure what's going on here, because per expo docs this should be fine https://docs.expo.io/versions/latest/guides/push-notifications/#http2-api

I am not sure why I don't get these values title and body in this case.

Can't send notifications at all

SeePlease I need help in sending push notifications to anybody that installs my app on their android phone to get a push notification each time I create a post using PHP as the backend.

Here is my code for that:

$response = array();
require_once __DIR__.'/exponent-server-sdk-php/vendor/autoload.php';


		$channelName = 'video_alert';
		$recipient =  'ExponentPushToken[AAAAnrlyESE:APA91bHYeOkFi5MlUB9eitKn1yEuReJ1dNrRSnlMob0lcBLAjoanDaAIposGTBWQD164CGMV8F0hriJtsXuaFPdoKxEpjtrnXshoxlZQmxdlrCjP_F5TyRToNGP43YqwahCd6XYhKvwX]';
		
		// You can quickly bootup an expo instance
		$expo = \ExponentPhpSDK\Expo::normalSetup();
		
		// Subscribe the recipient to the server
		$expo->subscribe($channelName, $recipient);
		
		// Unsubscribe the recipient from the server
		$expo->unSubscribe($channelName, $recipient);
		
		// Build the notification data
		$notification = ['title' => 'Watch Movies', 'body' => 'Catch new latest movie ('.$movie_title.') on DooBuxx Movies today!', 'data' => json_encode(array('notification_type' => 'service_requested'))];
		try {
		// Notify an interest with a notification
		$expo->notify([$channelName], $notification);
		}  catch (ExpoException $e) {
			$response["message"] = $e->getMessage();
		 }

For the following part:

$channelName = 'video_alert';
        $recipient =  'ExponentPushToken[Server key]'; // I Inserted the server key i got from my firebase dashboard here. The package name is ok

Is the server key the right thing? or what? This is where I think I'm not doing it right. But I don't know what else to put there.

As you can see, I'm using the exponent-server-sdk-php that I cloned from GitHub to send the push notification but it's not sending anything after posting to the server.

Is there anything I'm doing wrong here? I have also checked the error log, but there is no erro in there.

When I posted the first time, a token file was created though but no notification was sent to the android phones that have the app installed.

I have configured my firebase credentials for the react native project I'm building after following the instructions from the expo website but all to no avail.

I know I'm not doing something all right here but can't seem to figure it out yet. Please help.

Asynchronous

Hi
Is it possible to get async notification ?
The code is subchronous and waiting for sending.
Thanks for reply.

Notification sound & badge functionality

Would be great to get sound and badges working on this.

For the time being i have just changed line 103 in Expo.php to this:

$postData[] = $data + ['to' => $token, 'sound' => 'default', 'badge' => 1];

Thanks

It doesn't work to send multiple notifications to different devices.

I was trying to use only the token to send multiple notifications, first sending the token on the server and the server is responsible for subscribing to the token in a topic, then I use the topic to send notifications it happens that when only one token significations work, but When I try to sign up another token the notifications do not work.

I jumped this part and tried to use only topics instead of token, I do even process sending the token on the server and server Subscribes the token in the topic, but instead of being based on tokens if it was based on topics, in this case in each topic has only one User and so maybe I think it should work, but only when I try to send notifications on more than a topic core in the array, it gives a bad error of the Expo server.

My code

`

$tokens = utils::getTokens(1, "",false,10000);

    if($tokens["total"] == 0) {
        $data["estado"] = "erro";
        $data["texto"] = "Infelizmente nenhum pessoa disponivel para o envio de notificações foi encontrada!";
    } else {

        // Notify an interest with a notification, only one recipient will receive it

        $t = [];

        foreach ($tokens["data"] as $token) {
                $t[] = $token["token"];
        }


        try {

            $expo = \ExponentPhpSDK\Expo::normalSetup();

            $title = $_POST["titulo"];
            $body = $_POST["conteudo"];
            $notification = ['title' => $title, "body"=>$body, 'data'=> json_encode(array('someData' => 'goes here'))];

            $expo->notify($t, $notification);

        
        } catch (Exception $e){

        }

        $data["estado"] = "ok";
        $data["texto"] = null;
        $data["total_ok"] = 0;
        $data["total_error"] = 0;

`

Is there limitation of number to subscribe ExpoToken?

Hi, Thanks for giving great service with push notification.
I want to know the number of tokens I can send at one time.

In the code,

$expo->subscribe($interestDetails[0], $interestDetails[1]);

How many I can subscribe tokens in one request?
Can I subscribe 10,000 tokens?

i am getting this message how to solve it ?

fopen(/var/www/html/app/vendor/alymosul/exponent-server-sdk-php/lib/Repositories/../../storage/tokens.json): failed to open stream: Permission denied

solution of it please.....

Notify with expo token directly

First I would like to say this is a very nice project.
For my use case, I would really like to send a notification without subscribing a user.
I already have the expo token stored.
Is this something worth having in your project?

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.