user8022208
user8022208

Reputation:

how to switch onesignal keys in laravel to send push notifications to different accounts

I have one laravel api for two different apps which has different onesignal keys, I was wondering if it is possible to send a push notification depending on the keys I want to use.

In config/services I have:

'onesignal' => [
    'app_id' => env('ONESIGNAL_APP_ID_1'),
    'rest_api_key' => env('ONESIGNAL_REST_API_KEY_1')
],

In .env I have the two keys, how can I switch them?

ONESIGNAL_APP_ID_1='xxx'
ONESIGNAL_REST_API_KEY_1='xxx'

ONESIGNAL_APP_ID_2='yyy'
ONESIGNAL_REST_API_KEY_2='yyy'

Upvotes: 4

Views: 1319

Answers (2)

Lucas Dalmarco
Lucas Dalmarco

Reputation: 333

For those using the "berkayk/laravel-onesignal" package, you can create your own function that call the package "sendNotificationCustom" function passing in params the "app_id" and "api_key" props. The second app ids you can keep in .env file.

Here an example:

  public static function sendToDifferentApp($message, $headings, $tags, $data){

   $contents = array(
       "en" => $message
   );

   $params = array(
       'app_id' => env('ONESIGNAL_SECOND_APP_ID'),
       'contents' => $contents,
       'filters' => $tags,
       'api_key' => env('ONESIGNAL_SECOND_APP_REST_API_KEY'),
   );

   if (isset($data)) {
       $params['data'] = $data;
   }

   if(isset($headings)){
       $params['headings'] = array(
           "en" => $headings
       );
   }

   OneSignal::sendNotificationCustom($params);

}

Upvotes: 1

user8022208
user8022208

Reputation:

Ok I found the solution from kikutou in github, the solution:

I made two channels and extended to original from onesignal

namespace App\Channels;

use Berkayk\OneSignal\OneSignalClient;
use NotificationChannels\OneSignal\OneSignalChannel;

class OneSignalFirstChannel extends OneSignalChannel
{
    public function __construct()
    {
        $oneSignal = new OneSignalClient(env("FIRST_ONESIGNAL_APP_ID"), env("FIRST_ONESIGNAL_REST_API_KEY"),null);
        parent::__construct($oneSignal);
    }

}

And

namespace App\Channels;

use Berkayk\OneSignal\OneSignalClient;
use NotificationChannels\OneSignal\OneSignalChannel;

class OneSignalSecondChannel extends OneSignalChannel
{
    public function __construct()
    {
        $oneSignal = new OneSignalClient(env("Second_ONESIGNAL_APP_ID"), env("Second_ONESIGNAL_REST_API_KEY"),null);
        parent::__construct($oneSignal);
    }

}

and finally, use the notification

public function via($notifiable)
{
        return [OneSignalFirstChannel::class, OneSignalSecondChannel::class];
}

Upvotes: 1

Related Questions