-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomServiceExample.php
More file actions
443 lines (398 loc) · 14.8 KB
/
Copy pathCustomServiceExample.php
File metadata and controls
443 lines (398 loc) · 14.8 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
<?php
/**
* Custom Service Webhook Example (PayPal)
*
* This example shows how to add support for a custom webhook service
* using LaraWebhook's extensible Strategy Pattern architecture.
*
* LaraWebhook natively supports: Stripe, GitHub, Slack, Shopify
*
* The same pattern applies to any additional service:
* - PayPal (this example)
* - Mailchimp
* - SendGrid
* - Twilio
* - Square
* - etc.
*
* LaraWebhook uses two Strategy interfaces:
* - PayloadParserInterface: Extracts event type and metadata from payloads
* - SignatureValidatorInterface: Validates webhook signatures
*/
namespace App\Webhook\Parsers;
use Proxynth\Larawebhook\Contracts\PayloadParserInterface;
/**
* Step 1: Create a Payload Parser
*
* Implement PayloadParserInterface to handle PayPal's payload format.
*
* @see https://developer.paypal.com/api/rest/webhooks/
*/
class PayPalPayloadParser implements PayloadParserInterface
{
/**
* Extract the event type from PayPal payload.
*
* PayPal uses "event_type" field (e.g., PAYMENT.CAPTURE.COMPLETED)
*/
public function extractEventType(array $data): string
{
return $data['event_type'] ?? 'unknown';
}
/**
* Extract metadata from PayPal payload.
*/
public function extractMetadata(array $data): array
{
$resource = $data['resource'] ?? [];
return [
'event_id' => $data['id'] ?? null,
'event_type' => $data['event_type'] ?? null,
'resource_type' => $data['resource_type'] ?? null,
'resource_id' => $resource['id'] ?? null,
'amount' => $resource['amount']['value'] ?? null,
'currency' => $resource['amount']['currency_code'] ?? null,
'status' => $resource['status'] ?? null,
'create_time' => $data['create_time'] ?? null,
];
}
public function serviceName(): string
{
return 'paypal';
}
}
/*
* ═══════════════════════════════════════════════════════════════════════════
*/
namespace App\Webhook\Validators;
use Proxynth\Larawebhook\Contracts\SignatureValidatorInterface;
use Proxynth\Larawebhook\Exceptions\InvalidSignatureException;
/**
* Step 2: Create a Signature Validator
*
* PayPal uses certificate-based validation or transmission signature.
* This example shows simplified signature validation.
*
* @see https://developer.paypal.com/docs/api-basics/notifications/webhooks/notification-messages/
*/
class PayPalSignatureValidator implements SignatureValidatorInterface
{
/**
* Validate PayPal webhook signature.
*
* PayPal sends several headers for validation:
* - PAYPAL-TRANSMISSION-ID
* - PAYPAL-TRANSMISSION-TIME
* - PAYPAL-TRANSMISSION-SIG
* - PAYPAL-CERT-URL
*
* For simplicity, this example validates using webhook ID + transmission data.
* In production, you should use PayPal's certificate-based validation.
*
* @throws InvalidSignatureException
*/
public function validate(string $payload, string $signature, string $secret, int $tolerance = 300): bool
{
// Signature format: "transmission_id|transmission_time|webhook_id|crc32"
$parts = explode('|', $signature);
if (count($parts) < 4) {
throw new InvalidSignatureException('Invalid PayPal signature format.');
}
[$transmissionId, $transmissionTime, $webhookId, $expectedCrc] = $parts;
// Verify the webhook ID matches our secret (webhook ID)
if ($webhookId !== $secret) {
throw new InvalidSignatureException('Invalid PayPal webhook ID.');
}
// Verify CRC32 checksum of the payload
$actualCrc = sprintf('%u', crc32($payload));
if ($actualCrc !== $expectedCrc) {
throw new InvalidSignatureException('Invalid PayPal webhook signature (CRC mismatch).');
}
return true;
}
public function serviceName(): string
{
return 'paypal';
}
}
/*
* ═══════════════════════════════════════════════════════════════════════════
*
* Step 3: Register in WebhookService Enum
*
* Add your service to src/Enums/WebhookService.php:
*
* enum WebhookService: string
* {
* case Stripe = 'stripe';
* case Github = 'github';
* case Slack = 'slack';
* case Shopify = 'shopify';
* case PayPal = 'paypal'; // Add new case
*
* public function parser(): PayloadParserInterface
* {
* return match ($this) {
* self::Stripe => new StripePayloadParser,
* self::Github => new GithubPayloadParser,
* self::Slack => new SlackPayloadParser,
* self::Shopify => new ShopifyPayloadParser,
* self::PayPal => new PayPalPayloadParser, // Add mapping
* };
* }
*
* public function signatureValidator(): SignatureValidatorInterface
* {
* return match ($this) {
* self::Stripe => new StripeSignatureValidator,
* self::Github => new GithubSignatureValidator,
* self::Slack => new SlackSignatureValidator,
* self::Shopify => new ShopifySignatureValidator,
* self::PayPal => new PayPalSignatureValidator, // Add mapping
* };
* }
*
* public function signatureHeader(): string
* {
* return match ($this) {
* self::Stripe => 'Stripe-Signature',
* self::Github => 'X-Hub-Signature-256',
* self::Slack => 'X-Slack-Signature',
* self::Shopify => 'X-Shopify-Hmac-Sha256',
* self::PayPal => 'PAYPAL-TRANSMISSION-SIG', // Add header
* };
* }
* }
*
* ═══════════════════════════════════════════════════════════════════════════
*
* Step 4: Add Configuration
*
* In config/larawebhook.php:
*/
/*
'services' => [
'stripe' => [
'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
'tolerance' => 300,
],
'github' => [
'webhook_secret' => env('GITHUB_WEBHOOK_SECRET'),
'tolerance' => 300,
],
'slack' => [
'webhook_secret' => env('SLACK_WEBHOOK_SECRET'),
'tolerance' => 300,
],
'shopify' => [
'webhook_secret' => env('SHOPIFY_WEBHOOK_SECRET'),
'tolerance' => 300,
],
'paypal' => [
'webhook_secret' => env('PAYPAL_WEBHOOK_ID'), // PayPal uses webhook ID
'tolerance' => 300,
],
],
*/
/*
* In .env:
*
* PAYPAL_WEBHOOK_ID=your_paypal_webhook_id
*
* ═══════════════════════════════════════════════════════════════════════════
*/
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
/**
* Step 5: Create the Controller
*
* Use the standard validate-webhook middleware - it now works with your service!
*/
class PayPalWebhookController extends Controller
{
/**
* Handle PayPal webhooks.
*
* Route: POST /paypal-webhook
* Middleware: validate-webhook:paypal
*/
public function handle(Request $request): JsonResponse
{
$payload = json_decode($request->getContent(), true);
$eventType = $payload['event_type'] ?? 'unknown';
Log::info('PayPal webhook received', [
'event_type' => $eventType,
'event_id' => $payload['id'] ?? null,
]);
// Route to specific handlers based on event type
match ($eventType) {
'PAYMENT.CAPTURE.COMPLETED' => $this->handlePaymentCaptured($payload),
'PAYMENT.CAPTURE.DENIED' => $this->handlePaymentDenied($payload),
'PAYMENT.CAPTURE.REFUNDED' => $this->handlePaymentRefunded($payload),
'CHECKOUT.ORDER.APPROVED' => $this->handleOrderApproved($payload),
'CHECKOUT.ORDER.COMPLETED' => $this->handleOrderCompleted($payload),
'BILLING.SUBSCRIPTION.CREATED' => $this->handleSubscriptionCreated($payload),
'BILLING.SUBSCRIPTION.ACTIVATED' => $this->handleSubscriptionActivated($payload),
'BILLING.SUBSCRIPTION.CANCELLED' => $this->handleSubscriptionCancelled($payload),
'INVOICING.INVOICE.PAID' => $this->handleInvoicePaid($payload),
default => $this->handleUnknownEvent($eventType, $payload),
};
return response()->json(['status' => 'success']);
}
private function handlePaymentCaptured(array $payload): void
{
$resource = $payload['resource'] ?? [];
Log::info('PayPal payment captured', [
'capture_id' => $resource['id'] ?? null,
'amount' => $resource['amount']['value'] ?? null,
'currency' => $resource['amount']['currency_code'] ?? null,
]);
// Example: Update order status
// Order::where('paypal_order_id', $resource['supplementary_data']['related_ids']['order_id'] ?? null)
// ->update(['status' => 'paid']);
}
private function handlePaymentDenied(array $payload): void
{
Log::warning('PayPal payment denied', [
'resource_id' => $payload['resource']['id'] ?? null,
]);
}
private function handlePaymentRefunded(array $payload): void
{
Log::info('PayPal payment refunded', [
'resource_id' => $payload['resource']['id'] ?? null,
]);
}
private function handleOrderApproved(array $payload): void
{
Log::info('PayPal order approved', [
'order_id' => $payload['resource']['id'] ?? null,
]);
}
private function handleOrderCompleted(array $payload): void
{
Log::info('PayPal order completed', [
'order_id' => $payload['resource']['id'] ?? null,
]);
}
private function handleSubscriptionCreated(array $payload): void
{
Log::info('PayPal subscription created', [
'subscription_id' => $payload['resource']['id'] ?? null,
'plan_id' => $payload['resource']['plan_id'] ?? null,
]);
}
private function handleSubscriptionActivated(array $payload): void
{
Log::info('PayPal subscription activated', [
'subscription_id' => $payload['resource']['id'] ?? null,
]);
}
private function handleSubscriptionCancelled(array $payload): void
{
Log::info('PayPal subscription cancelled', [
'subscription_id' => $payload['resource']['id'] ?? null,
]);
}
private function handleInvoicePaid(array $payload): void
{
Log::info('PayPal invoice paid', [
'invoice_id' => $payload['resource']['id'] ?? null,
]);
}
private function handleUnknownEvent(string $eventType, array $payload): void
{
Log::warning('Unknown PayPal webhook event', ['event_type' => $eventType]);
}
}
/*
* ═══════════════════════════════════════════════════════════════════════════
*
* Step 6: Define the Route
*
* In routes/web.php:
*/
/*
use App\Http\Controllers\PayPalWebhookController;
Route::post('/paypal-webhook', [PayPalWebhookController::class, 'handle'])
->middleware('validate-webhook:paypal');
*/
/*
* ═══════════════════════════════════════════════════════════════════════════
*
* Step 7: Configure in PayPal Developer Dashboard
*
* 1. Go to PayPal Developer Dashboard → Webhooks
* 2. Click "Add Webhook"
* 3. Enter URL: https://your-domain.com/paypal-webhook
* 4. Select events to subscribe to:
* - Payment Capture Completed
* - Payment Capture Denied
* - Checkout Order Approved
* - etc.
* 5. Copy the Webhook ID and add to .env as PAYPAL_WEBHOOK_ID
*
* ═══════════════════════════════════════════════════════════════════════════
*
* Testing Your Custom Webhook
*
* Use PayPal's webhook simulator in the Developer Dashboard:
* 1. Go to Webhooks → Simulate Event
* 2. Select your webhook URL
* 3. Choose an event type
* 4. Click "Send Test"
*
* Or use curl to test locally:
*/
/*
# Example test with simplified signature
WEBHOOK_ID="your_paypal_webhook_id"
PAYLOAD='{"id":"WH-123","event_type":"PAYMENT.CAPTURE.COMPLETED","resource":{"id":"CAP-123"}}'
CRC=$(echo -n "$PAYLOAD" | php -r "echo sprintf('%u', crc32(file_get_contents('php://stdin')));")
SIGNATURE="TX-123|2024-01-15T10:30:00Z|$WEBHOOK_ID|$CRC"
curl -X POST http://localhost:8000/paypal-webhook \
-H "Content-Type: application/json" \
-H "PAYPAL-TRANSMISSION-SIG: $SIGNATURE" \
-d "$PAYLOAD"
*/
/*
* ═══════════════════════════════════════════════════════════════════════════
*
* Summary: Adding a Custom Service with Strategy Pattern
*
* 1. Create a PayloadParser implementing PayloadParserInterface
* - extractEventType(): Parse event type from payload
* - extractMetadata(): Extract relevant metadata
* - serviceName(): Return service identifier
*
* 2. Create a SignatureValidator implementing SignatureValidatorInterface
* - validate(): Verify the webhook signature
* - serviceName(): Return service identifier
*
* 3. Register in WebhookService enum:
* - Add new case
* - Add parser() mapping
* - Add signatureValidator() mapping
* - Add signatureHeader() mapping
*
* 4. Add configuration in config/larawebhook.php
*
* 5. Create controller and route with validate-webhook:{service} middleware
*
* Supported services out of the box:
* ✅ Stripe
* ✅ GitHub
* ✅ Slack
* ✅ Shopify
*
* This pattern works for any additional webhook service:
* - PayPal (this example)
* - Mailchimp → HMAC-SHA256 validation
* - SendGrid → HTTP Basic Auth or ECDSA signature
* - Twilio → SHA1 signature validation
* - Square → HMAC-SHA256 validation
*
* ═══════════════════════════════════════════════════════════════════════════
*/