Get player_id from OneSignal on page load

Viney picture Viney · Mar 21, 2017 · Viewed 9.1k times · Source

I am implementing web push notifications using Onesigal API.

    $fields = array(
        'app_id' => "07aae1f0-xxxx-xxxx-aa7a-21c79c5b6733",
        'include_player_ids'=>['57dd3f80-xxxx-xxxx-adb0-294bfa69621a'],
        'contents' => array( "en"=> "message" )
    );

    $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',
                                               'Authorization: Basic YTdmYTYxYzYtN...tNjVlNzJkNDFlZmMz'));
    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_CAINFO, dirname(__FILE__) . '/cacert.pem' );
    $response = curl_exec($ch);
    curl_close($ch);

Above code sends a push notification to the user if you know his player_id. But suppose if some user visits my site and subscribes to push notifications and leaves.Later again he visits (he is already subscribed) and favs.(adds to favorite) a currently out of stock product.So how can I get player_id of this user which I can store in "subs_fav" table ?

id  player_id           product_id
1   57dd3f80...a69621a  p097

When that product becomes available pushFav() function will run which would notify the user that the product is now available and they can buy it but for that we should know the player_id of the user who favd. this product. I want to know how to find this player_id so that I can send it addToFav() ajax call to store in "sub_fav" table

Answer

Viney picture Viney · Mar 21, 2017

Found it! all you need is OneSignal.getUserId() passed in a callback, which gives the user's player_id upon querying. Before calling make sure user has actually subscribed.

OneSignal.isPushNotificationsEnabled(function(isEnabled) {
  if (isEnabled) {
      // user has subscribed
      OneSignal.getUserId( function(userId) {
          console.log('player_id of the subscribed user is : ' + userId);
          // Make a POST call to your server with the user ID        
      });
  }
});