Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Sample integration to send a push notification using OneSignal from a Supabase edge function.

NotificationsYou must be signed in to change notification settings

OneSignalDevelopers/onesignal-supabase-sample-integration-supabase

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

91 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OneSignal

Quickstart  •  Website  •  Docs  •  Examples

OneSignal + Supabase Sample Omni-channel Integration

OneSignal makes engaging customers simple and is the fastest, most reliable service to send push notifications, in-app messages, SMS, and emails.

This project demonstrates how to use OneSignal as an integration withSupabase to handle your messaging needs, including push notifications, SMS text messages, email, and in-app messaging. Feel free to use this sample as a reference for your own Supabase integration.

Table of Contents

🚦 Getting started

This project assumes that you already have a few things setup.

Setup OneSignal App

  1. From the OneSignal Dashboard, selectNew App/Website to create an app.Select New App/Website to create new app
  2. Name app and choose theAndroid platform to setup.Onesignal platform configuration
  3. Enter FCM credentials for the Firebase project you want to handle Android notifications and chooseSave & Continue.FCM configuration form

Setup iOS Platform

iOS configuration requires substantially more effort to integrate due to needing signed certs from Apple. Due to this fact, followthis guide for detailed instructions on creating the certificate needed to use Apple's Push Notification Service (APNs).

After you have the certificate, head to the OneSignal Dashboard

  1. ChooseSettings -> Platforms
  2. Activate the iOS cardPlatform settings
  3. Upload your certificate and enter the password you used to encrypt it. If you didn't set a password, leave the password input blank.Apple iOS (APNs) Configuration form

Craft an In-App Message

Consent is required before we can present push notifications to a user. It's recommend to use an in-app message to ask for consent because no prior consent is needed to present them. This is particularly useful in situations where a user accidentally declines consent. We have an in-depth guide explaining this strategyhere.

  1. SelectNew Message -> New In-App and name it "prompt_notification"Select new in app message

  2. Configure an in-app message with at least one button; here's the message with two buttons I configured for this sample using our Block Editor!Example in-app message

  3. Add thePush Permission PromptClick Action to the primary call to action button.Adding a cliock action

  4. SelectAdd Trigger -> In-App Trigger to present the in-app message when specific conditions are metAdding in-app trigger

  5. Schedule the message to start showingImmediately, toShow forever, and to showEvery time trigger conditions are satisfied

  6. SelectMake Message Live to publish message

If you didn't name your in-app message "prompt_notification", you'll need to update theFlutter app's code to use your name.

Setup Supabase Project

Initialize Supabase project

Run this command to interactively configure a new Supabase project

supabase projects create onesignal-supabase-sample-integration -i

asciicast

Disable email confirmation authentication

Disable Supabase email confirmation

Supabase projects are more secure by default. The front-end client consuming this project does not support magic links. Disabling email confirmation is needed to run thecompanion sample app.

  1. From the Supabase Dashboard, navigate to your project's Authenication pane.Select Providers on Authentication page
  2. SelectProviders under the Configuration header.Disable Confirm email
  3. DisableConfirm email and selectSave.

Edit Database Triggers

We can rely on Supabase to automatically insert a user profile after user signup. Supabase provides Database Functions and Triggers that enable us to react to events on the database. For this sample integration, we will edit the existing functionon_auth_user_created.

  1. Navigate to Database -> Triggerson_auth_user_created Trigger

  2. Edit the backing function by navigating to Functions and clicking the edit button located in the context-menu for the recordhandle_new_user.Navigate to Supabase Database Functions

  3. Paste the 👇 script as theDefintion and selectConfirm

begininsert intopublic.profiles (id, email)values (new.id,new.raw_user_meta_data->>'email');  return new;end;

Database function edit form

Create Edge Function

The Supabase CLI's command to create a function will add the boilerplate for an edge function located in a directory with the name specified in the command,push/index.ts.

supabase functions new push-order-confirmation-to-customer

asciicast

This function is responsible for calling the OneSignal API usingonesignal-node-sdk.

Function Implementation

Supabase Edge Functions are executed in the Deno enfironment on the edge, so

  • Functions are written in TypeScript
  • You can't install packages with a package manager like npm or Yarn

Function logic is implemented inpush/index.ts (Here).

We can't use a traditional package manager to install packages, so we're usingesm.sh – a global CDN for npm packages – to load theonesignal-node-api module.

import*asOneSignalfrom "https://esm.sh/@onesignal/node-onesignal@1.0.

Deno'sDeno.env object exposes the values we need.

exportconst_OnesignalAppId_=Deno.env.get("ONESIGNAL_APP_ID")!
const_OnesignalUserAuthKey_=Deno.env.get("USER_AUTH_KEY")!
exportconst_OnesignalRestApiKey_=Deno.env.get("ONESIGNAL_REST_API_KEY")!

