-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathWebhookController.php
More file actions
71 lines (57 loc) · 2.08 KB
/
WebhookController.php
File metadata and controls
71 lines (57 loc) · 2.08 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
<?php
namespace App\Controllers;
use App\Models\Order;
class WebhookController extends BaseController
{
public function index($request, $response)
{
// settings
$settings = $this->container->get('settings');
// json data received
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if (!is_array($decoded)) {
throw new Exception('Received content contained invalid JSON!');
}
// received event
$eventType = $decoded['eventType'];
$data = $decoded['data'];
$signature = $decoded['signature'];
//
unset($decoded['signature']);
// public key
$publicKey = $settings['dataDir'] . DIRECTORY_SEPARATOR . 'certs' . DIRECTORY_SEPARATOR . 'public.pem';
$publicKeyPem = openssl_pkey_get_public(file_get_contents($publicKey));
$dataNotVerified = json_encode($decoded, JSON_UNESCAPED_UNICODE);
// verify signature
$isValid = openssl_verify($dataNotVerified, base64_decode($signature), $publicKeyPem, 'sha256WithRSAEncryption');
// if data is not valid
if (0 == $isValid) {
throw new Exception('Signature error!');
};
// find order by invoice number
$order = Order::query()->where('invoice_number', '=', $data['invoiceNumber'])->first();
//
switch ($eventType) {
case 'invoice.paid':
//
$order->status = Order::STATUS_COMPLETE;
$order->save();
break;
case 'invoice.cancelled':
$order->status = Order::STATUS_CANCELED;
$order->save();
break;
case 'invoice.expired':
$order->status = Order::STATUS_FAILED;
$order->save();
break;
}
return $response->withJson([
'code' => 0, 'response' => ['message' => 'OK']],
200,
JSON_UNESCAPED_UNICODE
);
}
}