Thứ Tư, 11 tháng 5, 2016

Hướng dẫn sử dụng PHP và Firebase gửi Push Notification đến iOS device.

Trước hết, ta tạo tài khoản Firebase hoặc đăng nhập dùng account của Google. Trong phần Dashboard của Firebase ta ghi nhận 2 chuỗi mã là uid và secret key để dùng sau này:
Tiếp theo ta dùng code php để generate Default Token. Lưu ý: Default Token này không phải là token mà iOS device (mà ta sẽ đề cập sau) dùng để thực chứng với APNS (Apple Push Notification Service). Default token này dùng để thực chứng khi chạy code PHP truy xuất Database của Firebase.
Để generate Default Token ta dùng source PHP có trên Git Token Generator do Firebase cung cấp. Hãy tải source này theo hướng dẫn dùng tool composer. Sau đó tạo file PHP :
// Generate Firebase token to login Firebase
require_once 'vendor/autoload.php';

use Firebase\Token\TokenException;
use Firebase\Token\TokenGenerator;
 try {

  $generator = new TokenGenerator('iGUWEsXOJbTSc74kykPL1ww1SYZ71zz8BoDpVIqP');
  $token = $generator
   ->setData(array('uid' => '002a448c-30c0-4b87-a16b-f70dfebe3386'))
   ->create();
 } catch (TokenException $e) {
  echo "Error: ".$e->getMessage();
 }
 echo $token;

Chạy file PHP ta được Default Token:
Kế đến ta tải source PHP cho Firebase theo link Git PHP-Firebase (bạn nên dùng Composer để tải). Sau đó đưa Default Token vào code để request data từ Firebase như sau:
require_once 'vendor/autoload.php';

const DEFAULT_URL = 'https://YOUR_FIREBASE_DOMAIN.firebaseio.com/';
const DEFAULT_TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhZG1pbiI6ZmFsc2UsImRlYnVnIjpmYWxzZSwiZCI6eyJ1aWQiOiIwMDJhNDQ4Yy0zMGMwLTRiODctYTE2Yi1mNzBkZmViZTMzODYifSwidiI6MCwiaWF0IjoxNDYyODUyNjU0fQ.Vh0-NOgsy7l3EAdFwoUaptNV4Mi3tCHeIg1N-Uo8n6I';
const DEFAULT_PATH = '/firebase/example';

$firebase = new \Firebase\FirebaseLib(DEFAULT_URL, DEFAULT_TOKEN);

// --- reading the stored string from Firebase ---
$name = $firebase->get(DEFAULT_PATH . '/name/contact001');

///// Sending Push Notification of info from Firebase to device
// Put your device token here (without spaces):
$deviceToken = 'YOUR_DEVICE_TOKEN'; // device token này nhận từ APNS khi bạn chạy app iOS Push Notification client

// Put your private key's passphrase here:
$passphrase = 'YOUR_PASSPHRASE'; // passphrase là password của file .p12

$message = $name;
$url = 'www.johndoe.info';

if (!$message || !$url)
    exit('Example Usage: $php newspush.php \'Breaking News!\'');

////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'YOUR_PEM_FILENAME.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

// Open a connection to the APNS server
$fp = stream_socket_client(
  'ssl://gateway.sandbox.push.apple.com:2195', $err,
  $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

if (!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;

// Create the payload body
$body['aps'] = array(
  'alert' => $message,
  'sound' => 'default',
  'link_url' => $url,
  );

// Encode the payload as JSON
$payload = json_encode($body);

// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));

if (!$result) {echo 'Message not delivered' . PHP_EOL;}
else{ echo 'Message successfully delivered' . PHP_EOL;}
// Close the connection to the server
Trong đoạn code trên, đoạn đầu là để request lấy dữ liệu về từ Firebase.
$name = $firebase->get(DEFAULT_PATH . '/name/contact001');
Đoạn code tiếp theo để tạo stream. Lưu ý:
- deviceToken là token mà bạn nhận được khi chạy app iOS Push Notification phía client.
- Passphrase là pass của file .p12 được export từ keychain.
- bạn cần tạo file YOUR_PEM_FILENAME.pem từ file .p12 để có thể attach vào source code. Cách tạo file .pem bạn có thể tham khảo từ link Push Notification Tutorial.
Code tạo stream cho message:
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'YOUR_PEM_FILENAME.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

// Open a connection to the APNS server
$fp = stream_socket_client(
  'ssl://gateway.sandbox.push.apple.com:2195', $err,
  $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
Sau đó là gửi message lên APNS:
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
Nhờ đó thông qua APNS gửi Notification về cho iOS device. Đây là Source Demo. Ngoài ra bạn có thể tham khảo cách tạo một ứng dụng iOS đơn giản để nhận Notification ở "Hướng dẫn tạo ứng dụng iOS đơn giản nhận Push Notification từ APNS". Chúc bạn thành công.