Skip to content

Instantly share code, notes, and snippets.

@celian-m
Created January 30, 2025 09:11
Show Gist options
  • Save celian-m/d954133c67cbd1ee35dcfd31215cdce8 to your computer and use it in GitHub Desktop.
Save celian-m/d954133c67cbd1ee35dcfd31215cdce8 to your computer and use it in GitHub Desktop.
Sending Push Notification using bash script and P8 key
#!/bin/bash
# This script is based on Apple Official Documentation :
# https://developer.apple.com/documentation/usernotifications/sending-push-notifications-using-command-line-tools#Send-a-device-push-notification-using-a-JWT
# Replace these values with your own
TEAM_ID="XXXXXXXXX" # the Apple Team Id
AUTH_KEY_ID="XXXXXXXXX" # Name of the P8 key, as it appears on the developer portal
TOKEN_KEY_FILE_NAME="/path/to/key.p8" # Path to the local P8 file generated on the developer portal
DEVICE_TOKEN="device-token" # the APNS token retrieved from didRegisterForRemoteNotificationsWithDeviceToken callback
TOPIC="com.application.bundleId" # Your app bundle Id
APNS_HOST_NAME=api.sandbox.push.apple.com
# Get a Bearer token
JWT_ISSUE_TIME=$(date +%s)
JWT_HEADER=$(printf '{ "alg": "ES256", "kid": "%s" }' "${AUTH_KEY_ID}" | openssl base64 -e -A | tr -- '+/' '-_' | tr -d =)
JWT_CLAIMS=$(printf '{ "iss": "%s", "iat": %d }' "${TEAM_ID}" "${JWT_ISSUE_TIME}" | openssl base64 -e -A | tr -- '+/' '-_' | tr -d =)
JWT_HEADER_CLAIMS="${JWT_HEADER}.${JWT_CLAIMS}"
JWT_SIGNED_HEADER_CLAIMS=$(printf "${JWT_HEADER_CLAIMS}" | openssl dgst -binary -sha256 -sign "${TOKEN_KEY_FILE_NAME}" | openssl base64 -e -A | tr -- '+/' '-_' | tr -d =)
AUTHENTICATION_TOKEN="${JWT_HEADER}.${JWT_CLAIMS}.${JWT_SIGNED_HEADER_CLAIMS}"
# Send the push notification
curl -v \
--header "apns-topic: $TOPIC" \
--header "apns-push-type: alert" \
--header "authorization: bearer $AUTHENTICATION_TOKEN" \
--data '{"aps":{"alert":"test"}}' \
--http2 https://${APNS_HOST_NAME}/3/device/${DEVICE_TOKEN}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment