Class: Api::WebhooksController

Inherits:
ActionController::API
  • Object
show all
Includes:
ElasticApmContext
Defined in:
app/controllers/api/webhooks_controller.rb

Overview

typed: ignore

Instance Method Summary collapse

Instance Method Details

#cc_responseObject



605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
# File 'app/controllers/api/webhooks_controller.rb', line 605

def cc_response
  hash_transaction_voucher = params[:transaction_id]
  hash_reservation = params[:id]
  hash_voucher_transaction = params[:voucher_transaction_id]

  transaction = if hash_reservation.present?
                  Reservation.fetch(Reservation.decrypt_id(hash_reservation))
                elsif hash_transaction_voucher.present?
                  VoucherTransaction.find(VoucherTransaction.decrypt_id(hash_transaction_voucher))
                elsif hash_voucher_transaction.present?
                  TicketTransaction.find(TicketTransaction.decrypt_id(hash_voucher_transaction))
                else
                  raise NotImplementedError
                end

  if params[:resultCode] == '00'
    redirect_to transaction.payment_success_url
  elsif params[:resultCode] == '999'
    # example payload
    # error.custom.request_context.ip_address 61.19.16.130
    # error.custom.request_context.params.action cc_response
    # error.custom.request_context.params.amount 8232.00
    # error.custom.request_context.params.controller api/webhooks
    # error.custom.request_context.params.currencyCode 764
    # error.custom.request_context.params.gbpReferenceNo gbp998311217981146
    # error.custom.request_context.params.id wqBk13
    # error.custom.request_context.params.referenceNo 6501522_2812
    # error.custom.request_context.params.resultCode 999
    # error.custom.request_context.params.resultMessage Do Not Honours

    # so it means the payment is not successful
    redirect_to transaction.payment_failed_url
  elsif params[:resultCode] == '58'
    # This error mean Transaction not Permitted to Terminal
    redirect_to transaction.payment_failed_url
  else
    # Do Not Honour
    if params[:resultCode] == '05'
      return redirect_to transaction.payment_failed_url
    end

    reservation = Reservation.find_by(id: Reservation.decrypt_id(hash_reservation))

    if reservation.present?
      BUSINESS_LOGGER.set_business_context({ reservation_id: reservation&.id })

      if reservation.active?
        # cancel the Reservation
        cancel_service = CancelReservationService.new(reservation.id, :user, { require_reason: true })
        cancel_service.cancel_reason = "Payment failed: #{params[:resultMessage]}"
        if cancel_service.execute
          BUSINESS_LOGGER.info('Webhook: Reservation is canceled because the payment failed')
        else
          BUSINESS_LOGGER.error("Webhook: Failed to cancel reservation because #{cancel_service.error_message_simple}")
          APMErrorHandler.report("#{self.class} #{cancel_service.error_message_simple}", {
                                   reservation_id: reservation.id,
                                   params: params.permit!.to_h,
                                 })
        end
      else
        # if reservation status is already "canceled", do nothing
        BUSINESS_LOGGER.info('Webhook: Payment status is unknown and the reservation is already canceled')
      end
    else
      APMErrorHandler.report("#{self.class} #{action_name} reservation not found", {
                               hash_reservation: hash_reservation,
                               params: params.permit!.to_h,
                             })
    end

    redirect_to transaction.payment_failed_url
  end
end

#gb_primepayObject

Omise Promptpay has 2 ID, charge ID and transaction ID

* charge ID is created when creating Promptpay
* transaction ID is received when Promptpay has been paid

GB Primepay only has 1 ID, gbpReferenceNo so charge ID and Transaction ID is same



685
686
687
688
689
690
691
692
# File 'app/controllers/api/webhooks_controller.rb', line 685

def gb_primepay
  if params[:gbpReferenceNo].present? && params[:resultCode] == '00'
    # For GB Primepay, charge id and transaction id is same
    MarkReservationAsPaidWorker.perform_async(params[:gbpReferenceNo], params[:gbpReferenceNo], params[:referenceNo])
    CheckingDuplicateChargeWorker.perform_at((DateTime.now + 1.hour), params[:gbpReferenceNo])
  end
  head :ok
