ServiceWorker を
この
OneSignal の
サーバ側に
参考
Webhook の
以下は、
前提
バックエンド、
バックエンド
Django 、
- Django (1.11.11)
- wagtail (1.13.1)
- puput (0.9.2.1)
- djangorestframework (3.6.4)
フロントエンド
react と、
- react@16.2.0
- rmwc@1.1.2
- react-helmet@5.2.0
実装
OneSignal で Webhooks URL を 設定する
OneSinal の
cors をX-OneSignal-Event
と
var OneSignal = window.OneSignal || []; OneSignal.push(["init", { appId: "${config.oneSignalAppId}", autoRegister: false, allowLocalhostAsSecureOrigin: true, notifyButton: { enable: false /* Set to false to hide */ }, webhooks: { cors: true, // Defaults to false if omitted "notification.displayed": "https://mutter.monotalk.xyz/notification/collect/", "notification.clicked": "https://mutter.monotalk.xyz/notification/collect/", "notification.dismissed": "https://mutter.monotalk.xyz/notification/collect/" } }]);
サーバ側の 実装
サーバ側は、
rest_framework.py
api_view
デコレータでPOST のみを 受け付けるようにしました。
Header の設定有無で、 HTTP_400_BAD_REQUEST
を返すようにしましたが、 referrer の チェック等の 実装して おいた ほうが いいかもしれません。
Header のチェックで 問題が なければ、 POST された データを、 Measurement Protocol の 形式に 変換して 送信します。
content-type は、x-www-form-urlencoded なので、 辞書を データと して 直接送信します。 from django.http import Http404 from rest_framework import status from rest_framework.decorators import api_view import json import requests @api_view(['POST']) def collect_notification_event(request): """ List all code snippets, or create a new snippet. """ event = request.META.get('HTTP_X_ONESIGNAL_EVENT', None) if event not in ["notification.clicked","notification.displayed","notification.dismissed"]: return Response(status=status.HTTP_400_BAD_REQUEST) if request.method == 'POST': json_data = request.data payload = {"v": "1", "t": "event", "tid": "UA-xxxxxxxx-x", "cid": json_data.get("userId", ""), "hl": "ja", "ni": "1", "ec": "Notification", "ea": json_data.get("event", ""), "el": json_data.get("heading", "") } r = requests.post("https://www.google-analytics.com/collect", data=payload) return Response(status=r.status_code) else: return Response(status=status.HTTP_400_BAD_REQUEST)
urls.py
from home.api.rest_framework import collect_notification_event urlpatterns = [ url(r'^notification/collect/$', collect_notification_event, name='collect_notification_event') ]
動作確認 OneSingal から、 WebPush を 送信する
ブラウザを
OneSingal の
POST データの
MixPanel も
以上です。
コメント