傳送推送通知 - Amazon Pinpoint

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

傳送推送通知

Amazon Pinpoint API 可將交易推播通知傳送到特定的裝置識別碼。本節包含完整的程式碼範例,您可以使用這些範例,藉由 AWS SDK 透過 Amazon Pinpoint API 傳送推播通知。

您可以使用這些範例,透過 Amazon Pinpoint 支援的任何推播通知服務傳送推播通知。Amazon Pinpoint 目前支援以下管道:Firebase Cloud Messaging (FCM)、Apple 推播通知服務 (APN)、百度雲端推送和 Amazon Device Messaging (ADM)。

注意

透過 Firebase Cloud Messaging (FCM) 服務傳送推播通知時,請在 Amazon Pinpoint API 的呼叫中使用服務名稱 GCM。Google 已於 2018 年 4 月 10 日終止 Google Cloud Messaging (GCM) 服務。但 Amazon Pinpoint API 會使用透過 FCM 服務傳訊的 GCM 服務名稱,這樣才能與 GCM 服務停止之前編寫的 API 程式碼保持一致。

JavaScript (Node.js)

使用此範例,藉由 AWS SDK for JavaScript in Node.js 傳送推播通知。此範例假設您已安裝並設定了 SDK for JavaScript in Node.js。

此範例也會假設您使用共用的登入資料檔案,指定現有 使用者的存取金鑰和私密存取金鑰。詳情請參閱 AWS SDK for JavaScript in Node.js 開發人員指南中的設定憑證

'use strict'; const AWS = require('aws-sdk'); // The AWS Region that you want to use to send the message. For a list of // AWS Regions where the Amazon Pinpoint API is available, see // https://docs.aws.amazon.com/pinpoint/latest/apireference/ const region = 'us-east-1'; // The title that appears at the top of the push notification. var title = 'Test message sent from Amazon Pinpoint.'; // The content of the push notification. var message = 'This is a sample message sent from Amazon Pinpoint by using the ' + 'AWS SDK for JavaScript in Node.js'; // The Amazon Pinpoint project ID that you want to use when you send this // message. Make sure that the push channel is enabled for the project that // you choose. var applicationId = 'ce796be37f32f178af652b26eexample'; // An object that contains the unique token of the device that you want to send // the message to, and the push service that you want to use to send the message. var recipient = { 'token': 'a0b1c2d3e4f5g6h7i8j9k0l1m2n3o4p5q6r7s8t9u0v1w2x3y4z5a6b7c8d8e9f0', 'service': 'GCM' }; // The action that should occur when the recipient taps the message. Possible // values are OPEN_APP (opens the app or brings it to the foreground), // DEEP_LINK (opens the app to a specific page or interface), or URL (opens a // specific URL in the device's web browser.) var action = 'URL'; // This value is only required if you use the URL action. This variable contains // the URL that opens in the recipient's web browser. var url = 'https://www.example.com'; // The priority of the push notification. If the value is 'normal', then the // delivery of the message is optimized for battery usage on the recipient's // device, and could be delayed. If the value is 'high', then the notification is // sent immediately, and might wake a sleeping device. var priority = 'normal'; // The amount of time, in seconds, that the push notification service provider // (such as FCM or APNS) should attempt to deliver the message before dropping // it. Not all providers allow you specify a TTL value. var ttl = 30; // Boolean that specifies whether the notification is sent as a silent // notification (a notification that doesn't display on the recipient's device). var silent = false; function CreateMessageRequest() { var token = recipient['token']; var service = recipient['service']; if (service == 'GCM') { var messageRequest = { 'Addresses': { [token]: { 'ChannelType' : 'GCM' } }, 'MessageConfiguration': { 'GCMMessage': { 'Action': action, 'Body': message, 'Priority': priority, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } }; } else if (service == 'APNS') { var messageRequest = { 'Addresses': { [token]: { 'ChannelType' : 'APNS' } }, 'MessageConfiguration': { 'APNSMessage': { 'Action': action, 'Body': message, 'Priority': priority, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } }; } else if (service == 'BAIDU') { var messageRequest = { 'Addresses': { [token]: { 'ChannelType' : 'BAIDU' } }, 'MessageConfiguration': { 'BaiduMessage': { 'Action': action, 'Body': message, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } }; } else if (service == 'ADM') { var messageRequest = { 'Addresses': { [token]: { 'ChannelType' : 'ADM' } }, 'MessageConfiguration': { 'ADMMessage': { 'Action': action, 'Body': message, 'SilentPush': silent, 'Title': title, 'Url': url } } }; } return messageRequest } function ShowOutput(data){ if (data["MessageResponse"]["Result"][recipient["token"]]["DeliveryStatus"] == "SUCCESSFUL") { var status = "Message sent! Response information: "; } else { var status = "The message wasn't sent. Response information: "; } console.log(status); console.dir(data, { depth: null }); } function SendMessage() { var token = recipient['token']; var service = recipient['service']; var messageRequest = CreateMessageRequest(); // Specify that you're using a shared credentials file, and specify the // IAM profile to use. var credentials = new AWS.SharedIniFileCredentials({ profile: 'default' }); AWS.config.credentials = credentials; // Specify the AWS Region to use. AWS.config.update({ region: region }); //Create a new Pinpoint object. var pinpoint = new AWS.Pinpoint(); var params = { "ApplicationId": applicationId, "MessageRequest": messageRequest }; // Try to send the message. pinpoint.sendMessages(params, function(err, data) { if (err) console.log(err); else ShowOutput(data); }); } SendMessage()
Python

