Sending Amazon SNS from my PHP server
Asked Answered
S

3

16

I have an application both in Android and iOS platforms. Both of them are registered with Amazon SNS. This is successfully done, because if I have the device tokens, then I can login to my applications dashboard in Amazon, and can send SNS from their console.

I want it make it automated. I mean have my own PHP admin site (and API) for the applications. I want add another page to the admin site, that can request the amazon SNS to send single payload with device identifier, registration keys and message body provided with the request.

First question - Is it possible? I have seen Urban Airship allows it, so it is usual that amazon also does?

Second question - What is the process? Since I am working on this for one of my client and all the docs are not accessible to me. My client is unable to explain it to amazon.

When I have registered my apps to amazon, shouldn't they provide me some keys and secrets that I can use to call their service over http?

Sextillion answered 4/2, 2014 at 15:56 Comment(0)
S
27

Yes, it is possible. Download the Amazon Web Service (AWS) PHP SDK from here and follow their instructions to use this in you web server API. Get the Platform Application ARN's for both iOS and android, access key id and the secret key from Amazon console. And then try the code below and follow the commented out instructions:

<?php

require '<path to this file>/aws.phar';
use Aws\Sns\SnsClient;

if(isset($_POST['submit']))
{
    $push_message = $_POST['push_message'];

    if(!empty($push_message))
    {
        // Create a new Amazon SNS client
        $sns = SnsClient::factory(array(
            'key'    => '<access key>',
            'secret' => '<app secret>',
            'region' => '<region code>'
            ));

        // region code samples: us-east-1, ap-northeast-1, sa-east-1, ap-southeast-1, ap-southeast-2, us-west-2, us-gov-west-1, us-west-1, cn-north-1, eu-west-1

        $iOS_AppArn = "<iOS app's Application ARN>";
        $android_AppArn = "<android app's Application ARN>";

        // Get the application's endpoints
        $iOS_model = $sns->listEndpointsByPlatformApplication(array('PlatformApplicationArn' => $iOS_AppArn));
        $android_model = $sns->listEndpointsByPlatformApplication(array('PlatformApplicationArn' => $android_AppArn));

        // Display all of the endpoints for the iOS application
        foreach ($iOS_model['Endpoints'] as $endpoint)
        {
            $endpointArn = $endpoint['EndpointArn'];
            echo $endpointArn;
        }

        // Display all of the endpoints for the android application
        foreach ($android_model['Endpoints'] as $endpoint)
        {
            $endpointArn = $endpoint['EndpointArn'];
            echo $endpointArn;
        }

        // iOS: Send a message to each endpoint
        foreach ($iOS_model['Endpoints'] as $endpoint)
        {
            $endpointArn = $endpoint['EndpointArn'];

            try
            {
                $sns->publish(array('Message' => $push_message,
                    'TargetArn' => $endpointArn));

                echo "<strong>Success:</strong> ".$endpointArn."<br/>";
            }
            catch (Exception $e)
            {
                echo "<strong>Failed:</strong> ".$endpointArn."<br/><strong>Error:</strong> ".$e->getMessage()."<br/>";
            }
        }

        // android: Send a message to each endpoint
        foreach ($android_model['Endpoints'] as $endpoint)
        {
            $endpointArn = $endpoint['EndpointArn'];

            try
            {
                $sns->publish(array('Message' => $push_message,
                    'TargetArn' => $endpointArn));

                echo "<strong>Success:</strong> ".$endpointArn."<br/>";
            }
            catch (Exception $e)
            {
                echo "<strong>Failed:</strong> ".$endpointArn."<br/><strong>Error:</strong> ".$e->getMessage()."<br/>";
            }
        }
    }
}   
?>

The code is tested and it works, feel free to change as your need.

Solis answered 7/2, 2014 at 14:44 Comment(4)
I would like to know how to send an APNS message with a badge and sound also. I am looking for that answer now.Springlet
@Springlet check my answer below if you still needed help with it.Franklinfranklinite
Hey is there a way I can get in touch with you? I'd like to discuss about SNS and PHP and managing push notifications. I have everything setup, the AWS sdk setup, as well as the server running. I am also able to send push notifications from the AWS console, but now trying to manage it in php. I'm a developer and will know how to code and implement any pseudocode, but I'd like to get in touch with you since you seem to know what you're talking about after reading your answer Can you get in touch with me via skype or email? [email protected] or pavankatariaStatvolt
can you catch errors from try { $sns->publish(array('Message' => $push_message, 'TargetArn' => $endpointArn)); } catch(Exception $e){ } i dont think it will prevent the application from closingEyas
F
5

If you want to send alert sound and badge number with custom payload replace this code block // iOS: Send a message to each endpoint foreach ($iOS_model['Endpoints'] as $endpoint)

with this code block

    foreach ($iOS_model['Endpoints'] as $endpoint)
{
    $endpointArn = $endpoint['EndpointArn'];

    try
    {
        $sns->publish(array(
        'TargetArn' => $endpointArn,
        'MessageStructure' => 'json',
        'Message' => json_encode(array(
            'default' => $title,
            'APNS_SANDBOX' => json_encode(array(
                'aps' => array(
                    'alert' => $title,
                    'sound' => 'default',
                    'badge' => 1
                    ),
                    // Your custom payload if needed
                    'whatever' => 'here',
                    'andwhatever' => 'here'
                    ))

            ))
    ));


        echo "1";//Success push
    }
    catch (Exception $e)
    {
        echo "2";//Failed push
    }
}
Franklinfranklinite answered 5/3, 2015 at 21:5 Comment(3)
I cant wait to get back to my production machine to test this out. So I've been looking around in the Amazon SNS console, I see how I can subscribe (manually) a device token (ios, specifically)... can that be done programmatically from PHP, assuming it would trigger a user confirmation to enable / authorize push notification for my app? I have all my device ids / tokens (android and ios) going into mysql db, so Im hoping I can loop through that database to send to ios users and android users repectively... downloading the SDK and spending the next day or two with it!Gump
Hi @Gump you sure can follow this guide here medium.com/aws-activate-startup-blog/…Franklinfranklinite
How to set title and body of a notification for iOS?Mahout
E
0

i believe the simplest way to send push notification to single device or user is by this code

                $snsClient = Aws\Sns\SnsClient::factory(array(
                    'credentials' => array(
                        'key'    => AMAZON_KEY,
                        'secret' => AMAZON_SECRET,
                    ),
                    'region'  => AMAZON_REIGON
                )); 


          //you should have variable that have user end single point .

           $result = $snsClient->publish(array(

                    'Message' => "push text message",
                    'TargetArn' => $user_end_point
                ));
Ephraimite answered 22/8, 2016 at 23:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.