Search code examples
laravelpush-notificationamazon-sns

AWS SNS Push Notification using Laravel


I have searched AWS documentation and wasted a couple of hours but could not find the code to send push notifications using Laravel 8. Can anybody help in sending AWS SNS push notifications using Laravel?


Solution

  • I found my solution

    first need to add this composer package

    "aws/aws-sdk-php"
    

    The code for generate endpoint ARN

    $platformApplicationArn = config('services.sns.android_arn');
    
    $client = new SnsClient([
            'version'     => '2010-03-31',
            'region'      => config('services.sns.region'),
            'credentials' => new Credentials(
                config('services.sns.key'),
                config('services.sns.secret')
            ),
        ]);
    
        $result = $client->createPlatformEndpoint(array(
            'PlatformApplicationArn' => $platformApplicationArn,
            'Token'                  => $deviceToken,
        ));
    
        $endPointArn = isset($result['EndpointArn']) ? $result['EndpointArn'] : '';
    

    The code for send push notification

        $client = new SnsClient([
                'version'     => '2010-03-31',
                'region'      => config('services.sns.region'),
                'credentials' => new Credentials(
                    config('services.sns.key'),
                    config('services.sns.secret')
                ),
            ]);
    
        $fcmPayload = json_encode(
                [
                    'notification' => 
                        [
                            'title' => 'Test Notification',
                            'body'  => 'Hi from RB',
                            'sound' => 'default',
                        ],
                ]
            );
    
        $message = json_encode(['GCM' => $fcmPayload]);
    
        $client->publish([
              'TargetArn'        => $userDeviceToken->endpoint_arn,
              'Message'          => $message,
              'MessageStructure' => 'json',
        ]);