咨询:是否有Salesforce与Amazon SNS集成的参考示例?
Absolutely! I’ve implemented this integration a handful of times, so here’s a practical, step-by-step guide with working code examples to help you connect Salesforce and Amazon SNS smoothly.
Salesforce + Amazon SNS Integration: Practical Examples & Guide
Prerequisites First
- Salesforce Side: A user profile with
API Enabledpermission, access to create/run Apex classes, and (if using direct API calls) the SNS endpoint added toRemote Site Settings. - AWS Side: An IAM user with permissions to interact with SNS (e.g., a custom policy allowing
sns:Publishon your target topic), your AWS Access Key/Secret Key, and a pre-created SNS Topic ARN.
Option 1: Direct Apex Call to AWS SNS REST API
This approach gives you full control without relying on third-party connectors. You’ll handle AWS signature generation (critical for authenticating requests) and HTTP calls directly in Apex.
Example Apex Class
public class SalesforceToSNS { // Store these securely in Named Credentials/Custom Settings for production! private static final String AWS_ACCESS_KEY = 'YOUR_AWS_ACCESS_KEY'; private static final String AWS_SECRET_KEY = 'YOUR_AWS_SECRET_KEY'; private static final String AWS_REGION = 'us-east-1'; // Update to your region private static final String SNS_TOPIC_ARN = 'arn:aws:sns:us-east-1:123456789012:Your-Topic-Name'; public static void publishMessage(String messageBody, String messageSubject) { String snsEndpoint = 'https://sns.' + AWS_REGION + '.amazonaws.com/'; // Build request parameters required by SNS Publish API Map<String, String> requestParams = new Map<String, String> { 'Action' => 'Publish', 'TopicArn' => SNS_TOPIC_ARN, 'Message' => messageBody, 'Subject' => messageSubject, 'Version' => '2010-03-31', 'Timestamp' => DateTime.now().formatGMT('yyyy-MM-dd\'T\'HH:mm:ss\'Z\''), 'AWSAccessKeyId' => AWS_ACCESS_KEY }; // Generate AWS Signature Version 2 (simplified; use SigV4 for production) String canonicalQuery = buildCanonicalQueryString(requestParams); String signature = generateHmacSignature(canonicalQuery, AWS_SECRET_KEY); requestParams.put('Signature', signature); requestParams.put('SignatureVersion', '2'); requestParams.put('SignatureMethod', 'HmacSHA256'); // Send HTTP POST request to SNS Http http = new Http(); HttpRequest req = new HttpRequest(); req.setEndpoint(snsEndpoint); req.setMethod('POST'); req.setBody(buildQueryString(requestParams)); try { HttpResponse res = http.send(req); if (res.getStatusCode() == 200) { System.debug('✅ Message sent successfully! Response: ' + res.getBody()); } else { System.debug('❌ Failed to send message. Status: ' + res.getStatusCode() + ' | Error: ' + res.getBody()); } } catch (Exception e) { System.debug('⚠️ Exception occurred: ' + e.getMessage()); } } // Helper to sort and format parameters into a canonical string private static String buildCanonicalQueryString(Map<String, String> params) { List<String> sortedKeys = new List<String>(params.keySet()); sortedKeys.sort(); String canonical = ''; for (String key : sortedKeys) { canonical += key + '=' + EncodingUtil.urlEncode(params.get(key), 'UTF-8') + '&'; } return canonical.removeEnd('&'); } // Helper to generate HMAC SHA256 signature private static String generateHmacSignature(String data, String secret) { Blob mac = Crypto.generateMac('HmacSHA256', Blob.valueOf(data), Blob.valueOf(secret)); return EncodingUtil.base64Encode(mac); } }
How to Use It
Call this method from a trigger, Visualforce button, or Apex job like so:
// Example: Publish a message when an Account is created trigger AccountTrigger on Account (after insert) { for (Account acc : Trigger.new) { SalesforceToSNS.publishMessage( 'New Account created: ' + acc.Name + ' | ID: ' + acc.Id, 'Salesforce: New Account Alert' ); } }
Option 2: Use AWS Connector for Salesforce
If you prefer a low-code approach, the official AWS Connector (available on AppExchange) handles authentication and API abstraction for you.
Setup Steps
- Install the AWS Toolkit for Salesforce from AppExchange.
- Configure your AWS credentials in the connector settings (navigate to AWS > Credentials).
- Ensure your IAM user has the necessary SNS permissions.
Example Apex Code
public class SNSConnectorExample { public static void publishViaConnector(String message, String subject) { // Initialize SNS client with configured credentials AmazonSNSClient snsClient = new AmazonSNSClient(AWSCredentialsProvider.getDefaultAWSCredentialsProvider()); snsClient.setRegion(Region.getRegion(Regions.US_EAST_1)); // Update to your region // Create publish request PublishRequest publishReq = new PublishRequest() .withTopicArn('arn:aws:sns:us-east-1:123456789012:Your-Topic-Name') .withMessage(message) .withSubject(subject); try { PublishResult result = snsClient.publish(publishReq); System.debug('✅ Message published! ID: ' + result.getMessageId()); } catch (AmazonServiceException ase) { System.debug('❌ AWS Service Error: ' + ase.getErrorMessage()); } catch (AmazonClientException ace) { System.debug('⚠️ AWS Client Error: ' + ace.getMessage()); } } }
Key Notes for Production
- Security: Never hardcode AWS credentials in Apex. Use Named Credentials or Custom Metadata Types with encryption to store sensitive keys.
- Error Handling: Add retry logic for transient errors (e.g., network timeouts) and log failures to Salesforce’s
EventLogFileor a custom object. - Permissions: Restrict Salesforce user access to these Apex classes, and follow the principle of least privilege for your AWS IAM user (only grant
sns:Publishon the specific topic, not full SNS access). - Testing: Validate the integration in a sandbox first—check the AWS SNS console to confirm messages are being received.
内容的提问来源于stack exchange,提问作者Raghu
相关产品推荐
相关产品推荐

