> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gameball.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Push Notifications

> Integrate Gameball push notifications and build custom notification systems using webhooks

Notifications are a powerful way to build stronger relationships with your customers by keeping them engaged with your service. Gameball provides default notification options and supports custom notification systems through webhooks.

***

## Notification Options

Gameball offers multiple ways to deliver notifications to your customers:

> [card] In-App Notifications
>
> **Web Applications**
>
> Built-in notifications for web applications that display within your app interface.

> [card] Push Notifications
>
> **Mobile Apps**
>
> Push notifications using Firebase for iOS and Android mobile applications.

> [card] Custom Systems
>
> **Webhooks**
>
> Build your own notification system using SMS, WhatsApp, Amazon SNS, Twilio, or other third-party services via webhooks.

> [card] Customer Notifications API
>
> **Programmatic Access**
>
> Retrieve and display notifications programmatically using the Customer Notifications API.

***

## Mobile Push Notifications (Firebase)

Gameball uses Firebase to deliver push notifications for mobile applications. This includes support for iOS and Android apps.

> [!WARNING]
>
> **Prerequisites**: Before implementing push notifications, you must configure your Firebase account in your Gameball dashboard. Follow the steps in the [Firebase push notifications guide](https://docs.gameball.co/product-documentation/admin-settings/configure-firebase-push-notifications.md).

### How It Works

**1. Configure Firebase**

Set up Firebase Cloud Messaging (FCM) and configure it in your Gameball dashboard.

> [!NOTE]
>
> This configuration links your Firebase project with Gameball so notifications can be delivered through Firebase.

**2. Register Device Token**

Register the device token with Gameball by passing `deviceToken` and `pushProvider` to the SDK's `initializeCustomer` method. To register it from your server instead, send `deviceToken` and `pushServiceProvider` to the [Create/Update Customer API](https://docs.gameball.co/api-reference/customers/management/create-customer.md#registering-a-push-token).

> [!NOTE]
>
> Device tokens are unique identifiers for each mobile device. You need to register them so Gameball knows where to send push notifications. Re-register whenever the push service issues a new token.

**3. Handle Notifications**

Configure your app to handle incoming push notifications and display them appropriately.

### Platform-Specific Guides

> [tab] iOS
>
> For iOS apps, integrate push notifications by:
>
> > [accordion] Configure AppDelegate
> >
> > Inherit required protocols in your `AppDelegate` class:
> >
> > ```swift theme={null}
> > class AppDelegate: UIResponder, UIApplicationDelegate, 
> >                   UNUserNotificationCenterDelegate, MessagingDelegate {
> >   var gameballApp: Gameball?
> > }
> > ```
>
> > [accordion] Initialize Firebase
> >
> > Add Firebase configuration in `didFinishLaunchingWithOptions()`:
> >
> > ```swift theme={null}
> > FirebaseApp.configure()
> > registerForPushNotifications()
> > ```
>
> > [accordion] Request Permissions
> >
> > Request notification permissions from the user:
> >
> > ```swift theme={null}
> > func registerForPushNotifications() {
> >   UNUserNotificationCenter.current()
> >     .requestAuthorization(options: [.alert, .sound, .badge]) {
> >       [weak self] granted, error in
> >       UNUserNotificationCenter.current().delegate = self
> >       Messaging.messaging().delegate = self
> >       guard granted else { return }
> >       self?.getNotificationSettings()
> >     }
> > }
> > ```
>
> > [accordion] Register Device Token
> >
> > Register the device token with Gameball by calling `initializeCustomer` with `deviceToken` and `pushProvider: .firebase`. Refer to the [Firebase documentation](https://firebase.google.com/docs/cloud-messaging/ios/client#access_the_registration_token) for accessing the registration token.
>
> > [!TIP]
> >
> > See the [iOS Push Notifications installation guide](https://docs.gameball.co/installation-guides/v4/ios/push-notifications.md) for complete implementation details.

> [tab] Android
>
> Android push notification integration follows similar patterns to iOS, using Firebase Cloud Messaging.
>
> > [!TIP]
> >
> > See the [Android Push Notifications installation guide](https://docs.gameball.co/installation-guides/v4/android/push-notifications.md) for platform-specific implementation details.

> [tab] React Native
>
> React Native apps can integrate push notifications using the Gameball SDK for React Native.
>
> > [!TIP]
> >
> > See the [React Native Push Notifications installation guide](https://docs.gameball.co/installation-guides/v4/react-native/push-notifications.md) for framework-specific implementation.

***

## Custom Notification Systems via Webhooks

If you have your own notification system—like SMS messaging, WhatsApp bots, or third-party services like Amazon SNS or Twilio—Gameball makes this easy by using **webhooks** to notify your system whenever a notification needs to be sent.

### How Webhooks Work

**1. Build Webhook Endpoint**

Create a webhook endpoint on your server (written in any language like Ruby, PHP, or Node.js) that processes incoming requests.

> [!NOTE]
>
> This endpoint will receive POST requests from Gameball containing notification data.

**2. Provide Endpoint URL**

Share your endpoint URL (e.g., `https://yourdomain.com/webhook-endpoint`) with Gameball through your dashboard.

**3. Receive Notifications**

Gameball sends a POST request with all necessary notification data to your endpoint whenever a customer should receive a notification.

**4. Process and Deliver**

Use the notification data to send messages through your preferred channels (SMS, WhatsApp, push, etc.).

![Notifications via webhooks overview](https://873157020-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FElcuAgxn15Pk6F2fINKe%2Fuploads%2F5rGdGr0h7ycZcoJBffpn%2Fnotifications.drawio.png?alt=media\&token=2966189c-f0f4-4085-b2d4-e77254a20c18)

### Implementation Steps

#### Step 1: Build a Notifications Endpoint

Create a webhook endpoint on your server:

```javascript theme={null}
app.post('/gb-webhook/notification', (request, response) => {
  // Process notification here
});
```

> [!NOTE]
>
> This endpoint will be invoked whenever Gameball needs to send a notification to your customer.

#### Step 2: Activate Notifications Webhook

In your Gameball dashboard:

**1. Navigate to Settings**

Go to **Admin Settings > Account Integration > Webhooks**.

**2. Add Endpoint URL**

Add your notification endpoint URL (e.g., `www.yourdomain.com/gb-webhook/notification`) to the Notification Webhook field.

**3. Update Webhook**

Click **Update Webhook** to save your configuration.

![Configuring Webhooks](https://873157020-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FElcuAgxn15Pk6F2fINKe%2Fuploads%2FOB3GyqZyoKENnAJMmEmt%2Fimage.png?alt=media\&token=bcb92a03-033e-4074-ae89-3a336503da3e)

#### Step 3: Verify Webhook Signatures

> [!WARNING]
>
> **Security Critical**: Always verify that incoming requests are legitimate requests from Gameball and not malicious attempts to spam your system.

Verify webhook signatures using the SHA1 hash in the `X-GB-Signature` header:

```javascript theme={null}
const crypto = require("crypto");

function verifySignature(request) {
  const SECRET_KEY = process.env.SECRET_KEY;
  // Get the signature from the header
  const signature = request.headers["x-gb-signature"];
  if (!signature) return false;

  // Compute the signature using the payload and secret key
  const payload = JSON.stringify(request.body);
  const computedSignature = crypto
    .createHash("sha1")
    .update(payload + ":" + SECRET_KEY)
    .digest("hex");

  // Compare the signatures
  return computedSignature === signature;
}

app.post('/gb-webhook/notification', (request, response) => {
  // verify the request
  if (verifySignature(request) == false) {
    return response.status(401).send('Unauthorized');
  }
  
  // Process notification
});
```

> [!TIP]
>
> For more information on webhook verification, see the [Webhooks documentation](https://docs.gameball.co/api-reference/webhooks/subscribing.md).

#### Step 4: Process Notification Data

The webhook request contains all the data needed to send notifications to your customers. Here's an example of the notification payload:

```json theme={null}
{
  "event": "customer.notification.push",
  "client_id": "2155",
  "customer_id": "webhook-test",
  "gb_customer_id": 1234,
  "created_at": "2024-11-12T19:02:24.631Z",
  "data": [
    {
      "local": "en",
      "icon": "https://example.com/image.webp",
      "body": "Your recent activities have been amazing! Keep up the great work and enjoy your rewards!",
      "title": "Well Done!"
    }
  ]
}
```

> [accordion] Webhook Fields
>
> The notification webhook includes:
>
> * **event**: Identifies this as a customer notification push event
> * **client\_id**: Your app's unique identifier
> * **customer\_id**: The customer identifier you use in your system
> * **gb\_customer\_id**: Gameball's internal customer identifier
> * **created\_at**: Timestamp when the notification was created
> * **data**: Array of notification content in different languages (title, body, icon, local)

### Implementation Examples

> [tab] SMS Integration
>
> Send notifications via SMS using your SMS gateway:
>
> ```javascript theme={null}
> app.post('/gb-webhook/notification', (request, response) => {
>   if (verifySignature(request) == false) return;
>
>   let webhookData = request.body;
>   let customerId = webhookData.customer_id;
>   let customerInfo = getCustomerDetails(customerId);
>
>   // Send SMS to customer's phone number
>   SMSGateway.sendMessage({
>     phoneNumber: customerInfo.phone,
>     messageTitle: webhookData.data[0].title,
>     messageContent: webhookData.data[0].body
>   });
> });
> ```

> [tab] WhatsApp Integration
>
> Send notifications via WhatsApp using WhatsApp Business API or Twilio:
>
> ```javascript theme={null}
> app.post('/gb-webhook/notification', (request, response) => {
>   if (verifySignature(request) == false) return;
>
>   let webhookData = request.body;
>   let customerId = webhookData.customer_id;
>   let customerInfo = getCustomerDetails(customerId);
>
>   // Send WhatsApp message
>   WhatsappHandler.sendWhatsappMessage({
>     phoneNumber: customerInfo.phone,
>     messageContent: webhookData.data[0].body
>   });
> });
> ```

> [tab] Push Notifications (AWS SNS)
>
> Send push notifications using AWS SNS:
>
> ```javascript theme={null}
> app.post('/gb-webhook/notification', (request, response) => {
>   if (verifySignature(request) == false) return;
>
>   let webhookData = request.body;
>   let customerId = webhookData.customer_id;
>   let customerInfo = getCustomerDetails(customerId);
>
>   // Send push notification using device token
>   SNS.sendNotification({
>     token: customerInfo.deviceToken,
>     title: webhookData.data[0].title,
>     body: webhookData.data[0].body
>   });
> });
> ```
>
> > [!NOTE]
> >
> > AWS SNS uses device tokens to identify mobile devices. Store each customer's device token in your database.

> [tab] Multiple Channels
>
> You can send notifications through multiple channels simultaneously:
>
> ```javascript theme={null}
> app.post('/gb-webhook/notification', (request, response) => {
>   if (verifySignature(request) == false) return;
>
>   let webhookData = request.body;
>   let customerId = webhookData.customer_id;
>   let customerInfo = getCustomerDetails(customerId);
>
>   // Send SMS
>   SMSGateway.sendMessage({
>     phoneNumber: customerInfo.phone,
>     messageContent: webhookData.data[0].body
>   });
>
>   // Send WhatsApp
>   WhatsappHandler.sendWhatsappMessage({
>     phoneNumber: customerInfo.phone,
>     messageContent: webhookData.data[0].body
>   });
>
>   // Send push notification
>   if (customerInfo.deviceToken) {
>     SNS.sendNotification({
>       token: customerInfo.deviceToken,
>       title: webhookData.data[0].title,
>       body: webhookData.data[0].body
>     });
>   }
> });
> ```

***

## Customer Notifications API

Gameball also provides APIs to retrieve and manage customer notifications programmatically.

### Retrieving Notifications

Use the [Get Customer Notifications API](https://docs.gameball.co/api-reference/customers/notifications/list-customer-notifications.md) to fetch a list of notifications for a specific customer:

```json theme={null}
GET /api/v4.0/integrations/customers/{customerId}/notifications
```

**Response Example:**

```json theme={null}
{
  "notifications": [
    {
      "notificationId": "15227561",
      "title": "Congratulations!",
      "body": "Buy over 500$ and get 10$ 💰 earned. Enjoy your rewards and keep earning more!",
      "isRead": false,
      "createdAt": "2024-11-19T13:39:13.792Z",
      "lang": "en",
      "icon": "https://cdn.gameball.co/uploads/Client_9423/2b2efc2f-b85e-4cce-baf6-380454e4d62ccash.webp"
    }
  ],
  "count": 4,
  "hasMore": false
}
```

> [card] Pagination
>
> Use `count` and `hasMore` fields to implement pagination in your UI.
>
> * **count**: Number of notifications in current response
> * **hasMore**: Indicates if more notifications are available

> [card] Language Support
>
> Request notifications in different languages using the `lang` query parameter.
>
> Example: `?lang=es` for Spanish

### Marking Notifications as Read

Use the [Mark Notifications as Read API](https://docs.gameball.co/api-reference/customers/notifications/mark-notifications-read.md) to update notification status:

```json theme={null}
PUT /api/v4.0/integrations/customers/{customerId}/notifications/read
{
  "notificationsIds": [15227561, 15227560]
}
```

### Get Notification Count

Use the [Get Customer Notifications Count API](https://docs.gameball.co/api-reference/customers/notifications/get-customer-notifications-count.md) to get the total count without fetching all records:

```json theme={null}
GET /api/v4.0/integrations/customers/{customerId}/notifications/count
```

***

## Best Practices

> [card] Verify Webhooks
>
> Always verify webhook signatures to ensure requests are legitimate and secure.

> [card] Handle Errors Gracefully
>
> Implement proper error handling for failed notification deliveries.

> [card] Store Device Tokens
>
> For push notifications, securely store device tokens in your database and update them when they refresh.

> [card] Respect User Preferences
>
> Allow customers to opt-in or opt-out of different notification types.

***

## Related Resources

> [card] [Notification Webhooks](https://docs.gameball.co/api-reference/webhooks/webhook-topics/notifications.md)
>
> Complete webhook documentation for notifications

> [card] [Customer Notifications API](https://docs.gameball.co/api-reference/customers/notifications/list-customer-notifications.md)
>
> API reference for retrieving customer notifications

> [card] [Build Custom UI](https://docs.gameball.co/tutorials/experiences/more/build-your-own-notifications.md)
>
> Guide on displaying notifications in your custom UI

> [card] [iOS Push Notifications](https://docs.gameball.co/installation-guides/v4/ios/push-notifications.md)
>
> iOS-specific push notification integration guide

***


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.