| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- <?php
-
- namespace App\Commerce\Payments\HitPay;
-
- use App\Commerce\Checkout;
- use App\Commerce\Payments\CheckoutLink;
- use App\Commerce\Payments\PaymentException;
- use App\Commerce\Payments\PaymentGateway;
- use App\Commerce\Payments\PaymentStatus;
- use App\Models\Order;
- use App\Models\Store;
- use App\Support\MalaysianPhone;
-
- /**
- * DuitNow QR, Touch 'n Go and ShopeePay through the merchant's own HitPay account. HitPay hosts the payment page.
- *
- * The page is made with the merchant's API key, so the money goes straight to them. We take no cut.
- * Messages from HitPay are not trusted: they only tell us to ask HitPay about an order (HitPayWebhookController).
- */
- final class HitPayGateway implements PaymentGateway
- {
- public function __construct(private readonly HitPayApi $api) {}
-
- public function name(): string
- {
- return 'hitpay';
- }
-
- public function canTakePayments(Store $store): bool
- {
- return $this->methods($store) !== [];
- }
-
- public function methods(Store $store): array
- {
- return $store->hitpayAccount?->offeredMethods() ?? [];
- }
-
- public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
- {
- $account = $order->store->hitpayAccount;
-
- if ($account === null || $account->offeredMethods() === []) {
- throw new PaymentException('The store has not connected HitPay.');
- }
-
- $methods = $this->methods($order->store);
- $phone = MalaysianPhone::normalize($order->customer_phone);
- $webhook = rtrim((string) config('app.url'), '/').route('hitpay.webhook', $order->public_id, false);
-
- $fields = [
- 'amount' => number_format($order->total / 100, 2, '.', ''),
- 'currency' => 'MYR',
- 'payment_methods' => $methods,
- 'email' => $order->customer_email,
- 'name' => $order->customer_name,
- // HitPay wants the country code with a plus, such as +60123456789.
- ...($phone !== null ? ['phone' => '+'.$phone] : []),
- 'purpose' => mb_substr($order->store->name.' order #'.$order->number, 0, 255),
- 'reference_number' => (string) $order->number,
- 'redirect_url' => $successUrl,
- 'allow_repeated_payments' => 'false',
- // The shopper is told this deadline on the order page and in the reminder email.
- 'expires_after' => Checkout::PAY_WITHIN_HOURS.' hours',
- // The store sends its own email once the order is paid.
- 'send_email' => 'false',
- // HitPay only calls public https addresses, so a development machine relies on the shopper coming back.
- ...(str_starts_with($webhook, 'https://') ? ['webhook' => $webhook] : []),
- ];
-
- try {
- $request = $this->api->createPaymentRequest($account->api_key, $fields);
-
- // Methods refused earlier were accepted this time: the merchant switched them on in HitPay.
- if ($account->refused_methods !== null && array_diff($account->refused_methods, $methods) === []) {
- $account->clearRefused();
- $account->save();
- }
- } catch (HitPayRefusedMethods $e) {
- // Some ticked methods are switched off in the merchant's HitPay account. Remember them, so the
- // merchant is told in Settings and shoppers are not offered them for a while, then try once more
- // with the methods that are left.
- $account->refused($e->methods);
- report($e);
- $left = array_values(array_diff($methods, $e->methods));
-
- if ($left === []) {
- throw $e;
- }
-
- $request = $this->api->createPaymentRequest($account->api_key, [...$fields, 'payment_methods' => $left]);
- }
-
- return new CheckoutLink($request['id'], $request['url']);
- }
-
- public function checkPayment(Order $order): PaymentStatus
- {
- $account = $order->store->hitpayAccount;
-
- if ($order->payment_checkout_id === null || $account === null) {
- throw new PaymentException('The order has no HitPay payment page, or the store disconnected HitPay.');
- }
-
- $request = $this->api->paymentRequest($account->api_key, $order->payment_checkout_id);
- $payments = is_array($request['payments'] ?? null) ? $request['payments'] : [];
- $payment = collect($payments)->first(fn ($payment) => is_array($payment) && ($payment['status'] ?? null) === 'succeeded');
- $inRinggit = strtolower((string) ($request['currency'] ?? '')) === 'myr';
-
- return new PaymentStatus(
- checkoutId: (string) ($request['id'] ?? $order->payment_checkout_id),
- paid: $inRinggit && ($payment !== null || ($request['status'] ?? null) === 'completed'),
- reference: is_string($payment['id'] ?? null) ? $payment['id'] : null,
- amount: self::sen($payment['amount'] ?? $request['amount'] ?? null),
- );
- }
-
- /**
- * Not used: HitPay's messages go to HitPayWebhookController, which asks HitPay directly instead of trusting them.
- */
- public function readWebhook(string $payload, string $signature, bool $fromMerchants = false): ?PaymentStatus
- {
- return null;
- }
-
- /** HitPay sends amounts as text in ringgit, such as "50.00". */
- private static function sen(mixed $amount): ?int
- {
- return is_numeric($amount) ? (int) round(((float) $amount) * 100) : null;
- }
- }
|