-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
54 lines (48 loc) · 1.73 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { serve } from "https://deno.land/std@0.131.0/http/server.ts"
import * as OneSignal from "https://esm.sh/@onesignal/node-onesignal@1.0.0-beta7"
import {
_OnesignalAppId_,
_OnesignalRestApiKey_,
_OnesignalUserAuthKey_,
} from "../_utils/config.ts"
import { getCustomerProfile } from "../_utils/supabase.ts"
const notifMessage = (amount: number, currency: string) =>
`You just spent ${amount / 100} ${(currency as String).toUpperCase()}.`
serve(async (req) => {
// Load secrets
// Create OneSignal client
const configuration = OneSignal.createConfiguration({
userKey: _OnesignalUserAuthKey_,
appKey: _OnesignalRestApiKey_,
})
const onesignalClient = new OneSignal.DefaultApi(configuration)
try {
const json = await req.json()
const { record } = json
const customerId = record.stripe_customer_id
const profile: string | null = await getCustomerProfile(customerId)
if (!profile) {
throw Error(`No profile found for Stripe customer ${customerId}.`)
}
// Build OneSignal notification object
const notification = new OneSignal.Notification()
notification.app_id = _OnesignalAppId_
notification.include_external_user_ids = [profile]
notification.contents = { en: notifMessage(record.amount, record.currency) }
const onesignalApiRes = await onesignalClient.createNotification(
notification
)
return new Response(
JSON.stringify({ onesignalResponse: onesignalApiRes }),
{
headers: { "Content-Type": "application/json" },
}
)
} catch (err) {
console.error("Failed to create OneSignal notification", err)
return new Response("Server error.", {
headers: { "Content-Type": "application/json" },
status: 400,
})
}
})