当前位置: 首页 > news >正文

APNS和FCM推送服务脚本

APNS推送

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

# 配置
AUTH_KEY_PATH = 'xxxxx.p8'  # .p8 文件路径
TEAM_ID = 'xxxxxx'                     # Apple 开发者团队 ID
KEY_ID = 'xxxxx'                       # .p8 文件的密钥 ID
DEVICE_TOKEN = 'xxxxxx'                # 目标设备的令牌
TOPIC = 'xxxxxxxxx'                    # App 的 Bundle ID

# 创建 Payload
payload = Payload(
    alert="Hello, APNs with .p8!",  # 通知内容
    sound="default",                # 提示音
    badge=1,                        # 角标
    custom={"key": "value"}         # 自定义数据
)

# 使用 Token 认证
credentials = TokenCredentials(
    auth_key_path=AUTH_KEY_PATH,  # .p8 文件路径
    auth_key_id=KEY_ID,           # 密钥 ID
    team_id=TEAM_ID               # 团队 ID
)

# 创建 APNs 客户端
client = APNsClient(
    credentials=credentials,
    use_sandbox=True,  # 测试环境使用 sandbox,生产环境设置为 False
    use_alternative_port=False
)

# 发送通知
try:
    response = client.send_notification(
        DEVICE_TOKEN,
        payload,
        topic=TOPIC
    )
    print("Notification sent successfully!")
    print("APNs response:", response)
except Exception as e:
    print("Failed to send notification:", e)

FCM推送

json文件来自 管理台-项目设置-服务账号-Firebase Admin SDK-生成新的私钥

import firebase_admin
from firebase_admin import credentials
from firebase_admin import messaging

# 初始化SDK(服务账号方式)
cred = credentials.Certificate('xxxxxx.json')
firebase_admin.initialize_app(cred)

def send_fcm_notification(registration_token, title, body, data=None):
    """
    发送单设备推送
    
    参数:
    registration_token : str - 设备注册令牌
    title : str - 通知标题
    body : str - 通知内容
    data : dict - 自定义键值对数据
    """
    message = messaging.Message(
        notification=messaging.Notification(
            title=title,
            body=body
        ),
        data=data or {},
        # 添加此处可以在点击时拉起app的处理,需要在AndroidManifest.xml对应处理
        # 
        # 需要在主activity下添加如下
        # <intent-filter>
        #     <action android:name="NOTIFICATION_OPEN" />
        #     <category android:name="android.intent.category.DEFAULT" />
        # </intent-filter>
        # 
        # 在主activity中的onNewIntent中Intent可以获取到data内数据
        android=messaging.AndroidConfig(
            notification=messaging.AndroidNotification(
                click_action='NOTIFICATION_OPEN'  # Android端匹配的action
            )
        ),
        token=registration_token
    )

    try:
        response = messaging.send(message)
        print('成功发送:', response)
        return True
    except Exception as e:
        print('发送失败:', str(e))
        return False

# 使用示例
send_fcm_notification(
    registration_token='xxxxxxxxxx',
    title='温度警报',
    body='当前温度已超过阈值38℃',
    data={'sensor_id': 'temp-001', 'value': '38.5'}
)

相关文章:

  • Kubernetes》k8s》Containerd ctr cri
  • DPO介绍+公式推理
  • ngx_http_core_init_main_conf
  • 将任何网站变成独立的桌面应用 开源免费 Tuboshu
  • 3.使用epoll实现单线程并发服务器
  • JavaWeb——事务管理、AOP
  • windows USB 了解
  • 阿里云Tair KVCache:打造以缓存为中心的大模型Token超级工厂
  • NX二次开发刻字功能——布尔运算
  • Spring项目中使用EasyExcel实现Excel 多 Sheet 导入导出功能(完整版)
  • 泛目录和泛站有什么不同?什么是无极泛目录?
  • IP属地和发作品的地址不一样吗
  • 生成AI基本原理简介
  • 深入理解 Linux 内核中的 GPU 子系统:从 DRM 到 NXP 驱动架构全解读
  • Java构造函数与普通函数
  • 洛谷P1706 全排列题解
  • 【redis】持久化之RDB与AOF
  • 前后前缀
  • Windows下在IntelliJ IDEA 使用 Git 拉取、提交脚本出现换行符问题
  • 比较4点结构和4次函数
  • 金融监管总局等八部门:引导银行向小微企业贷款倾斜核销空间和资源,释放更多信贷资源
  • NFL球员将参加洛杉矶奥运会腰旗橄榄球比赛
  • 联合国妇女署:超过2.8万名妇女和女童在加沙战火中丧生
  • 钟睒睒:不反对代工,但农夫山泉目前所有产品是无法代工的
  • 特朗普与泽连斯基通话
  • 今晚油价下调,加满一箱油将省9元