end

#gb_primepay_for_ccObject

example payload

{
  "amount": "910.00",
  "referenceNo": "870776_6419",
  "gbpReferenceNo": "gbp2368111xxxxx",
  "currencyCode": "764", # iso 4217
  "resultCode": "TO", # 00 Approved, another than 00 means invalid
  "cardNo": "416202XXXXXX2234",
  "fee": "0",
  "vat": "0",
  "paymentType": "C",
  "amountPerMonth": "0",
  "totalAmount": "0",
  "thbAmount": "0",
  "detail": "Booking 870776",
  "customerEmail": "user@hungryhub.com",
  "merchantDefined1": "Reservation",
  "headers": {
  }
}


714
715
716
717
718
719
720
721
722
# File 'app/controllers/api/webhooks_controller.rb', line 714

def gb_primepay_for_cc
  if params[:gbpReferenceNo].present? && params[:referenceNo].present? && params[:resultCode] == '00'
    payload = params.require(:webhook).permit!.to_h.deep_transform_keys do |key|
      key.to_s.underscore
    end
    AddCcPaymentToReservationWorker.new.perform(:gb_primepay, payload)
  end
  head :ok
end

#grab_webhookObject



735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
# File 'app/controllers/api/webhooks_controller.rb', line 735

def grab_webhook
  config = {}
  permitted_params = params.permit(:deliveryID, :timestamp, :status, :trackURL, :failedReason, :merchantOrderID,
                                   sender: %i[name address relationship], recipient: %i[name address relationship],
                                   driver: %i[name phone licensePlate photoURL currentLat currentLng])

  order_id = permitted_params[:deliveryID]
  order = Externals::Grab::Order.find_by(order_ref: order_id)
  reservation = order&.driver&.reservation.presence || Reservation.find_by(id: permitted_params[:merchantOrderID])
  if reservation.present?
    config[:webhook_params] = permitted_params.to_h
    DeliveryChannels::MaintainOrderWorker.perform_async(reservation.id, order_id, config)
  end
  head :ok
end

#lalamove_webhookObject



751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
# File 'app/controllers/api/webhooks_controller.rb', line 751

def lalamove_webhook
  config = {}
  permitted_params = params.permit(:apiKey, :timestamp, :signature, :eventId, :eventType,
                                   data: [:updatedAt, { order: %i[orderId market status driverId shareLink
                                                                  previousStatus] }])
  config[:webhook_params] = permitted_params.to_h
  if permitted_params[:eventType].present?
    case permitted_params[:eventType]
    when Driver::LALAMOVE_WALLET_BALANCE_CHANGED
      # skip
    when Driver::LALAMOVE_ORDER_REPLACED
      previous_order_id = params[:data][:prevOrderId]
      order_id = params[:data][:order][:orderId]
      order = Externals::Lalamove::Order.find_by!(order_ref: previous_order_id)
      order.update! order_ref: order_id
      reservation = order&.driver&.reservation
      DeliveryChannels::MaintainOrderWorker.perform_async(reservation.id, order_id, config)
    else
      order_id = params[:data][:order][:orderId]
      order = Externals::Lalamove::Order.find_by!(order_ref: order_id)
      reservation = order&.driver&.reservation
      DeliveryChannels::MaintainOrderWorker.perform_async(reservation.id, order_id, config) if reservation.present?
    end
  end
  head :ok
end

#netcore_callbackObject



778
779
780
# File 'app/controllers/api/webhooks_controller.rb', line 778

def netcore_callback
  head :ok
end

#omiseObject



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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# File 'app/controllers/api/webhooks_controller.rb', line 19