Create the OneSignal API client so we can send a request to the API.

exportconstonesignal=newOneSignal.DefaultApi(configuration)

Now we can configure the notification object.

constnotification=newOneSignal.Notification()
notification.app_id=_OnesignalAppId_
notification.include_external_user_ids=[profile]
notification.contents={
en:generateMessage(record.amount,record.currency),
}

And send the notification to OneSignal to send the push notification.

constonesignalApiRes=awaitonesignal.createNotification(notification)

Set Environment Variables

Locally

Supabase will respect local environment variables set insupabase/.env.local.

Copy.env.example and fill in your keys from OneSignal app.

$ cp supabase/.env.example supabase/.env.local

On Supabase

Use the Supabase CLI to set environment variables in the Supabase project.

$ supabase secretsset test=123Finished supabase secrets set.

asciicast

How to Remove Variable

Use the Supabase CLI to remove environmental variables in the Supabase project.

$ supabase secretsunsettestFinished supabase secrets unset.

Run Migrations

💡You only need to run steps 1 since this sample includes migrations files (here).

  1. Runsupabase db diff and copy its outputGenerate SQL script for Supabase migration

  2. Create a new migration and paste the output from the previous step into the.sql fileCreate Supabase Migration

  3. Runsupabase db push to apply migrations to the hosted project

Deploy Edge Function

We can deploy edge functions to a local or production environment. Developing locally allows us to test and iterate quickly.

Hosting locally

  1. Start the Supabase Docker container, navigate to the root directory of this sample project and runsupabase start
  2. To serve the function, runsupabase functions serve push --env-file ./supabase/.env.local --debug
  3. Submit a request to the endpoint making sure to use theanon key as your bearer token.

Result of runningsupabase start

$ supabase startSeeding data supabase/seed.sql...Started supabaselocal development setup.API URL: http://localhost:54321DB URL: postgresql://postgres:postgres@localhost:54322/postgresStudio URL: http://localhost:54323Inbucket URL: http://localhost:54324JWT secret: super-secret-jwt-token-with-at-least-32-characters-longanon key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24ifQ.625_WdcF3KHqz5amU0x2X5WWHP-OEs_4qj0ssLNHzTsservice_role key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSJ9.vI9obAHOGyVVKa3pD--kJlyxp-Z2zV9UUMAhKpNLAcU

Serving a function to the local instance of Supabase.

asciicast

To Production

Supabase makes deploying your project to production simple with their CLI.

supabase functions deploy push

If the command ☝️ doesn't work for you, try executing the command with the--legacy-bundle flag set.

asciicast

Create Database Webhook

For complete instructions on creating a webhooks, please refer to theSupabase docs.

Sample hook

  1. From the Database -> Webhooks page SelectCreate a new hook button
  2. Name the hook "push-order-confirmation-to-user"
  3. Set the table toorders
  4. SelectInsert checkbox
  5. Set hook type to HTTP Request
  6. Set the HTTP request method toPOST
  7. Set the URL to the edge function,push-order-confirmation-to-customer
  8. Add a HTTP Header namedAuthorization and set the value toBearer [Your Supabase project's anonKey]
  9. SelectConfirm confirm button to complete setup

💡We need to include the Authorization header so the edge function can verify the request. Without this header, anyone would be able to call our endpoint.

Example Database Webhook event
{type:"INSERT",table:"orders",record:{id:"796a354b-c087-4afe-8614-5a1015221d04",amount:1099,currency:"usd",created_at:"2022-11-30T18:41:42.605",stripe_pi_id:"pi_3M9vDvKCO1JeQB0L1PGzangD",stripe_customer_id:"cus_MtibdpF533vFYn"},schema:"public",old_record:null}

🚀🚀🚀 Launch Companion App

Thecompanion app andsupporting API can be built from source to run alongside this Supabase project.

App demo

Debugging

TheSupabase dashboard presents all deployed functions along with their time of deployment and status.

Functions deployed to production

Inspect Supabase Edge Function Requests

Supabase enables you to review HTTP request logs to assist with our debugging.

Inspecting function requests

Review Server Logs

Ourconsole.logs will appear here!

Reviewing function logs


❤️ Developer Community

For additional resources, please join theOneSignal Developer Community.

Get in touch with us or learn more about OneSignal through the channels below.

Show your support

Give a ⭐️ if this project helped you, and watch this repo to stay up to date.

About

Sample integration to send a push notification using OneSignal from a Supabase edge function.

Topics

Resources

Stars

Watchers

Forks


[8]ページ先頭

©2009-2025 Movatter.jp