AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

HitPayTest.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. <?php
  2. namespace Tests\Feature\Stores;
  3. use App\Commerce\Payments\PaymentGateway;
  4. use App\Mail\OrderConfirmation;
  5. use App\Models\HitPayAccount;
  6. use App\Models\Order;
  7. use App\Models\Product;
  8. use App\Models\Store;
  9. use App\Models\User;
  10. use App\StorePlan\SamplePlan;
  11. use Illuminate\Foundation\Testing\RefreshDatabase;
  12. use Illuminate\Http\Client\Request as HttpRequest;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Http;
  15. use Illuminate\Support\Facades\Mail;
  16. use Inertia\Testing\AssertableInertia as Assert;
  17. use Tests\Support\FakeGateway;
  18. use Tests\TestCase;
  19. /**
  20. * DuitNow QR and e-wallets through the merchant's own HitPay account, next to Stripe.
  21. */
  22. class HitPayTest extends TestCase
  23. {
  24. use RefreshDatabase;
  25. private const string API = 'https://api.sandbox.hit-pay.com/v1';
  26. private User $user;
  27. private Store $store;
  28. /** @var array<string, mixed> What the fake HitPay says about the payment page. */
  29. private array $hitpay = [];
  30. private bool $hitpayFaked = false;
  31. /** @var list<string> Methods the fake HitPay says are switched off in the merchant's account. */
  32. private array $switchedOff = [];
  33. protected function setUp(): void
  34. {
  35. parent::setUp();
  36. Mail::fake();
  37. Http::preventStrayRequests();
  38. config(['services.hitpay.sandbox' => true]);
  39. $this->user = User::factory()->create();
  40. $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
  41. $this->store->plan = SamplePlan::for($this->store);
  42. $this->store->save();
  43. $this->actingAs($this->user);
  44. }
  45. private function connectHitPay(array $methods = HitPayAccount::METHODS): HitPayAccount
  46. {
  47. return $this->store->hitpayAccount()->create(['api_key' => 'hp_test_key_123456', 'methods' => $methods]);
  48. }
  49. /**
  50. * HitPay's answers: a new payment page, and that page with whatever payments were made on it.
  51. * Can be called again to change the answers.
  52. *
  53. * @param list<array<string, mixed>> $payments
  54. */
  55. private function fakeHitPay(string $status = 'pending', array $payments = [], string $amount = '50.00', string $currency = 'myr'): void
  56. {
  57. $this->hitpay = ['status' => $status, 'payments' => $payments, 'amount' => $amount, 'currency' => $currency];
  58. if ($this->hitpayFaked) {
  59. return;
  60. }
  61. $this->hitpayFaked = true;
  62. Http::fake(function (HttpRequest $request) {
  63. if ($request->url() === self::API.'/payment-requests') {
  64. // Like HitPay: one error per method that is switched off, by its place in the list.
  65. $errors = [];
  66. foreach (array_values((array) $request['payment_methods']) as $i => $method) {
  67. if (in_array($method, $this->switchedOff, true)) {
  68. $errors["payment_methods.{$i}"] = ["The selected payment method ({$method}) is unavailable for your account or the currency is invalid. Please check the payment method you selected."];
  69. }
  70. }
  71. if ($errors !== []) {
  72. return Http::response(['error_code' => 'validation_error', 'message' => 'The given data was invalid.', 'errors' => $errors], 422);
  73. }
  74. return Http::response([
  75. 'id' => 'hp_req_1',
  76. 'url' => 'https://securecheckout.sandbox.hit-pay.com/payment-request/@kedai-ali/hp_req_1/checkout',
  77. 'status' => 'pending',
  78. 'amount' => $this->hitpay['amount'],
  79. 'currency' => $this->hitpay['currency'],
  80. ]);
  81. }
  82. if ($request->url() === self::API.'/payment-requests/hp_req_1') {
  83. return Http::response(['id' => 'hp_req_1', ...$this->hitpay]);
  84. }
  85. return Http::response(['message' => 'Not found.'], 404);
  86. });
  87. }
  88. /** RM 42 of products and the default RM 8 shipping to Selangor: RM 50. */
  89. private function placeOrder(string $payWith = 'hitpay')
  90. {
  91. $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 4200, 'stock' => 10]);
  92. $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
  93. return $this->post(route('stores.preview.checkout.store', $this->store->slug), [
  94. 'name' => 'Aminah binti Ali',
  95. 'email' => 'aminah@example.com',
  96. 'phone' => '012-345 6789',
  97. 'line1' => '12 Jalan Mawar',
  98. 'city' => 'Shah Alam',
  99. 'postcode' => '40000',
  100. 'state' => 'Selangor',
  101. 'pay_with' => $payWith,
  102. ]);
  103. }
  104. public function test_a_merchant_connects_hitpay_with_a_key_that_hitpay_accepts()
  105. {
  106. // HitPay refuses the first key and accepts the second.
  107. Http::fake([self::API.'/account-status' => Http::sequence()
  108. ->push(['message' => 'Unauthenticated.'], 401)
  109. ->push(['verification' => ['overall_status' => 'verified']])]);
  110. $this->post(route('stores.hitpay.connect', $this->store->slug), ['api_key' => 'wrong_key_123456'])
  111. ->assertSessionHasErrors('api_key');
  112. $this->assertNull($this->store->fresh()->hitpayAccount);
  113. $this->post(route('stores.hitpay.connect', $this->store->slug), ['api_key' => ' hp_test_key_123456 '])
  114. ->assertSessionHasNoErrors()
  115. ->assertRedirect(route('stores.settings', $this->store->slug));
  116. $account = $this->store->fresh()->hitpayAccount;
  117. $this->assertSame('hp_test_key_123456', $account->api_key);
  118. $this->assertSame(['duitnow', 'touch_n_go', 'shopee_pay'], $account->methods);
  119. // Saved encrypted.
  120. $this->assertStringNotContainsString('hp_test_key_123456', (string) DB::table('hitpay_accounts')->value('api_key'));
  121. Http::assertSent(fn (HttpRequest $request) => $request->url() === self::API.'/account-status'
  122. && $request->hasHeader('X-BUSINESS-API-KEY', 'hp_test_key_123456'));
  123. // Settings says it is connected, and never sends the key back to the page.
  124. $this->get(route('stores.settings', $this->store->slug))
  125. ->assertInertia(fn (Assert $page) => $page
  126. ->where('hitpay.connected', true)
  127. ->where('hitpay.methods', ['duitnow', 'touch_n_go', 'shopee_pay'])
  128. ->where('hitpay.sandbox', true))
  129. ->assertDontSee('hp_test_key_123456');
  130. }
  131. public function test_hitpay_being_down_while_connecting_says_so()
  132. {
  133. Http::fake([self::API.'/account-status' => Http::failedConnection()]);
  134. $this->post(route('stores.hitpay.connect', $this->store->slug), ['api_key' => 'hp_test_key_123456'])
  135. ->assertSessionHasErrors(['api_key' => 'HitPay could not be reached. Please try again in a moment.']);
  136. $this->assertNull($this->store->fresh()->hitpayAccount);
  137. }
  138. public function test_the_merchant_chooses_which_hitpay_methods_shoppers_see_and_can_disconnect()
  139. {
  140. $this->connectHitPay();
  141. $this->put(route('stores.hitpay.update', $this->store->slug), ['methods' => ['shopee_pay', 'duitnow', 'duitnow']])
  142. ->assertSessionHasNoErrors();
  143. $this->assertSame(['duitnow', 'shopee_pay'], $this->store->fresh()->hitpayAccount->methods);
  144. $this->put(route('stores.hitpay.update', $this->store->slug), ['methods' => []])->assertSessionHasErrors('methods');
  145. $this->put(route('stores.hitpay.update', $this->store->slug), ['methods' => ['card']])->assertSessionHasErrors('methods.0');
  146. $this->assertSame(['duitnow', 'shopee_pay'], $this->store->fresh()->hitpayAccount->methods);
  147. $this->delete(route('stores.hitpay.disconnect', $this->store->slug))->assertRedirect(route('stores.settings', $this->store->slug));
  148. $this->assertNull($this->store->fresh()->hitpayAccount);
  149. }
  150. public function test_another_merchants_hitpay_cannot_be_changed()
  151. {
  152. $other = Store::factory()->create();
  153. $other->hitpayAccount()->create(['api_key' => 'theirs_123456', 'methods' => HitPayAccount::METHODS]);
  154. $this->post(route('stores.hitpay.connect', $other->slug), ['api_key' => 'hp_test_key_123456'])->assertNotFound();
  155. $this->put(route('stores.hitpay.update', $other->slug), ['methods' => ['duitnow']])->assertNotFound();
  156. $this->delete(route('stores.hitpay.disconnect', $other->slug))->assertNotFound();
  157. $this->assertNotNull($other->fresh()->hitpayAccount);
  158. }
  159. public function test_shoppers_choose_between_stripe_and_hitpay_at_checkout()
  160. {
  161. $this->connectHitPay(['duitnow', 'touch_n_go']);
  162. $this->post(route('stores.preview.cart.add', $this->store->slug), [
  163. 'product_id' => Product::factory()->for($this->store)->create(['price' => 4200])->id,
  164. 'quantity' => 1,
  165. ]);
  166. $this->get(route('stores.preview.checkout', $this->store->slug))
  167. ->assertInertia(fn (Assert $page) => $page
  168. ->where('view.takingOrders', true)
  169. ->where('view.payWays', [
  170. ['key' => 'fake', 'methods' => ['card', 'fpx', 'grabpay']],
  171. ['key' => 'hitpay', 'methods' => ['duitnow', 'touch_n_go']],
  172. ]));
  173. // A store with only HitPay can take orders too.
  174. $stripe = app(PaymentGateway::class);
  175. $this->assertInstanceOf(FakeGateway::class, $stripe);
  176. $stripe->takingPayments = false;
  177. $this->get(route('stores.preview.checkout', $this->store->slug))
  178. ->assertInertia(fn (Assert $page) => $page
  179. ->where('view.takingOrders', true)
  180. ->where('view.payWays', [['key' => 'hitpay', 'methods' => ['duitnow', 'touch_n_go']]]));
  181. }
  182. public function test_paying_with_hitpay_opens_a_hitpay_page_in_the_merchants_account()
  183. {
  184. $this->connectHitPay();
  185. $this->fakeHitPay();
  186. $response = $this->placeOrder();
  187. $order = Order::firstOrFail();
  188. $response->assertRedirect('https://securecheckout.sandbox.hit-pay.com/payment-request/@kedai-ali/hp_req_1/checkout');
  189. $this->assertSame('hitpay', $order->payment_provider);
  190. $this->assertSame('hp_req_1', $order->payment_checkout_id);
  191. $this->assertSame(5000, $order->total);
  192. Http::assertSent(function (HttpRequest $request) use ($order) {
  193. return $request->url() === self::API.'/payment-requests'
  194. && $request->method() === 'POST'
  195. && $request->hasHeader('X-BUSINESS-API-KEY', 'hp_test_key_123456')
  196. && $request['amount'] === '50.00'
  197. && $request['currency'] === 'MYR'
  198. && $request['payment_methods'] === ['duitnow', 'touch_n_go', 'shopee_pay']
  199. && $request['phone'] === '+60123456789'
  200. && $request['reference_number'] === '1001'
  201. && $request['purpose'] === 'Kedai Ali order #1001'
  202. && $request['redirect_url'] === route('stores.preview.order', [$this->store->slug, $order->public_id])
  203. && $request['send_email'] === 'false'
  204. // Expires before the double-check gives up on the order.
  205. && $request['expires_after'] === '23 hours'
  206. // A development machine has no public https address for HitPay to call.
  207. && ! isset($request['webhook']);
  208. });
  209. }
  210. public function test_on_a_public_server_hitpay_is_told_where_to_send_news_about_the_order()
  211. {
  212. config(['app.url' => 'https://shop.example.com']);
  213. $this->connectHitPay();
  214. $this->fakeHitPay();
  215. $this->placeOrder();
  216. $order = Order::firstOrFail();
  217. Http::assertSent(fn (HttpRequest $request) => $request->url() === self::API.'/payment-requests'
  218. && $request['webhook'] === 'https://shop.example.com/hitpay/webhook/'.$order->public_id);
  219. }
  220. public function test_hitpay_being_down_leaves_no_order_behind()
  221. {
  222. $this->connectHitPay();
  223. Http::fake([self::API.'/payment-requests' => Http::response(['message' => 'The selected payment methods is invalid.'], 422)]);
  224. $this->placeOrder()->assertSessionHasErrors('cart');
  225. $this->assertSame(0, Order::count());
  226. }
  227. public function test_a_way_that_is_not_offered_falls_back_to_stripe()
  228. {
  229. // HitPay is not connected, so the choice is ignored.
  230. $this->placeOrder('hitpay')->assertRedirect('https://pay.test/cs_fake_1');
  231. $this->assertSame('fake', Order::firstOrFail()->payment_provider);
  232. }
  233. public function test_the_order_is_paid_once_hitpay_says_so_when_the_shopper_comes_back()
  234. {
  235. $this->connectHitPay();
  236. $this->fakeHitPay();
  237. $this->placeOrder();
  238. $order = Order::firstOrFail();
  239. // Not paid yet.
  240. $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
  241. ->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'pending'));
  242. $this->assertFalse($order->fresh()->isPaid());
  243. $this->fakeHitPay('completed', [['id' => 'hp_pay_9', 'status' => 'succeeded', 'amount' => '50.00', 'payment_type' => 'duitnow']]);
  244. $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
  245. ->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'paid')->where('cart.count', 0));
  246. $order->refresh();
  247. $this->assertTrue($order->isPaid());
  248. $this->assertSame('hp_pay_9', $order->payment_reference);
  249. $this->assertSame(9, Product::firstOrFail()->stock);
  250. Mail::assertSent(OrderConfirmation::class, 1);
  251. }
  252. public function test_a_payment_of_the_wrong_amount_or_currency_does_not_count()
  253. {
  254. $this->connectHitPay();
  255. $this->fakeHitPay();
  256. $this->placeOrder();
  257. $order = Order::firstOrFail();
  258. $this->fakeHitPay('completed', [['id' => 'hp_pay_9', 'status' => 'succeeded', 'amount' => '5.00']], amount: '5.00');
  259. $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
  260. $this->assertFalse($order->fresh()->isPaid());
  261. $this->fakeHitPay('completed', [['id' => 'hp_pay_9', 'status' => 'succeeded', 'amount' => '50.00']], currency: 'sgd');
  262. $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
  263. $this->assertFalse($order->fresh()->isPaid());
  264. Mail::assertNothingSent();
  265. }
  266. public function test_a_message_from_hitpay_is_checked_with_hitpay_before_the_order_counts_as_paid()
  267. {
  268. $this->connectHitPay();
  269. $this->fakeHitPay();
  270. $this->placeOrder();
  271. $order = Order::firstOrFail();
  272. // A message claiming the order was paid, while HitPay itself says it was not.
  273. $this->post(route('hitpay.webhook', $order->public_id), ['status' => 'completed', 'payment_request_id' => 'hp_req_1'])
  274. ->assertOk();
  275. $this->assertFalse($order->fresh()->isPaid());
  276. // The shopper paid and closed the browser: HitPay's message gets the order marked paid.
  277. $this->fakeHitPay('completed', [['id' => 'hp_pay_9', 'status' => 'succeeded', 'amount' => '50.00']]);
  278. $this->post(route('hitpay.webhook', $order->public_id))->assertOk();
  279. $this->post(route('hitpay.webhook', $order->public_id))->assertOk();
  280. $this->assertTrue($order->fresh()->isPaid());
  281. Mail::assertSent(OrderConfirmation::class, 1);
  282. // Unknown orders are ignored.
  283. $this->post(route('hitpay.webhook', 'not-an-order'))->assertOk();
  284. }
  285. public function test_methods_switched_off_in_hitpay_are_left_out_and_the_merchant_is_told()
  286. {
  287. $this->connectHitPay();
  288. $this->fakeHitPay();
  289. $this->switchedOff = ['duitnow', 'touch_n_go'];
  290. // The shopper still gets a payment page, with the method that works.
  291. $this->placeOrder()->assertRedirect('https://securecheckout.sandbox.hit-pay.com/payment-request/@kedai-ali/hp_req_1/checkout');
  292. Http::assertSent(fn (HttpRequest $request) => $request->url() === self::API.'/payment-requests'
  293. && $request['payment_methods'] === ['shopee_pay']);
  294. $account = $this->store->fresh()->hitpayAccount;
  295. $this->assertSame(['duitnow', 'touch_n_go'], $account->refused_methods);
  296. $this->assertNotNull($account->refused_at);
  297. // The next shoppers are only offered what works, and the merchant sees why.
  298. $this->get(route('stores.preview.checkout', $this->store->slug))
  299. ->assertInertia(fn (Assert $page) => $page->where('view.payWays.1', ['key' => 'hitpay', 'methods' => ['shopee_pay']]));
  300. $this->get(route('stores.settings', $this->store->slug))
  301. ->assertInertia(fn (Assert $page) => $page->where('hitpay.refused', ['duitnow', 'touch_n_go'])->whereNot('hitpay.refused_at', null));
  302. // An hour later they are tried again, in case the merchant switched them on in HitPay.
  303. $this->travel(61)->minutes();
  304. $this->switchedOff = [];
  305. $this->get(route('stores.preview.checkout', $this->store->slug))
  306. ->assertInertia(fn (Assert $page) => $page->where('view.payWays.1.methods', ['duitnow', 'touch_n_go', 'shopee_pay']));
  307. // This time HitPay takes them all, so the warning goes away.
  308. $this->placeOrder();
  309. $this->assertNull($this->store->fresh()->hitpayAccount->refused_methods);
  310. }
  311. public function test_saving_the_methods_tries_refused_ones_again_at_once()
  312. {
  313. $this->connectHitPay()->refused(['duitnow']);
  314. $this->put(route('stores.hitpay.update', $this->store->slug), ['methods' => ['duitnow', 'shopee_pay']]);
  315. $account = $this->store->fresh()->hitpayAccount;
  316. $this->assertNull($account->refused_methods);
  317. $this->assertSame(['duitnow', 'shopee_pay'], $account->offeredMethods());
  318. }
  319. public function test_when_hitpay_refuses_every_method_the_shopper_is_told_and_hitpay_is_hidden_for_a_while()
  320. {
  321. $this->connectHitPay(['duitnow']);
  322. $this->fakeHitPay();
  323. $this->switchedOff = ['duitnow'];
  324. $this->placeOrder()->assertSessionHasErrors('cart');
  325. $this->assertSame(0, Order::count());
  326. // Only Stripe is offered until the merchant fixes it (or an hour passes).
  327. $this->get(route('stores.preview.checkout', $this->store->slug))
  328. ->assertInertia(fn (Assert $page) => $page->where('view.payWays', [['key' => 'fake', 'methods' => ['card', 'fpx', 'grabpay']]]));
  329. }
  330. public function test_the_double_check_asks_hitpay_about_hitpay_orders()
  331. {
  332. $this->connectHitPay();
  333. $this->fakeHitPay();
  334. $this->placeOrder();
  335. $order = Order::firstOrFail();
  336. // The shopper paid by DuitNow and closed the phone; no webhook came.
  337. $this->fakeHitPay('completed', [['id' => 'hp_pay_9', 'status' => 'succeeded', 'amount' => '50.00']]);
  338. $this->travel(3)->minutes();
  339. $this->artisan('orders:check-payments')->assertSuccessful();
  340. $this->assertTrue($order->fresh()->isPaid());
  341. $this->assertSame('hp_pay_9', $order->fresh()->payment_reference);
  342. }
  343. }