def omise
  case params[:key]
  when 'charge.create', 'charge.complete'
    # {
    #   "livemode": false,
    #   "data": {
    #     "metadata": {},
    #     "livemode": false,
    #     "fee": 14509,
    #     "source": null,
    #     "failure_message": null,
    #     "multi_capture": false,
    #     "branch": null,
    #     "authorize_uri": "https://api.omise.co/payments/paym_test_61wo91wy58ox5haqk3z/authorize?acs=false",
    #     "authorized": true,
    #     "authorized_amount": 15900,
    #     "partially_refundable": true,
    #     "voided": false,
    #     "id": "chrg_test_61wo91wq64mq8ww1u3q",
    #     "net": 381980,
    #     "merchant_advice": null,
    #     "capturable": false,
    #     "fee_vat": 1016,
    #     "failure_code": null,
    #     "ip": "10.244.1.146",
    #     "capture": true,
    #     "refunded_amount": 0,
    #     "paid_at": "2024-11-29T07:50:03Z",
    #     "device": null,
    #     "transaction_fees": {
    #       "fee_flat": "0.0",
    #       "fee_rate": "3.65",
    #       "vat_rate": "7.0"
    #     },
    #     "card": {
    #       "country": "",
    #       "livemode": false,
    #       "city": null,
    #       "security_code_check": true,
    #       "first_digits": null,
    #       "created_at": "2024-11-29T07:49:41Z",
    #       "last_digits": "5862",
    #       "tokenization_method": "[FILTERED]",
    #       "expiration_year": 2025,
    #       "bank": "",
    #       "deleted": false,
    #       "financing": "",
    #       "fingerprint": "kjKcPlt7g3j7001OhemYtNoOe9aTV3guYp2Hfftw5bQ=",
    #       "name": "nesya meong",
    #       "expiration_month": 2,
    #       "location": "/customers/cust_test_61wm2nuyj61hdx4r5cb/cards/card_test_61wo8xcur8lp72q6kql",
    #       "street1": null,
    #       "phone_number": null,
    #       "id": "card_test_61wo8xcur8lp72q6kql",
    #       "street2": null,
    #       "state": null,
    #       "postal_code": null,
    #       "brand": "MasterCard",
    #       "object": "card"
    #     },
    #     "object": "charge",
    #     "status": "successful",
    #     "can_perform_void": true,
    #     "disputable": true,
    #     "acquirer_reference_number": null,
    #     "interest_vat": 0,
    #     "link": null,
    #     "description": "HungryHub-623035",
    #     "created_at": "2024-11-29T07:50:03Z",
    #     "expired_at": null,
    #     "authorized_at": "2024-11-29T07:50:03Z",
    #     "refunds": {
    #       "total": 0,
    #       "data": [],
    #       "offset": 0,
    #       "limit": 20,
    #       "location": "/charges/chrg_test_61wo91wq64mq8ww1u3q/refunds",
    #       "from": "1970-01-01T00:00:00Z",
    #       "to": "2024-11-29T07:50:04Z",
    #       "object": "list",
    #       "order": "chronological"
    #     },
    #     "funding_currency": "THB",
    #     "expires_at": "2024-12-06T07:50:02Z",
    #     "expired": false,
    #     "interest": 0,
    #     "linked_account": null,
    #     "zero_interest_installments": false,
    #     "captured_amount": 15900,
    #     "reversible": false,
    #     "currency": "SGD",
    #     "refundable": true,
    #     "dispute": null,
    #     "approval_code": null,
    #     "amount": 15900,
    #     "return_uri": "https://hh-pegasus-staging.netlify.app/restaurants/frost-and-feathers/payment-success/9Yz6Z",
    #     "reversed_at": null,
    #     "terminal": null,
    #     "authorization_type": null,
    #     "funding_amount": 397505,
    #     "platform_fee": {
    #       "amount": null,
    #       "percentage": null,
    #       "fixed": null
    #     },
    #     "schedule": null,
    #     "paid": true,
    #     "location": "/charges/chrg_test_61wo91wq64mq8ww1u3q",
    #     "transaction": "trxn_test_61wo922u9bmq72lokno",
    #     "reversed": false,
    #     "customer": "cust_test_61wm2nuyj61hdx4r5cb"
    #   },
    #   "created_at": "2024-11-29T07:50:04Z",
    #   "location": "/events/evnt_test_61wo92470k08ytg9skn",
    #   "id": "evnt_test_61wo92470k08ytg9skn",
    #   "key": "charge.create",
    #   "team_uid": "team_52stxa89q5ncuxmwdci",
    #   "object": "event",
    #   "webhook_deliveries": [],
    #   "user_uid": "acct_51610lktddw6k5wonen"
    # }

    if params[:data][:status] == 'successful' &&
        params[:data][:paid] == true
      # on charge booking
      MarkReservationAsPaidWorker.perform_async(params[:data][:id], params[:data][:transaction])
    elsif params[:data][:status] == 'pending' && params[:data][:paid] == false
      # on hold booking
    elsif params[:data][:status] == 'failed'

      id = params[:data][:id]
      transaction = params[:data][:transaction]

      charge = Externals::Omise::Charge.find_by omise_charge_id: id
      charge = Externals::Omise::Charge.find_by omise_charge_id: transaction if charge.blank?

      if charge.present?
        transaction_record = charge.reservation || charge.ticket_transaction
        update_firebase_for_failed_payment(transaction_record, id) if transaction_record.present?
      else
        # Log when charge is not found
        BUSINESS_LOGGER.warn('Charge not found for failed payment webhook', {
                               omise_charge_id: id,
                               transaction_id: transaction,
                               webhook_data: params[:data].permit!.to_h,
                             })
      end

      # failed to charge

      # {
      #   "object": "event",
      #   "id": "evnt_61x1dkc6gdxcnp10upg",
      #   "livemode": true,
      #   "location": "/events/evnt_61x1dkc6gdxcnp10upg",
      #   "webhook_deliveries": [],
      #   "data": {
      #     "object": "charge",
      #     "id": "chrg_61x1dkaj01glx9igdf7",
      #     "location": "/charges/chrg_61x1dkaj01glx9igdf7",
      #     "amount": 900,
      #     "authorization_type": null,
      #     "authorized_amount": 900,
      #     "captured_amount": 900,
      #     "acquirer_reference_number": null,
      #     "net": 21709,
      #     "fee": 743,
      #     "fee_vat": 52,
      #     "interest": 0,
      #     "interest_vat": 0,
      #     "funding_amount": 22504,
      #     "refunded_amount": 0,
      #     "transaction_fees": {
      #       "fee_flat": "0.0",
      #       "fee_rate": "3.3",
      #       "vat_rate": "7.0"
      #     },
      #     "platform_fee": {
      #       "fixed": null,
      #       "amount": null,
      #       "percentage": null
      #     },
      #     "currency": "SGD",
      #     "funding_currency": "THB",
      #     "ip": "27.124.95.146",
      #     "refunds": {
      #       "object": "list",
      #       "data": [],
      #       "limit": 20,
      #       "offset": 0,
      #       "total": 0,
      #       "location": "/charges/chrg_61x1dkaj01glx9igdf7/refunds",
      #       "order": "chronological",
      #       "from": "1970-01-01T00:00:00Z",
      #       "to": "2024-11-30T06:12:20Z"
      #     },
      #     "link": null,
      #     "description": "HungryHub-6494183",
      #     "metadata": {},
      #     "card": {
      #       "object": "card",
      #       "id": "card_61x1diuty649wx5u90v",
      #       "livemode": true,
      #       "location": "/customers/cust_61x1dk0ujxszukz0t4y/cards/card_61x1diuty649wx5u90v",
      #       "deleted": false,
      #       "street1": null,
      #       "street2": null,
      #       "city": null,
      #       "state": null,
      #       "phone_number": null,
      #       "postal_code": null,
      #       "country": "",
      #       "financing": "",
      #       "bank": "",
      #       "brand": "MasterCard",
      #       "fingerprint": "Cl2mtIbpad0A8zeMpwOIgX2mX0A5yL8/pshwVjcwS0A=",
      #       "first_digits": null,
      #       "last_digits": "5862",
      #       "name": "nesya meong",
      #       "expiration_month": 2,
      #       "expiration_year": 2025,
      #       "security_code_check": true,
      #       "tokenization_method": "******",
      #       "created_at": "2024-11-30T06:12:13Z"
      #     },
      #     "source": null,
      #     "schedule": null,
      #     "linked_account": null,
      #     "customer": "cust_61x1dk0ujxszukz0t4y",
      #     "dispute": null,
      #     "transaction": null,
      #     "failure_code": "payment_rejected",
      #     "failure_message": "payment rejected",
      #     "status": "failed",
      #     "authorize_uri": "https://3dsms.omise.co/payments/pay2_61x1dkam0g1hc5bj7l7/authorize",
      #     "return_uri": "https://web.hungryhub.com/restaurants/el-rincon-del-sabor/payment-success/zMkdgz",
      #     "created_at": "2024-11-30T06:12:20Z",
      #     "paid_at": null,
      #     "authorized_at": null,
      #     "expires_at": "2024-12-07T06:12:19Z",
      #     "expired_at": null,
      #     "reversed_at": null,
      #     "multi_capture": false,
      #     "zero_interest_installments": false,
      #     "branch": null,
      #     "terminal": null,
      #     "device": null,
      #     "authorized": false,
      #     "capturable": false,
      #     "capture": true,
      #     "disputable": false,
      #     "livemode": true,
      #     "refundable": false,
      #     "partially_refundable": false,
      #     "reversed": false,
      #     "reversible": false,
      #     "voided": false,
      #     "paid": false,
      #     "expired": false,
      #     "can_perform_void": false,
      #     "approval_code": null
      #   },
      #   "key": "charge.create",
      #   "created_at": "2024-11-30T06:12:20Z",
      #   "team_uid": "team_52stxa89q5ncuxmwdci",
      #   "user_uid": "acct_51610lktddw6k5wonen"
      # }
      # Payment failures are expected business events, not errors
      # Log them for business tracking but don't report to APM
      failure_code = params[:data][:failure_code]
      message = params[:data][:failure_message] || failure_code

      BUSINESS_LOGGER.set_business_context({
                                             omise_charge_id: params[:data][:id],
                                             transaction_id: params[:data][:transaction],
                                             failure_message: params[:data][:failure_message],
                                             failure_code: failure_code,
                                           })

      if Externals::Omise::Charge::EXPECTED_FAILURE_CODES.include?(failure_code)
        BUSINESS_LOGGER.warn('Omise charge failed - expected payment failure', {
                               message: message,
                               failure_code: failure_code,
                               charge_status: params[:data][:status],
                               charge_id: params[:data][:id],
                               amount: params[:data][:amount],
                               currency: params[:data][:currency],
                             })
      else
        BUSINESS_LOGGER.warn('Omise charge failed - unexpected failure', {
                               message: message,
                               failure_code: failure_code,
                               charge_status: params[:data][:status],
                               charge_id: params[:data][:id],
                               amount: params[:data][:amount],
                               currency: params[:data][:currency],
                             })
        APMErrorHandler.report("Omise charge failed: #{message}", data: params[:data].permit!.to_h)
      end
    else
      raise NotImplementedError
    end
  when 'customer.update'
    # {
    #   "livemode": false,
    #   "data": {
    #     "metadata": {},
    #     "deleted": false,
    #     "cards": {
    #       "total": 3,
    #       "data": [
    #         {
    #           "country": "us",
    #           "livemode": false,
    #           "city": null,
    #           "security_code_check": true,
    #           "first_digits": null,
    #           "created_at": "2024-11-29T05:07:56Z",
    #           "last_digits": "4242",
    #           "tokenization_method": "[FILTERED]",
    #           "expiration_year": 2025,
    #           "bank": "JPMORGAN CHASE BANK N.A.",
    #           "deleted": false,
    #           "financing": "credit",
    #           "fingerprint": "Xl2zFgr8Er4CGTJRVp7H0YCjQR/xYnDXmAYXeVH/L0I=",
    #           "name": "test",
    #           "expiration_month": 2,
    #           "location": "/customers/cust_test_61wmo1ubx70o73nwv3j/cards/card_test_61wmnzeix48y0s123g9",
    #           "street1": null,
    #           "phone_number": null,
    #           "id": "card_test_61wmnzeix48y0s123g9",
    #           "street2": null,
    #           "state": null,
    #           "postal_code": null,
    #           "brand": "Visa",
    #           "object": "card"
    #         },
    #         {
    #           "country": "us",
    #           "livemode": false,
    #           "city": null,
    #           "security_code_check": true,
    #           "first_digits": null,
    #           "created_at": "2024-11-29T05:13:45Z",
    #           "last_digits": "4242",
    #           "tokenization_method": "[FILTERED]",
    #           "expiration_year": 2025,
    #           "bank": "JPMORGAN CHASE BANK N.A.",
    #           "deleted": false,
    #           "financing": "credit",
    #           "fingerprint": "Xl2zFgr8Er4CGTJRVp7H0YCjQR/xYnDXmAYXeVH/L0I=",
    #           "name": "test",
    #           "expiration_month": 2,
    #           "location": "/customers/cust_test_61wmo1ubx70o73nwv3j/cards/card_test_61wmq1815wgscwizb5o",
    #           "street1": null,
    #           "phone_number": null,
    #           "id": "card_test_61wmq1815wgscwizb5o",
    #           "street2": null,
    #           "state": null,
    #           "postal_code": null,
    #           "brand": "Visa",
    #           "object": "card"
    #         },
    #         {
    #           "country": "us",
    #           "livemode": false,
    #           "city": null,
    #           "security_code_check": true,
    #           "first_digits": null,
    #           "created_at": "2024-11-29T08:52:40Z",
    #           "last_digits": "4242",
    #           "tokenization_method": "[FILTERED]",
    #           "expiration_year": 2025,
    #           "bank": "JPMORGAN CHASE BANK N.A.",
    #           "deleted": false,
    #           "financing": "credit",
    #           "fingerprint": "Xl2zFgr8Er4CGTJRVp7H0YCjQR/xYnDXmAYXeVH/L0I=",
    #           "name": "test",
    #           "expiration_month": 2,
    #           "location": "/customers/cust_test_61wmo1ubx70o73nwv3j/cards/card_test_61wov3eozmwihidvz7r",
    #           "street1": null,
    #           "phone_number": null,
    #           "id": "card_test_61wov3eozmwihidvz7r",
    #           "street2": null,
    #           "state": null,
    #           "postal_code": null,
    #           "brand": "Visa",
    #           "object": "card"
    #         }
    #       ],
    #       "offset": 0,
    #       "limit": 20,
    #       "location": "/customers/cust_test_61wmo1ubx70o73nwv3j/cards",
    #       "from": "1970-01-01T00:00:00Z",
    #       "to": "2024-11-29T08:53:01Z",
    #       "object": "list",
    #       "order": "chronological"
    #     },
    #     "livemode": false,
    #     "default_card": "card_test_61wmnzeix48y0s123g9",
    #     "description": "188742",
    #     "created_at": "2024-11-29T05:08:07Z",
    #     "location": "/customers/cust_test_61wmo1ubx70o73nwv3j",
    #     "id": "cust_test_61wmo1ubx70o73nwv3j",
    #     "email": "android@gmail.com",
    #     "object": "customer",
    #     "linked_accounts": {
    #       "total": 0,
    #       "data": [],
    #       "offset": 0,
    #       "limit": 20,
    #       "location": "/customers/cust_test_61wmo1ubx70o73nwv3j/linked_accounts",
    #       "from": "1970-01-01T00:00:00Z",
    #       "to": "2024-11-29T08:53:01Z",
    #       "object": "list",
    #       "order": "chronological"
    #     }
    #   },
    #   "created_at": "2024-11-29T08:53:01Z",
    #   "location": "/events/evnt_test_61wov7vxzyxrt8r0kis",
    #   "id": "evnt_test_61wov7vxzyxrt8r0kis",
    #   "key": "customer.update",
    #   "team_uid": "team_52stxa89q5ncuxmwdci",
    #   "object": "event",
    #   "webhook_deliveries": [],
    #   "user_uid": "acct_51610lktddw6k5wonen"
    # }

    # Do nothing
  when 'customer.create'
    # {
    #   "livemode": false,
    #   "data": {
    #     "metadata": {},
    #     "deleted": false,
    #     "cards": {
    #       "total": 1,
    #       "data": [
    #         {
    #           "country": "us",
    #           "livemode": false,
    #           "city": null,
    #           "security_code_check": true,
    #           "first_digits": null,
    #           "created_at": "2024-11-29T08:41:07Z",
    #           "last_digits": "4242",
    #           "tokenization_method": "[FILTERED]",
    #           "expiration_year": 2025,
    #           "bank": "JPMORGAN CHASE BANK N.A.",
    #           "deleted": false,
    #           "financing": "credit",
    #           "fingerprint": "Xl2zFgr8Er4CGTJRVp7H0YCjQR/xYnDXmAYXeVH/L0I=",
    #           "name": "Firman",
    #           "expiration_month": 2,
    #           "location": "/customers/cust_test_61wor92cz5jtcdfix7x/cards/card_test_61wor13zj7bmhd6pvu4",
    #           "street1": null,
    #           "phone_number": null,
    #           "id": "card_test_61wor13zj7bmhd6pvu4",
    #           "street2": null,
    #           "state": null,
    #           "postal_code": null,
    #           "brand": "Visa",
    #           "object": "card"
    #         }
    #       ],
    #       "offset": 0,
    #       "limit": 20,
    #       "location": "/customers/cust_test_61wor92cz5jtcdfix7x/cards",
    #       "from": "1970-01-01T00:00:00Z",
    #       "to": "2024-11-29T08:41:45Z",
    #       "object": "list",
    #       "order": "chronological"
    #     },
    #     "livemode": false,
    #     "default_card": "card_test_61wor13zj7bmhd6pvu4",
    #     "description": "188555",
    #     "created_at": "2024-11-29T08:41:45Z",
    #     "location": "/customers/cust_test_61wor92cz5jtcdfix7x",
    #     "id": "cust_test_61wor92cz5jtcdfix7x",
    #     "email": "fhaya.firman@gmail.com",
    #     "object": "customer",
    #     "linked_accounts": {
    #       "total": 0,
    #       "data": [],
    #       "offset": 0,
    #       "limit": 20,
    #       "location": "/customers/cust_test_61wor92cz5jtcdfix7x/linked_accounts",
    #       "from": "1970-01-01T00:00:00Z",
    #       "to": "2024-11-29T08:41:45Z",
    #       "object": "list",
    #       "order": "chronological"
    #     }
    #   },
    #   "created_at": "2024-11-29T08:41:45Z",
    #   "location": "/events/evnt_test_61wor92v0tsiqbs0rk1",
    #   "id": "evnt_test_61wor92v0tsiqbs0rk1",
    #   "key": "customer.create",
    #   "team_uid": "team_52stxa89q5ncuxmwdci",
    #   "object": "event",
    #   "webhook_deliveries": [],
    #   "user_uid": "acct_51610lktddw6k5wonen"
    # }

    # Do nothing
  when 'refund.create'
    # {
    #   "livemode": false,
    #   "data": {
    #     "approval_code": null,
    #     "amount": 15900,
    #     "metadata": {
    #       "refund_for": "Refund-623035"
    #     },
    #     "acquirer_reference_number": null,
    #     "charge": "chrg_test_61wo91wq64mq8ww1u3q",
    #     "livemode": false,
    #     "capture": null,
    #     "created_at": "2024-11-29T07:53:20Z",
    #     "terminal": null,
    #     "funding_amount": 397505,
    #     "funding_currency": "THB",
    #     "location": "/charges/chrg_test_61wo91wq64mq8ww1u3q/refunds/rfnd_test_61woa7imf3ldnyj1fld",
    #     "voided": true,
    #     "currency": "SGD",
    #     "id": "rfnd_test_61woa7imf3ldnyj1fld",
    #     "transaction": "trxn_test_61woa7j2tjz0c8gxjo3",
    #     "object": "refund",
    #     "status": "closed"
    #   },
    #   "created_at": "2024-11-29T07:53:20Z",
    #   "location": "/events/evnt_test_61woa7jtpnu1i2qx8q2",
    #   "id": "evnt_test_61woa7jtpnu1i2qx8q2",
    #   "key": "refund.create",
    #   "team_uid": "team_52stxa89q5ncuxmwdci",
    #   "object": "event",
    #   "webhook_deliveries": [],
    #   "user_uid": "acct_51610lktddw6k5wonen"
    # }

    # Do nothing
  when 'transfer.create'
    # Do nothing
  else
    raise NotImplementedError
  end
  head :ok
