Skip to content

Commit 124bcfc

Browse files
authored
Create webhook-endpoint.php
1 parent 1435de9 commit 124bcfc

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed

webhook-endpoint.php

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

0 commit comments

Comments
 (0)