« centos7文字化け | メイン | PHP function どこで設定? »
2018年03月07日
web push を PHPで
公開鍵と秘密鍵は以下で作成https://web-push-codelab.glitch.me/
以下の感じでブラウザ側から許可もらって、
ブラウザの公開鍵(keys)
ともう一つのセキュリティ用の追加の認証キー?(auth)
とendpointを取得しサーバ側に保存する
/* * * Push Notifications codelab * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License * */ /* eslint-env browser, es6 */ console.log("start"); var applicationServerPublicKey = 公開鍵をここに-UW0Q'; var pushButton = document.querySelector('.js-push-btn'); var isSubscribed = false; var swRegistration = null; if (typeof navigator.serviceWorker !== "undefined" && typeof window.PushManager !== "undefined") { console.log('Service Worker and Push サポートされてます!'); navigator.serviceWorker.register('sw.js').then(function(swReg) { "use strict"; console.log('Service Worker is registered', swReg); swRegistration = swReg; initialiseUI(); }).catch(function(error) { "use strict"; console.error('Service Worker Error', error); }); } else { console.warn('未サポートブラウザ'); pushButton.textContent = '非対応ブラウザ'; } function urlB64ToUint8Array(base64String) { "use strict"; const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } function initialiseUI() { "use strict"; pushButton.addEventListener('click', function() { //2度押し抑制 pushButton.disabled = true; if (isSubscribed) { //ユーザー解除をここに } else { //ユーザー登録を行う subscribeUser(); } }); // Set the initial subscription value swRegistration.pushManager.getSubscription().then(function(subscription) { isSubscribed = !(subscription === null); if (isSubscribed) { console.log('既に通知希望済'); } else { console.log('通知未希望'); } updateBtn(); }); } //****************************** // ユーザー登録 //****************************** function subscribeUser() { "use strict"; const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey); console.log(applicationServerKey); swRegistration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: applicationServerKey }).then(function(subscription) { console.log('ブラウザにPUSH許可されました', subscription); //ブラウザ側からもらった subscription をサーバ側に保存する updateSubscriptionOnServer(subscription); isSubscribed = true; updateBtn(); }).catch(function(err) { console.log('Failed to subscribe the user: ', err); updateBtn(); }); } //****************************** // 通知OKを頂いた後のブラウザからもらった情報の処理 //***************************** function updateSubscriptionOnServer(subscription) { "use strict"; //とりあえず画面上に表示 const subscriptionJson = document.querySelector('.js-subscription-json'); const subscriptionDetails = document.querySelector('.js-subscription-details'); if (subscription) { subscriptionJson.textContent = JSON.stringify(subscription); subscriptionDetails.classList.remove('is-invisible'); } else { subscriptionDetails.classList.add('is-invisible'); } //サーバへ情報を転送し保存を本来行う } //************************** // ボタンの表示変更 //************************** function updateBtn() { "use strict"; console.log("Notification",Notification.permission); if (Notification.permission === 'denied') { pushButton.textContent = '通知はブロック済み.'; pushButton.disabled = true; updateSubscriptionOnServer(null); return; } if (isSubscribed) { pushButton.textContent = 'PUSH通知OFF'; } else { pushButton.textContent = 'PUSH通知ON'; } pushButton.disabled = false; }
サーバ側PUSHを発信する場合はweb-push-libs/web-push-phpを利用
https://github.com/web-push-libs/web-push-php
ダウンロードしてcomposerでインストール PHP7必須だった
cd web-push-php-master/
composer install
インストール後は
require(__DIR__ . '/vendor/autoload.php'); $public_key = "サーバ側の公開鍵"; $private_key = "サーバ側の秘密鍵"; $auth = array( 'VAPID' => array( 'subject' => 'https://secure.m-kaihatsu.com', 'publicKey' => $public_key, 'privateKey' => $private_key, ), ); $webpush = new \Minishlink\WebPush\WebPush($auth); $payload = [ 'title' => '通知があります。', 'message' => "poge", 'url' => 'https://secure.m-kaihatsu.com' ]; $user["key"] = "ユーザー側から取得した公開鍵(key)";//p256dh $user["auth"] = "ユーザー側からゲットした追加の認証キー?auth";//auth $user["endpoint"] = "ユーザー側からゲットしたエンドポイントのURL"; $res = $webpush->sendNotification( $user["endpoint"], json_encode( $payload ), // jsonで送ると、pushイベントでjsonでデータを取得できる。 $user["key"], $user["auth"], true );
細かいことはまだわかってないけど概要のみ
投稿者 muuming : 2018年03月07日 09:01