end

#restaurant_recommendationsObject



6
7
8
9
10
11
12
13
14
15
16
17
# File 'app/controllers/api/webhooks_controller.rb', line 6

def restaurant_recommendations
  restaurant_id = params[:profiles][0][:event_properties][:id].to_i
  similar_restaurants = Array.wrap(params.require(:key_values).values).map(&:to_i)

  ::RestaurantSimilarity.generate_data(restaurant_id: restaurant_id, similar_restaurants: similar_restaurants)

  render json: { success: true }
rescue StandardError => e
  APMErrorHandler.report(e)
  Rails.logger.error(e)
  render json: { success: true }
end

#shopee_payObject



724
725
726
727
728
729
730
731
732
733
# File 'app/controllers/api/webhooks_controller.rb', line 724

def shopee_pay
  unless ShopeePayService::ValidateSignature.new(request.headers['X-Airpay-Req-H'], request.body.read).execute
    return render json: { errcode: 1, debug_msg: 'header missmatch' }, status: :unprocessable_entity
  end

  charge_id = "shopeepay_#{params[:reference_id]}"
  MarkReservationAsPaidWorker.perform_async(charge_id, charge_id)

  render json: { errcode: 0, debug_msg: '' }, status: :ok
end

#true_walletObject



567
568
569
570
571
572
573
# File 'app/controllers/api/webhooks_controller.rb', line 567

