hmhv

コマンドラインでiPhoneにプッシュ通知を送る方法

2022-04-26

1. ファイルをダウンロード

curl -o sender.sh https://gist.githubusercontent.com/hmhv/7ab39297bdb5efe8b63cd024d893f6bd/raw/29328be9e54a3c1fe36f97369bb1f5d13db286d4/sender.sh
chmod 755 ./sender.sh
curl -o params.sh https://gist.githubusercontent.com/hmhv/dd37cd462a63fa34b588d0eea1eb698d/raw/3db9e1616daa29a13e8afd13e0a14079cba2e781/params.sh
chmod 755 ./params.sh

2. 以下のページを参考にparams.shの各パラメータを編集

3. sender.shを実行

./sender.sh ./params.sh

4. sender.shの内容

# Sending Push Notifications Using Command-Line Tools
# https://developer.apple.com/documentation/usernotifications/sending_push_notifications_using_command-line_tools
if [ "$#" == 1 ]; then
source $1
else
echo "usage: $0 ./params.sh" 1>&2
exit 0
fi
if [ -z "$APNS_HOST_NAME" ]; then
echo "APNS_HOST_NAME is empty" 1>&2
exit 0
elif [ -z "$TEAM_ID" ]; then
echo "TEAM_ID is empty" 1>&2
exit 0
elif [ -z "$AUTH_KEY_ID" ]; then
echo "AUTH_KEY_ID is empty" 1>&2
exit 0
elif [ -z "$TOKEN_KEY_FILE_NAME" ]; then
echo "TOKEN_KEY_FILE_NAME is empty" 1>&2
exit 0
elif [ -z "$TOPIC" ]; then
echo "TOPIC is empty" 1>&2
exit 0
elif [ -z "$DEVICE_TOKEN" ]; then
echo "DEVICE_TOKEN is empty" 1>&2
exit 0
elif [ -z "$APNS_PAYLOAD" ]; then
echo "APNS_PAYLOAD is empty" 1>&2
exit 0
fi
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}"
curl -v \
--header "apns-topic: $TOPIC" \
--header "apns-push-type: alert" \
--header "authorization: bearer $AUTHENTICATION_TOKEN" \
--data "${APNS_PAYLOAD}" \
--http2 https://${APNS_HOST_NAME}/3/device/${DEVICE_TOKEN}
view raw sender.sh hosted with ❤ by GitHub

5. params.shの内容

# Sending Push Notifications Using Command-Line Tools
# https://developer.apple.com/documentation/usernotifications/sending_push_notifications_using_command-line_tools
APNS_HOST_NAME=api.sandbox.push.apple.com
# APNS_HOST_NAME=api.push.apple.com
TEAM_ID=xxxxxxx
AUTH_KEY_ID=xxxxxxx
TOKEN_KEY_FILE_NAME=./xxxxxxx.p8
TOPIC=xxx.xxx.xxx
DEVICE_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
read -r -d '' APNS_PAYLOAD << EOM
{
"aps": {
"alert": "Hello World",
"badge": 1,
"sound": "defalut"
}
}
EOM
view raw params.sh hosted with ❤ by GitHub