Hi, this is my setup — hope it works for you:
In a service file, I have the following import and constructor:
import apn from 'apn';
private apnProvider: any;
constructor() {
const keyPath = path.resolve(__dirname, ${process.env.APNS_KEY_PATH}
);
const key = fs.readFileSync(keyPath);
const keyId: string = process.env.KEY_IDENTIFIER || "";
const teamId: string = process.env.TEAM_IDENTIFIER || "";
if (!keyId || !teamId) {
throw new Error("Missing APNS key identifier or team identifier.");
}
this.apnProvider = new apn.Provider({
token: {
key,
keyId,
teamId,
},
production: true,
});
}
Then I call a method that triggers the APNS as follows
private async sendPushNotification(devicePushToken: string, passTypeIdentifier: string): Promise<void> {
const notification = new apn.Notification();
notification.topic = passTypeIdentifier;
notification.contentAvailable = true;
try {
const result = await this.apnProvider.send(notification, devicePushToken);
console.log("APNs response:", result);
if (result.failed.length > 0) {
console.error('Failed to send push notification:', result.failed);
await insertWebLog('error', result.failed, `sendPushNotification on push-notification.service.ts`);
} else {
console.log('Push notification sent successfully');
}
} catch (error) {
console.error('Error sending push notification:', error);
throw new Error(`Error sending push notification: ${error}`);
}
}