OneSignal

Fetch your Users OneSignal Player ID for Custom Push Messaging

The Despia OneSignal Player ID SDK enables your application to retrieve a user's OneSignal ID for personalized push notifications. This ID can be sent to your server along with an authentication token to associate users with their notification channels.

Despia already adds the native OneSignal SDK as a dependency to your compiled app - you do not need to install the web SDK, since Despia will use the native one for a better and truly native experience.

Quick Start

1. Enable OneSignal Player ID retrieval

Enable the OneSignal Player ID retrieval with a simple command:

// Get player ID
window.despia = "getonesignalplayerid://"

2. Access the OneSignal Player ID

Once enabled, you can access the OneSignal Player ID through the global variable:

// Access the player ID
console.log(onesignalplayerid)

3. Send the Player ID to your server

Send the Player ID to your server for storing and future notifications:

// Send player ID to your server
sendToServer({
  playerId: onesignalplayerid,
  authToken: userAuthToken
})

How It Works

Native Integration

The SDK integrates with OneSignal to retrieve the unique identifier associated with the current user's device or browser.

Immediate Retrieval

When you call the getonesignalplayerid:// command, the SDK immediately makes the ID available in the global onesignalplayerid variable.

Server Association

The retrieved player ID can be sent to your server and associated with the user's account, enabling targeted push notifications.

Implementation Examples

Here's how you can implement the OneSignal Player ID retrieval in your application:

// Basic implementation
window.despia = "getonesignalplayerid://";

// Send the ID to your server with authentication
fetch('https://your-api.example.com/register-device', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${userAuthToken}`
  },
  body: JSON.stringify({
    playerId: onesignalplayerid
  })
});

// EXAMPLES FOR NO-CODE/LOW-CODE TOOLS
            
// ---------- WEWEB ----------     
// WEWEB example using wwWorkflow to handle OneSignal player ID
// 1. Create a Native WeWeb Global Workflow and return the variable:         
return onesignalplayerid     
// 2. This will now return the value via the code-block     
// 3. Process the code-block response accordingly, such as setting a variable or calling an API.

// ---------- WIZED ---------- 
// WIZED example using Wized's JS API
// Store the detected data in a Wized variable
v.onesignalId = onesignalplayerid;

// OPTIONAL - Create a request (API Call) that will process the data
const result = await Wized.requests.execute('SEND_PLAYER_ID');
console.log(result); // Or set result as variable for display
            
// ---------- NORDCRAFT / TODDLE ---------- 
// For Nordcraft / Toddle - trigger an event with the data
// Create a custom event handler in your project settings
ctx.triggerActionEvent("onOneSignalIdReceived", {
    playerId: onesignalplayerid,
    timestamp: new Date().getTime()
});

Data Structure

The OneSignal Player ID is a simple string value containing the unique identifier:

// Example OneSignal Player ID
"a1b2c3d4-5e6f-7g8h-9i0j-k1l2m3n4o5p6"

Best Practices

Authentication

  • Always send the player ID with proper authentication

  • Verify user identity before storing the player ID

  • Use HTTPS for all server communications

Implementation

  • Request the player ID early in your application lifecycle

  • Handle errors gracefully if the ID cannot be retrieved

  • Store the ID securely on your server

Complete Implementation Example

Here's a complete implementation example for retrieving the player ID and sending it to your server:

// Get the OneSignal player ID
window.despia = "getonesignalplayerid://";

// Function to send the ID to your server
function sendPlayerIdToServer() {
  // Get auth token from your authentication system
  const authToken = getAuthToken();
  
  // Send to your server
  fetch('https://your-api.example.com/register-device', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${authToken}`
    },
    body: JSON.stringify({
      playerId: onesignalplayerid,
      deviceInfo: {
        platform: navigator.platform,
        userAgent: navigator.userAgent
      }
    })
  })
  .then(response => response.json())
  .then(result => {
    console.log("Registration successful:", result);
  })
  .catch(error => {
    console.error("Failed to register:", error);
  });
}

// Call the function to send the ID
sendPlayerIdToServer();

Server Implementation

Sending Custom Push Notifications

Once you have collected player IDs on your server, you can send custom push notifications using the OneSignal REST API:

curl -X POST https://onesignal.com/api/v1/notifications \
  -H "Content-Type: application/json; charset=utf-8" \
  -H "Authorization: Basic YOUR_REST_API_KEY" \
  -d '{
    "app_id": "ONESIGNAL-APP-ID",
    "include_player_ids": ["PLAYER-ID"],
    "headings": {"en": "Hello"},
    "contents": {"en": "This is a test notification from Despia"}
  }'

Remember to replace:

  • YOUR_REST_API_KEY with your actual OneSignal REST API key

  • ONESIGNAL-APP-ID with your OneSignal application ID

  • PLAYER-ID with the actual player ID received from the client

Troubleshooting

Common Issues

Authentication Failures

  • Verify your authentication token is correctly formatted

  • Check that your server endpoints are properly configured

  • Ensure CORS settings allow requests from your application

Notification Delivery Issues

  • Confirm the player ID is correctly sent to OneSignal

  • Verify the user has granted notification permissions

  • Check that your OneSignal configuration is correct

Need Help?

For additional support or questions, please contact our support team at support@despia.com

Updated on