How to get user_id for OneSignal web notifications

I’m building website that allow users to register and receive real-time notification based on some events, i trying to use OneSignal for web notifications, so i already done this part and need help in collecting user token known as player_id and subscriber_id.

I have checked OneSignal documentation with no luck to find answers to question below.
https://documentation.onesignal.com/docs/web-push-quickstart

So we need help on the following:

  1. what is the right and efficient way to get user unique id?
<script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>
<script>
  window.OneSignalDeferred = window.OneSignalDeferred || [];
  OneSignalDeferred.push(function(OneSignal) {
    OneSignal.init({
      appId: "YOUR_APP_KEY",
    });
  });
</script>
  1. how to send notification to users using PHP (no composer)?

// send notification to user
sendMessage("Title","msg here","playerid");


function sendMessage($title,$message,$player_id,$image="") {
    $content      = array(

        "en" => $message,

    );

    $headings = array(

        'en' => $title

    );

    $fields = array(
        'app_id' => 'Your App ID Here',
        'include_player_ids' => array($player_id),
        'data' => array( 'foo' => 'bar' ),
        'contents' => $content,
        'headings' => $headings,
        "web_url" => "https://howi.in",
        "chrome_web_image" => $image
    );

    $fields = json_encode( $fields );

    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, 'https://onesignal.com/api/v1/notifications' );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json; charset=utf-8' ) );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
    curl_setopt( $ch, CURLOPT_HEADER, FALSE );
    curl_setopt( $ch, CURLOPT_POST, TRUE );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $fields );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );

    $response = curl_exec( $ch );
    curl_close( $ch );
}

?>

Thanks in advance

  • The player_id is a unique identifier for each user/device provided by OneSignal. To retrieve this ID, you can use the getUserId method from the OneSignal SDK.

    – 

  • @TSCAmerica.com thanks for the tip!, could you please show me how to use this method?

    – 

Leave a Comment