-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathwebhook-endpoint.php
More file actions
105 lines (82 loc) · 3.05 KB
/
webhook-endpoint.php
File metadata and controls
105 lines (82 loc) · 3.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
//payload
$payload = (array)json_decode(file_get_contents('php://input'));
writeLog('Payload',$payload);
// headers
$messageType = $_SERVER['HTTP_X_AMZ_SNS_MESSAGE_TYPE'];
//logics
//verify signature
$signingCertURL = $payload['SigningCertURL'];
$certUrlValidation = validateUrl($signingCertURL);
if($certUrlValidation == '1'){
$pubCert = get_content($signingCertURL);
$signature = $payload['Signature'];
$signatureDecoded = base64_decode($signature);
$content = getStringToSign($payload);
if($content!=''){
$verified = openssl_verify($content, $signatureDecoded, $pubCert, OPENSSL_ALGO_SHA1);
if($verified=='1'){
if($messageType=="SubscriptionConfirmation"){
$subscribeURL = $payload['SubscribeURL'];
writeLog('Subscribe',$subscribeURL);
//subscribe
$url = curl_init($subscribeURL);
curl_exec($url);
}
else if($messageType=="Notification"){
$notificationData = $payload['Message'];
writeLog('NotificationData-Message',$notificationData);
}
}
}
}
function writeLog($logName, $logData){
file_put_contents('./log-'.$logName.date("j.n.Y").'.log',$logData,FILE_APPEND);
}
function get_content($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function getStringToSign($message)
{
$signableKeys = [
'Message',
'MessageId',
'Subject',
'SubscribeURL',
'Timestamp',
'Token',
'TopicArn',
'Type'
];
$stringToSign = '';
if ($message['SignatureVersion'] !== '1') {
$errorLog = "The SignatureVersion \"{$message['SignatureVersion']}\" is not supported.";
writeLog('SignatureVersion-Error', $errorLog);
}
else{
foreach ($signableKeys as $key) {
if (isset($message[$key])) {
$stringToSign .= "{$key}\n{$message[$key]}\n";
}
}
writeLog('StringToSign', $stringToSign."\n");
}
return $stringToSign;
}
function validateUrl($url)
{
$defaultHostPattern = '/^sns\.[a-zA-Z0-9\-]{3,}\.amazonaws\.com(\.cn)?$/';
$parsed = parse_url($url);
if (empty($parsed['scheme']) || empty($parsed['host']) || $parsed['scheme'] !== 'https' || substr($url, -4) !== '.pem' || !preg_match($defaultHostPattern, $parsed['host']) ) {
return false;
}
else{
return true;
}
}
?>