如何获得设备id(播放器id)使用PHP的单信号浏览器推送通知


how to get device id (player id) using php for onesignal browser push notification?

我想为订阅我网站通知的用户添加自定义标签。但要做到这一点,我需要他们的playerid,我无法获取特定用户的playerid。

<?php
$fields = array( 
'app_id' => 'app_id', 
'tags' => array('user_id' => ''.$user_id.'','user_email' => ''.$user_email.'','tag3' => ''.$tag3.'','tag4' => ''.$tag4.'',)
); 
$fields = json_encode($fields); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/players/'.$playerID); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
$response = curl_exec($ch); 
curl_close($ch); 
$resultData = json_decode($response, true);
?>

你需要从onessignal javascript中调用getUserId来从浏览器中获取玩家id。

OneSignal.push(function() {
  OneSignal.getUserId(function(userId) {
    console.log("OneSignal User ID:", userId);
    // (Output) OneSignal User ID: 270a35cd-4dda-4b3f-b04e-41d7463a2316    
  });
});

我正在做的是在getUserId回调函数中创建一个ajax调用,该函数将userID作为参数发送。

然后我将它存储在php中的用户会话中,并在需要时使用它。

但是我不确定这里是否有任何缺点

我已经在数据库和本地存储中保存了玩家id因为这个脚本运行在每个页面加载,所以我检查localstorage是否有播放器id,然后我不发送ajax来保存它。

<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
window.OneSignal = window.OneSignal || [];
OneSignal.push(function() {
    OneSignal.init({
        autoResubscribe:true,
        appId: "your_app_id",
        safari_web_id: "your_safari_app_id",
        notifyButton: {
            enable: true,
        },
    });
    if(!localStorage.getItem('player_id')){
        OneSignal.getUserId().then(function(userId) {
            localStorage.setItem('player_id',userId)
            let xhttp = new XMLHttpRequest();
            // console.log("OneSignal User ID:", userId);
            // (Output) OneSignal User ID: 270a35cd-4dda-4b3f-b04e-41d7463a2316
            let data = new FormData();
            data.append('player_id', userId);
            xhttp.open('POST','/onesignal/save-player-id',true)
            xhttp.send(data);
        });
    }
});

更多细节请点击此处