APNs2-Up

0.9.0 · active · verified Thu Apr 16

APNs2-Up is a Python library designed for interacting with the Apple Push Notification Service (APNs) using the modern HTTP/2 protocol. It provides functionalities for sending both individual and batch push notifications, supporting both certificate-based and token-based authentication. The current version is 0.9.0, with releases occurring periodically to maintain compatibility with APNs and introduce new features.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates sending a single push notification using both certificate-based (.pem) and token-based (.p8) authentication methods. It also includes an example of sending a batch of notifications using token-based authentication. Remember to replace placeholder values with your actual APNs credentials and device token, preferably using environment variables for sensitive data.

import os
from apns2.client import APNsClient
from apns2.payload import Payload
from apns2.credentials import TokenCredentials
import collections

# --- Configuration from environment variables ---
# For certificate-based authentication (P8/PEM file)
CERTIFICATE_PATH = os.environ.get('APNS_CERTIFICATE_PATH', 'path/to/your/certificate.pem')

# For token-based authentication (P8 file details)
AUTH_KEY_PATH = os.environ.get('APNS_AUTH_KEY_PATH', 'path/to/your/AuthKey.p8')
AUTH_KEY_ID = os.environ.get('APNS_AUTH_KEY_ID', 'YOUR_KEY_ID') # E.g., 'ABC123DEFG'
TEAM_ID = os.environ.get('APNS_TEAM_ID', 'YOUR_TEAM_ID')     # E.g., 'XXXXXXXXXX'

# Common notification parameters
DEVICE_TOKEN = os.environ.get('APNS_DEVICE_TOKEN', 'your_device_token_hex_string')
TOPIC = os.environ.get('APNS_BUNDLE_ID', 'com.example.YourApp') # Your app's bundle ID

# Set to True for development/sandbox environment, False for production
USE_SANDBOX = bool(os.environ.get('APNS_USE_SANDBOX', 'True').lower() == 'true')

def send_notification_certificate_based():
    if not os.path.exists(CERTIFICATE_PATH):
        print(f"Warning: Certificate file not found at {CERTIFICATE_PATH}. Skipping certificate-based send.")
        return

    print("\n--- Sending notification with Certificate-Based Authentication ---")
    try:
        client = APNsClient(CERTIFICATE_PATH, use_sandbox=USE_SANDBOX)
        payload = Payload(alert="Hello from Cert!", sound="default", badge=1)
        response = client.send_notification(DEVICE_TOKEN, payload, TOPIC)
        print(f"Certificate-based response: {response.status_code} {response.reason}")
    except Exception as e:
        print(f"Error sending certificate-based notification: {e}")

def send_notification_token_based():
    if not os.path.exists(AUTH_KEY_PATH) or AUTH_KEY_ID == 'YOUR_KEY_ID' or TEAM_ID == 'YOUR_TEAM_ID':
        print("Warning: Token authentication details incomplete or AuthKey.p8 not found. Skipping token-based send.")
        return

    print("\n--- Sending notification with Token-Based Authentication ---")
    try:
        token_credentials = TokenCredentials(auth_key_path=AUTH_KEY_PATH, auth_key_id=AUTH_KEY_ID, team_id=TEAM_ID)
        client = APNsClient(credentials=token_credentials, use_sandbox=USE_SANDBOX)

        payload = Payload(alert="Hello from Token!", sound="default", badge=1)
        response = client.send_notification(DEVICE_TOKEN, payload, TOPIC)
        print(f"Token-based response: {response.status_code} {response.reason}")

        # Example of sending multiple notifications in a batch (Token-based)
        Notification = collections.namedtuple('Notification', ['token', 'payload'])
        notifications = [
            Notification(payload=payload, token=DEVICE_TOKEN)
        ]
        print("Sending batch notification...")
        batch_responses = client.send_notification_batch(notifications=notifications, topic=TOPIC)
        for res in batch_responses:
            print(f"Batch response for {res.token}: {res.status_code} {res.reason}")

    except Exception as e:
        print(f"Error sending token-based notification: {e}")

if __name__ == '__main__':
    send_notification_certificate_based()
    send_notification_token_based()

    print("\nQuickstart finished. Check your device for notifications if configuration was correct.")

view raw JSON →