· 7 years ago · Oct 04, 2018, 12:10 PM
1// To get the basic auth details
2private static void init() {
3 if(accessKey == null) {
4 accessKey='***';
5 secretKey='***';
6 host='sns.eu-west-1.amazonaws.com';
7 topic='**';
8 regionName= 'eu-west-1';
9 }
10}
11
12public static HttpResponse sendMessage(String topicName, String messageBody) {
13 init();
14 System.debug('accessKey --> ' + accessKey);
15 System.debug('secretKey --> ' + secretKey);
16 System.debug('host --> ' + host);
17
18 Map<String,String> params = new Map<String,String>();
19 params.put('AWSAccessKeyId',encode(accessKey));
20 params.put('Action','Publish');
21 params.put('MessageBody',encode(messageBody));
22 params.put('Timestamp',encode(getCurrentDate()));
23 params.put('SignatureMethod','HmacSHA1');
24 params.put('SignatureVersion','2');
25 params.put('Version','2010-03-31');
26 params.put('TargetArn','sns-euw1-ap-pe-df-product-store-products-d');
27 params.put('regionName','eu-west-1');
28
29
30 //The string to sign has to be sorted by keys
31 List<String> sortedKeys = new List<String>();
32 sortedKeys.addAll(params.keySet());
33 sortedKeys.sort();
34
35 String toSign = 'POSTn' + host +'n' + topicName + 'n';
36 Integer p = 0;
37 for (String key : sortedKeys) {
38 String value = params.get(key);
39 if (p > 0) {
40 toSign += '&';
41 }
42 p++;
43 toSign += key+'='+value;
44 }
45
46 params.put('Signature',getMac(toSign,secretKey));
47
48 String url = 'https://'+ host + topicName +'?';
49 p = 0;
50 for (String key : params.keySet()) {
51 if (p > 0) {
52 url += '&';
53 }
54 p++;
55 url += key+'='+params.get(key);
56 }
57
58 HttpRequest req = new HttpRequest();
59 req.setEndPoint(url);
60 req.setMethod('POST');
61 Http http = new Http();
62 HttpResponse res = null;
63 try {
64 System.debug('Signed string: ' + toSign);
65 System.debug('Url: ' + url);
66 res = http.send(req);
67 System.debug('Status: ' + res.getStatus());
68 System.debug('Code : ' + res.getStatusCode());
69 System.debug('Body : ' + res.getBody());
70
71 }
72 catch (System.CalloutException e) {
73 System.debug('ERROR: ' + e);
74 }
75 return res;
76}
77
78private static String getCurrentDate() {
79 return DateTime.now().formatGmt('yyyy-MM-dd'T'HH:mm:ss.SSS'Z'');
80}
81
82//Amazon wants + and * to be escaped, but not ~
83private static String encode(String message){
84 return EncodingUtil.urlEncode(message,'UTF-8').replace('+', '%20').replace('*', '%2A').replace('%7E','~');
85}
86
87private static String getMac(String RequestString, String secretkey) {
88 String algorithmName = 'hmacSHA1';
89 Blob input = Blob.valueOf(RequestString);
90 Blob key = Blob.valueOf(secretkey);
91 Blob signing =Crypto.generateMac(algorithmName, input, key);
92 return EncodingUtil.urlEncode(EncodingUtil.base64Encode(signing), 'UTF-8');
93}