def true_wallet
  if params[:gbpReferenceNo].present? && params[:resultCode] == '00'
    charge_id = "truewallet_#{params[:referenceNo]}"
    MarkReservationAsPaidWorker.perform_async(charge_id, params[:gbpReferenceNo])
  end
  head :ok
end

#true_wallet_responseObject



575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
# File 'app/controllers/api/webhooks_controller.rb', line 575

def true_wallet_response
  hash = params.require(:id)
  reservation = Reservation.fetch(Reservation.decrypt_id(hash))

  if reservation.charges.success_scope.present?
    # Only allow redirect if the URL is internal to prevent open redirect vulnerabilities
    web_url = reservation.web_url
    if web_url.present? && URI.parse(web_url).host.nil?
      redirect_to "#{web_url}&true_wallet=true"
    else
      # Log and render error if unsafe redirect detected
      APMErrorHandler.report('Blocked possible open redirect in true_wallet_response',
                             context: { web_url: web_url, reservation_id: reservation.id })
      render json: { error: 'Invalid redirect URL' }, status: :unprocessable_entity
    end
  else
    if reservation.use_third_party_reservation?
      cancel_service = CancelReservationService.new(
        reservation.id, :user, { require_reason: true }
      )
      cancel_service.cancel_reason = 'Payment failed'
      unless cancel_service.execute
        APMErrorHandler.report("#{self.class} #{cancel_service.error_message_simple}")
      end
    end

    redirect_to "#{reservation.payment_failed_url}&true_wallet=true"
  end
end