Esempi di Amazon Pinpoint con SDK for JavaScript (v3) - AWS SDK for JavaScript

La Guida API di riferimento AWS SDK for JavaScript V3 descrive in dettaglio tutte le API operazioni per la AWS SDK for JavaScript versione 3 (V3).

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Esempi di Amazon Pinpoint con SDK for JavaScript (v3)

I seguenti esempi di codice mostrano come eseguire azioni e implementare scenari comuni utilizzando AWS SDK for JavaScript (v3) con Amazon Pinpoint.

Le operazioni sono estratti di codice da programmi più grandi e devono essere eseguite nel contesto. Mentre le azioni mostrano come chiamare le singole funzioni di servizio, puoi vedere le azioni nel loro contesto negli scenari correlati.

Ogni esempio include un collegamento al codice sorgente completo, in cui è possibile trovare istruzioni su come configurare ed eseguire il codice nel contesto.

Argomenti

Azioni

Il seguente esempio di codice mostra come utilizzareSendMessages.

SDKper JavaScript (v3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l’esecuzione nel Repository di esempi di codice AWS.

Creare il client in un modulo separato ed esportarlo.

import { PinpointClient } from "@aws-sdk/client-pinpoint"; // Set the AWS Region. const REGION = "us-east-1"; export const pinClient = new PinpointClient({ region: REGION });

Invia un messaggio e-mail.

// Import required AWS SDK clients and commands for Node.js import { SendMessagesCommand } from "@aws-sdk/client-pinpoint"; import { pinClient } from "./libs/pinClient.js"; // The FromAddress must be verified in SES. const fromAddress = "FROM_ADDRESS"; const toAddress = "TO_ADDRESS"; const projectId = "PINPOINT_PROJECT_ID"; // The subject line of the email. const subject = "Amazon Pinpoint Test (AWS SDK for JavaScript in Node.js)"; // The email body for recipients with non-HTML email clients. const body_text = `Amazon Pinpoint Test (SDK for JavaScript in Node.js) ---------------------------------------------------- This email was sent with Amazon Pinpoint using the AWS SDK for JavaScript in Node.js. For more information, see https://aws.amazon.com/sdk-for-node-js/`; // The body of the email for recipients whose email clients support HTML content. const body_html = `<html> <head></head> <body> <h1>Amazon Pinpoint Test (SDK for JavaScript in Node.js)</h1> <p>This email was sent with <a href='https://aws.amazon.com/pinpoint/'>the Amazon Pinpoint Email API</a> using the <a href='https://aws.amazon.com/sdk-for-node-js/'> AWS SDK for JavaScript in Node.js</a>.</p> </body> </html>`; // The character encoding for the subject line and message body of the email. const charset = "UTF-8"; const params = { ApplicationId: projectId, MessageRequest: { Addresses: { [toAddress]: { ChannelType: "EMAIL", }, }, MessageConfiguration: { EmailMessage: { FromAddress: fromAddress, SimpleEmail: { Subject: { Charset: charset, Data: subject, }, HtmlPart: { Charset: charset, Data: body_html, }, TextPart: { Charset: charset, Data: body_text, }, }, }, }, }, }; const run = async () => { try { const { MessageResponse } = await pinClient.send( new SendMessagesCommand(params), ); if (!MessageResponse) { throw new Error("No message response."); } if (!MessageResponse.Result) { throw new Error("No message result."); } const recipientResult = MessageResponse.Result[toAddress]; if (recipientResult.StatusCode !== 200) { throw new Error(recipientResult.StatusMessage); } console.log(recipientResult.MessageId); } catch (err) { console.log(err.message); } }; run();

Manda un SMS messaggio

// Import required AWS SDK clients and commands for Node.js import { SendMessagesCommand } from "@aws-sdk/client-pinpoint"; import { pinClient } from "./libs/pinClient.js"; /* The phone number or short code to send the message from. The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format. */ const originationNumber = "SENDER_NUMBER"; //e.g., +1XXXXXXXXXX // The recipient's phone number. For best results, you should specify the phone number in E.164 format. const destinationNumber = "RECEIVER_NUMBER"; //e.g., +1XXXXXXXXXX // The content of the SMS message. const message = "This message was sent through Amazon Pinpoint " + "using the AWS SDK for JavaScript in Node.js. Reply STOP to " + "opt out."; /*The Amazon Pinpoint project/application ID to use when you send this message. Make sure that the SMS channel is enabled for the project or application that you choose.*/ const projectId = "PINPOINT_PROJECT_ID"; //e.g., XXXXXXXX66e4e9986478cXXXXXXXXX /* The type of SMS message that you want to send. If you plan to send time-sensitive content, specify TRANSACTIONAL. If you plan to send marketing-related content, specify PROMOTIONAL.*/ const messageType = "TRANSACTIONAL"; // The registered keyword associated with the originating short code. const registeredKeyword = "myKeyword"; /* The sender ID to use when sending the message. Support for sender ID // varies by country or region. For more information, see https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html.*/ const senderId = "MySenderID"; // Specify the parameters to pass to the API. const params = { ApplicationId: projectId, MessageRequest: { Addresses: { [destinationNumber]: { ChannelType: "SMS", }, }, MessageConfiguration: { SMSMessage: { Body: message, Keyword: registeredKeyword, MessageType: messageType, OriginationNumber: originationNumber, SenderId: senderId, }, }, }, }; const run = async () => { try { const data = await pinClient.send(new SendMessagesCommand(params)); console.log( `Message sent! ${data.MessageResponse.Result[destinationNumber].StatusMessage}`, ); } catch (err) { console.log(err); } }; run();
  • Per API i dettagli, vedere SendMessagesin AWS SDK for JavaScript APIReference.

SDKper JavaScript (v2)
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Invia un messaggio e-mail.

"use strict"; const AWS = require("aws-sdk"); // The AWS Region that you want to use to send the email. For a list of // AWS Regions where the Amazon Pinpoint API is available, see // https://docs.aws.amazon.com/pinpoint/latest/apireference/ const aws_region = "us-west-2"; // The "From" address. This address has to be verified in Amazon Pinpoint // in the region that you use to send email. const senderAddress = "sender@example.com"; // The address on the "To" line. If your Amazon Pinpoint account is in // the sandbox, this address also has to be verified. var toAddress = "recipient@example.com"; // The Amazon Pinpoint project/application ID to use when you send this message. // Make sure that the SMS channel is enabled for the project or application // that you choose. const appId = "ce796be37f32f178af652b26eexample"; // The subject line of the email. var subject = "Amazon Pinpoint (AWS SDK for JavaScript in Node.js)"; // The email body for recipients with non-HTML email clients. var body_text = `Amazon Pinpoint Test (SDK for JavaScript in Node.js) ---------------------------------------------------- This email was sent with Amazon Pinpoint using the AWS SDK for JavaScript in Node.js. For more information, see https:\/\/aws.amazon.com/sdk-for-node-js/`; // The body of the email for recipients whose email clients support HTML content. var body_html = `<html> <head></head> <body> <h1>Amazon Pinpoint Test (SDK for JavaScript in Node.js)</h1> <p>This email was sent with <a href='https://aws.amazon.com/pinpoint/'>the Amazon Pinpoint API</a> using the <a href='https://aws.amazon.com/sdk-for-node-js/'> AWS SDK for JavaScript in Node.js</a>.</p> </body> </html>`; // The character encoding the you want to use for the subject line and // message body of the email. var charset = "UTF-8"; // Specify that you're using a shared credentials file. var credentials = new AWS.SharedIniFileCredentials({ profile: "default" }); AWS.config.credentials = credentials; // Specify the region. AWS.config.update({ region: aws_region }); //Create a new Pinpoint object. var pinpoint = new AWS.Pinpoint(); // Specify the parameters to pass to the API. var params = { ApplicationId: appId, MessageRequest: { Addresses: { [toAddress]: { ChannelType: "EMAIL", }, }, MessageConfiguration: { EmailMessage: { FromAddress: senderAddress, SimpleEmail: { Subject: { Charset: charset, Data: subject, }, HtmlPart: { Charset: charset, Data: body_html, }, TextPart: { Charset: charset, Data: body_text, }, }, }, }, }, }; //Try to send the email. pinpoint.sendMessages(params, function (err, data) { // If something goes wrong, print an error message. if (err) { console.log(err.message); } else { console.log( "Email sent! Message ID: ", data["MessageResponse"]["Result"][toAddress]["MessageId"] ); } });

Manda un SMS messaggio

"use strict"; var 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/. var aws_region = "us-east-1"; // The phone number or short code to send the message from. The phone number // or short code that you specify has to be associated with your Amazon Pinpoint // account. For best results, specify long codes in E.164 format. var originationNumber = "+12065550199"; // The recipient's phone number. For best results, you should specify the // phone number in E.164 format. var destinationNumber = "+14255550142"; // The content of the SMS message. var message = "This message was sent through Amazon Pinpoint " + "using the AWS SDK for JavaScript in Node.js. Reply STOP to " + "opt out."; // The Amazon Pinpoint project/application ID to use when you send this message. // Make sure that the SMS channel is enabled for the project or application // that you choose. var applicationId = "ce796be37f32f178af652b26eexample"; // The type of SMS message that you want to send. If you plan to send // time-sensitive content, specify TRANSACTIONAL. If you plan to send // marketing-related content, specify PROMOTIONAL. var messageType = "TRANSACTIONAL"; // The registered keyword associated with the originating short code. var registeredKeyword = "myKeyword"; // The sender ID to use when sending the message. Support for sender ID // varies by country or region. For more information, see // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html var senderId = "MySenderID"; // Specify that you're using a shared credentials file, and optionally specify // the profile that you want to use. var credentials = new AWS.SharedIniFileCredentials({ profile: "default" }); AWS.config.credentials = credentials; // Specify the region. AWS.config.update({ region: aws_region }); //Create a new Pinpoint object. var pinpoint = new AWS.Pinpoint(); // Specify the parameters to pass to the API. var params = { ApplicationId: applicationId, MessageRequest: { Addresses: { [destinationNumber]: { ChannelType: "SMS", }, }, MessageConfiguration: { SMSMessage: { Body: message, Keyword: registeredKeyword, MessageType: messageType, OriginationNumber: originationNumber, SenderId: senderId, }, }, }, }; //Try to send the message. pinpoint.sendMessages(params, function (err, data) { // If something goes wrong, print an error message. if (err) { console.log(err.message); // Otherwise, show the unique ID for the message. } else { console.log( "Message sent! " + data["MessageResponse"]["Result"][destinationNumber]["StatusMessage"] ); } });
  • Per API i dettagli, vedere SendMessagesin AWS SDK for JavaScript APIReference.