How to send Push Notification to android and iphone with form processed by php?

Asked

Viewed 1,841 times

0

Does anyone know of a working PHP script for sending msgs to GCM and APNS (android and iphone)? The user fills in form, the PHP script processes and sends to GCM and APNS. From there follows the natural push sending routine. I only need the PHP part.

1 answer

1


PHP is back-end, or run on an HTTP server has nothing to do with android, it can never directly control the smartphone, or anything.

You must first learn the difference of back-end and front-end, what is server and what is client, knowing this will understand the layers.

There is no way to solve the problem without knowing if you want to send it to multiple users and what causes the notification call. PHP will have nothing to do with this action directly, it will at most contain a data that is a number, string or boolean and the Android/iOS app will fetch this url via http to check the data, after receiving the data the APP is who will do the rest.

The PushNotification Phonegap should look something like:

It’ll be something like:

var push = PushNotification.init({
    android: {
        senderID: "12345679"
    },
    browser: {
        pushServiceURL: 'http://[minha url]/pagina.php'
    },
    ios: {
        alert: "true",
        badge: "true",
        sound: "true"
    },
    windows: {}
});

push.on('registration', function(data) {
    // data.registrationId
});

push.on('notification', function(data) {
    // data.message,
    // data.title,
    // data.count,
    // data.sound,
    // data.image,
    // data.additionalData
});

push.on('error', function(e) {
    // e.message
});

And to send the request via GCM I found this code semi-ready gist:

Note: the url for sending GCM is https://android.googleapis.com/gcm/send

<?php

// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );


$registrationIds = array( $_GET['id'] );

// prep the bundle
$msg = array
(
    'message'    => 'here is a message. message',
    'title'      => 'This is a title. title',
    'subtitle'   => 'This is a subtitle. subtitle',
    'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1,
    'largeIcon' => 'large_icon',
    'smallIcon' => 'small_icon'
);

$fields = array
(
    'registration_ids' => $registrationIds,
    'data'             => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);

echo $result;

APN:

APN is a little more complex as it requires some server settings in some cases

Solution 1 for APN

There is a repository https://github.com/immobiliare/ApnsPHP, if you are going to use only push and feedback will only need Openssl, usually this is already activated on most servers:

  • Requires PHP 5.3.0+ and support for Openssl, PCNTL, System V Shared memory and Semaphore, to configure the server run this command (the PATH is opitional, and will be comment required if the file location is different)

    ./configure --with-openssl[=PATH] --enable-pcntl --enable-sysvshm --enable-sysvsem
    
  • If you plan to use only Push and the Feedback provider without the server part then you will only need Openssl:

    ./configure --with-openssl[=PATH]
    

Push sending:

<?php

// Adjust to your timezone
date_default_timezone_set('America/Sao_Paulo');

// Using Autoload all classes are loaded on-demand
require_once 'ApnsPHP/Autoload.php';

// Instantiate a new ApnsPHP_Push object
$push = new ApnsPHP_Push(
    ApnsPHP_Abstract::ENVIRONMENT_SANDBOX,
    'server_certificates_bundle_sandbox.pem'
);

// Set the Provider Certificate passphrase
// $push->setProviderCertificatePassphrase('test');

// Set the Root Certificate Autority to verify the Apple remote peer
$push->setRootCertificationAuthority('entrust_root_certification_authority.pem');

// Connect to the Apple Push Notification Service
$push->connect();

// Instantiate a new Message with a single recipient
$message = new ApnsPHP_Message('1e82db91c7ceddd72bf33d74ae052ac9c84a065b35148ac401388843106a7485');

// Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
// over a ApnsPHP_Message object retrieved with the getErrors() message.
$message->setCustomIdentifier("Message-Badge-3");

// Set badge icon to "3"
$message->setBadge(3);

// Set a simple welcome text
$message->setText('Hello APNs-enabled device!');

// Play the default sound
$message->setSound();

// Set a custom property
$message->setCustomProperty('acme2', array('bang', 'whiz'));

// Set another custom property
$message->setCustomProperty('acme3', array('bing', 'bong'));

// Set the expiry value to 30 seconds
$message->setExpiry(30);

