# Twinr Push API with Your Sharetribe Backend

> Send any push notification to your Sharetribe users from your own backend, using the device token Twinr attaches to each user's profile.

Your backend can send a push notification to any user of your marketplace app at any time, for any reason. New messages, reviews, booking reminders, payout updates, announcements to one person: if your server can decide to send it, the Twinr Push API can deliver it.

This page covers:

1. How each user's device token gets to their Sharetribe profile.
2. How to send a notification with the Twinr Push API.
3. A full example: a push for every new message.

> **Note:** For listing and transaction events, you can also send pushes from Zapier without writing code. See [Listing Push Notification](https://help.twinr.dev/plugins/sharetribe/listing-push-notification) and [Transaction-Related Push Notifications](https://help.twinr.dev/plugins/sharetribe/transaction-related-push-notifications). Everything else goes through your own backend, as described here.

***

## 1. Get the User's Device Token

### Automatically, from the Sharetribe Connection

Once [Sharetribe Connection](https://help.twinr.dev/plugins/sharetribe/sharetribe-connection) is set up, Twinr attaches each user's device token to their Sharetribe profile for you:

* When a user logs in to your marketplace inside the app, Twinr confirms the login with Sharetribe and writes two fields to that user's profile **metadata**:
  * `metadata.device_push_token`: the device token to send pushes to
  * `metadata.app_id`: your Twinr app ID
* If the device's token changes, Twinr writes the new one.
* When the user logs out, Twinr removes the token from their profile.

Your backend reads these fields with the Sharetribe Integration API [show user](https://www.sharetribe.com/api-reference/integration.html#show-user) endpoint, under `attributes.profile.metadata`.

The profile holds one token: the device the user logged in on most recently. If someone uses your app on a phone and a tablet, only the latest one is in their profile. To reach every device, store tokens yourself (see below).

This needs:

* Your app built with the latest Twinr version, and a paid app subscription
* Login enabled with a Login Script, and Firebase set up (see [Sharetribe Connection](https://help.twinr.dev/plugins/sharetribe/sharetribe-connection#important-setup-notes))

If either field is missing, the user hasn't logged in to your app yet. Skip the push for that user.

### Manually, with the JS Bridge

If you'd rather manage tokens yourself, your marketplace website can read the device token with the JS bridge function `twinr_push_token_fetch()` and save it wherever you like:

```javascript
if (typeof twinr_push_token_fetch === 'function') {
  const result = await twinr_push_token_fetch();
  if (result?.token) {
    // Save result.token (and result.platform) against the signed-in user,
    // for example in their profile's privateData or in your own database.
  }
}
```

`twinr_push_token_fetch` exists only inside the Twinr app. The `typeof` check keeps your website working in an ordinary browser.

This lets you keep one token per device, so a user with several devices gets the push on all of them. It needs [Personalized Push Notification](https://help.twinr.dev/push/personalized-push-notification) enabled. See [Push Notification - Device Token](https://help.twinr.dev/js-bridge/push-notification-device-token).

***

## 2. Send a Push with the Twinr Push API

### Create an Account Secret

The Push API authenticates with an account secret. Go to **My Profile → Account secrets**, click **Create secret**, and scope it to this app. It is shown once, when you create it, so copy it before closing the dialog. See [Account Secrets](https://help.twinr.dev/twinr-account/account-secrets).

> **Warning:** Keep the secret on your server, for example in an environment variable. Never put it in your website's JavaScript or in the app: anyone holding it can send notifications that appear to come from your app.

### Make the Request

```
POST https://msengageapi.twinr.dev/v3/send-notifications
Authorization: Bearer twnr_live_xxxxxxxxxxxx
Content-Type: application/json
```

```json
{
  "application_id": "metadata.app_id of the user",
  "push_tokens": ["metadata.device_push_token of the user"],
  "push_title": "New message from Alex",
  "push_message": "Is the bike still available?",
  "click_action": { "type": "url", "url": "https://your-marketplace.com/inbox" }
}
```

* **application\_id**: your Twinr app ID. Use `metadata.app_id` from the user. Required.
* **push\_tokens**: the device tokens to send to. Use `metadata.device_push_token` from the user, or the tokens you stored yourself. Required.
* **push\_title** and **push\_message**: the notification's title and text. Required.
* **click\_action**: what tapping the notification does. Required. It is one of:
  * `{ "type": "open_app" }`: opens the app
  * `{ "type": "open_tab", "tab_name": "Home" }`: opens a tab by its name in your Twinr dashboard
  * `{ "type": "url", "url": "https://..." }`: opens a page inside the app, such as the conversation or the order
* **push\_image**: an image URL to show in the notification. Optional.

There are no restrictions on what you send or when. Each call sends one notification to the tokens you list. See [Twinr Push API](https://help.twinr.dev/push/personalized-push-notification) for more on the request and its errors.

***

## 3. Example: A Push for Every New Message

Zapier has no Sharetribe trigger for new messages, so message pushes are a typical job for your backend. The same pattern works for any other Sharetribe event.

1. Your server reads events from the Sharetribe Integration API [query events](https://www.sharetribe.com/api-reference/integration.html#query-events) endpoint, filtered to the `message/created` event type. Keep the sequence ID of the last event you processed, and ask only for events after it, so each message is handled once.
2. A `message/created` event names the sender and the transaction, not the recipient. Fetch the transaction with its customer and provider. The recipient is whichever of the two is **not** the sender.
3. Fetch the recipient with **show user** and read `metadata.device_push_token` and `metadata.app_id`.
4. Send the push to Twinr.

Steps 3 and 4 in Node.js, with Sharetribe's Integration SDK:

```javascript
const flexIntegrationSdk = require('sharetribe-flex-integration-sdk');

const integrationSdk = flexIntegrationSdk.createInstance({
  clientId: process.env.SHARETRIBE_CLIENT_ID,
  clientSecret: process.env.SHARETRIBE_CLIENT_SECRET,
});

async function pushToUser(userId, title, message, url) {
  const res = await integrationSdk.users.show({ id: userId });
  const metadata = res.data.data.attributes.profile.metadata || {};
  if (!metadata.device_push_token || !metadata.app_id) return;

  await fetch('https://msengageapi.twinr.dev/v3/send-notifications', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.TWINR_SECRET}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      application_id: metadata.app_id,
      push_tokens: [metadata.device_push_token],
      push_title: title,
      push_message: message,
      click_action: url ? { type: 'url', url } : { type: 'open_app' },
    }),
  });
}
```

Use the Client ID and Client Secret of a Sharetribe Integration API application. Like the Twinr secret, they belong on your server only.

* [Sharetribe: events and event types](https://www.sharetribe.com/docs/references/events/)
* [Sharetribe Integration API reference](https://www.sharetribe.com/api-reference/integration.html)

Source: https://help.twinr.dev/plugins/sharetribe/push-api-with-sharetribe-backend
