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

0

Does anyone know of a PHP script that works, to send msgs to GCM and APNS (android and iphone)? The user fills in form, the PHP script processes and submits to GCM and APNS. From here the natural push push routine follows. I just need the PHP part.

    
asked by anonymous 14.08.2016 / 04:45

1 answer

1

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

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

You can not solve the problem without knowing if you want to send 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 number 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 in Phonegap should look something like:

It will look 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 semi-ready code gist :

  

Note: The GCM url is link

<?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 bit more complex, because it requires some server configuration in some cases

Solution 1 for APN

There is a repository , if you use only push and feedback you will need only OpenSSL, this is usually already enabled in Most servers:

  • Requires PHP 5.3.0+ and support for OpenSSL, PCNTL, System V shared memory and semaphore, to configure the server to run this command (the PATH is optional, and will be required if the file location is different) p>

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

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

Push Push:

<?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 the development link

  • Installation 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 push 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);

Feedback Service 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
  ));

$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);
    
14.08.2016 / 04:55