// Add the message to the message queue
$push->add($message);

// Send all messages in the message queue
$push->send();

// Disconnect from the Apple Push Notification Service
$push->disconnect();

// Examine the error message container
$aErrorQueue = $push->getErrors();
if (!empty($aErrorQueue)) {
    var_dump($aErrorQueue);
}

Feedback:

<?php
// Adjust to your timezone
date_default_timezone_set('America/Sao_Paulo');

// Using Autoload all classes are loaded on-demand
require_once 'ApnsPHP/Autoload.php';

// Instanciate a new ApnsPHP_Feedback object
$feedback = new ApnsPHP_Feedback(
    ApnsPHP_Abstract::ENVIRONMENT_SANDBOX,
    'server_certificates_bundle_sandbox.pem'
);

// Connect to the Apple Push Notification Feedback Service
$feedback->connect();

$aDeviceTokens = $feedback->receive();
if (!empty($aDeviceTokens)) {
    var_dump($aDeviceTokens);
}

// Disconnect from the Apple Push Notification Feedback Service
$feedback->disconnect();

Solution 2 for APN

An extension (need to install on the server or compile there) that facilitates development http://libcapn.org/php-apn/

  • Facility with pecl:

    Type in the terminal

    pecl install apn
    

    Or

    cd php-apn
    pecl install package.xml
    
  • Manual installation:

    Type in the terminal:

    cd php-apn
    phpize
    ./configure
    make
    make install
    

Push sending code:

// APNS contex
$apn = apn_init();
apn_set_array($apn, array(
      'certificate' => 'apns-dev-cert.pem',
      'private_key' => 'apns-dev-key.pem',
      'private_key_pass' => 'qwerty',
      'mode' => APN_SANDBOX
  ));

// Notification Payload context
$payload = apn_payload_init();
apn_payload_set_array($payload, array(
      'body' => 'This push was sent using PHP && php-apn',
      'sound' => 'default',
      'badge' => 34,
      'tokens' => array (
          'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
          'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY'
      )
));
apn_payload_add_custom_property($payload, 'test', 56);

$error = NULL;
$errcode = 0;

// Opening Apple Push Notification Service connection...
if(apn_connect($apn, $error, $errcode)) {
    // and if ok, try send push notification....
    if(!apn_send($apn, $payload, $error, $errcode)) {
        echo 'Could not sent push notification: ' . $error;
    }
} else {
    echo 'Could not connected to Apple Push Notification Servece: ' . $error;
}

apn_close($apn);
apn_payload_free($payload);
apn_free($apn);

Code of the Feedback service:

// APNS contex
$apn = apn_init();
apn_set_array($apn, array(
      'certificate' => 'apns-dev-cert.pem',
      'private_key' => 'apns-dev-key.pem',
      'private_key_pass' => 'qwerty',
      'mode' => APN_SANDBOX
  ));

$error = NULL;
$errcode = 0;

if(apn_feedback_connect($apn, $error, $errcode)) {
    $tokens = apn_feedback($apn, $error, $errcode);
    if(!is_array($tokens)) {
        echo 'Failed to obtain device tokens: ' . $error;
    } else {
      foreach($tokens as $token) {
          echo 'Token: '.$token;
      }
    }
} else {
    echo 'Failed to connect to Apple Push Feedback Service: ' . $error;
}

apn_close($apn);
apn_free($apn);
  • Guilherme Nascimento, I know. I’ve been developing for web with PHP for a long time. But I’m developing for mobile less time. I already have apps running blz. But what I need at the moment is to add a form in a web application where the client will define the message he wants to send to the app that is installed on customers' smartphone. Naturally this form will be processed by a php script that will push to android and iphone, via GCM and APNS.

  • @Rondanetbr after its edition was clear, but before it implied something totally different, however it seems a good question, I hope the code helps you, I fixed something that was missing in it (echo).

  • Thanks @Guilhermenascimento. I think it will help me a lot. Abs.

  • 1

    GCM is dated, the FCM has now supplanted it and if I’m not mistaken is slightly less difficult to use

  • 1

    @Jeffersonquesado opa, thanks, I will update the answer as soon as I have an opportunity.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.