使用 AWS SDK for Python (Boto3) 藉此範例傳送推送通知。此範例假設您已安裝並設定了 SDK for Python (Boto3)。

此範例也會假設您使用共用的登入資料檔案,指定現有 使用者的存取金鑰和私密存取金鑰。詳情請參閱 AWS SDK for Python (Boto3) API 參考中的憑證

import json import boto3 from botocore.exceptions import ClientError # The AWS Region that you want to use to send the message. For a list of # AWS Regions where the Amazon Pinpoint API is available, see # https://docs.aws.amazon.com/pinpoint/latest/apireference/ region = "us-east-1" # The title that appears at the top of the push notification. title = "Test message sent from Amazon Pinpoint." # The content of the push notification. message = ("This is a sample message sent from Amazon Pinpoint by using the " "AWS SDK for Python (Boto3).") # The Amazon Pinpoint project/application ID to use when you send this message. # Make sure that the push channel is enabled for the project or application # that you choose. application_id = "ce796be37f32f178af652b26eexample" # A dictionary that contains the unique token of the device that you want to send the # message to, and the push service that you want to use to send the message. recipient = { "token": "a0b1c2d3e4f5g6h7i8j9k0l1m2n3o4p5q6r7s8t9u0v1w2x3y4z5a6b7c8d8e9f0", "service": "GCM" } # The action that should occur when the recipient taps the message. Possible # values are OPEN_APP (opens the app or brings it to the foreground), # DEEP_LINK (opens the app to a specific page or interface), or URL (opens a # specific URL in the device's web browser.) action = "URL" # This value is only required if you use the URL action. This variable contains # the URL that opens in the recipient's web browser. url = "https://www.example.com" # The priority of the push notification. If the value is 'normal', then the # delivery of the message is optimized for battery usage on the recipient's # device, and could be delayed. If the value is 'high', then the notification is # sent immediately, and might wake a sleeping device. priority = "normal" # The amount of time, in seconds, that the push notification service provider # (such as FCM or APNS) should attempt to deliver the message before dropping # it. Not all providers allow you specify a TTL value. ttl = 30 # Boolean that specifies whether the notification is sent as a silent # notification (a notification that doesn't display on the recipient's device). silent = False # Set the MessageType based on the values in the recipient variable. def create_message_request(): token = recipient["token"] service = recipient["service"] if service == "GCM": message_request = { 'Addresses': { token: { 'ChannelType': 'GCM' } }, 'MessageConfiguration': { 'GCMMessage': { 'Action': action, 'Body': message, 'Priority' : priority, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } } elif service == "APNS": message_request = { 'Addresses': { token: { 'ChannelType': 'APNS' } }, 'MessageConfiguration': { 'APNSMessage': { 'Action': action, 'Body': message, 'Priority' : priority, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } } elif service == "BAIDU": message_request = { 'Addresses': { token: { 'ChannelType': 'BAIDU' } }, 'MessageConfiguration': { 'BaiduMessage': { 'Action': action, 'Body': message, 'SilentPush': silent, 'Title': title, 'TimeToLive': ttl, 'Url': url } } } elif service == "ADM": message_request = { 'Addresses': { token: { 'ChannelType': 'ADM' } }, 'MessageConfiguration': { 'ADMMessage': { 'Action': action, 'Body': message, 'SilentPush': silent, 'Title': title, 'Url': url } } } else: message_request = None return message_request # Show a success or failure message, and provide the response from the API. def show_output(response): if response['MessageResponse']['Result'][recipient["token"]]['DeliveryStatus'] == "SUCCESSFUL": status = "Message sent! Response information:\n" else: status = "The message wasn't sent. Response information:\n" print(status, json.dumps(response,indent=4)) # Send the message through the appropriate channel. def send_message(): token = recipient["token"] service = recipient["service"] message_request = create_message_request() client = boto3.client('pinpoint',region_name=region) try: response = client.send_messages( ApplicationId=application_id, MessageRequest=message_request ) except ClientError as e: print(e.response['Error']['Message']) else: show_output(response) send_message()