AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

StripeConnectTest.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. namespace Tests\Feature\Stores;
  3. use App\Commerce\Payments\MerchantAccounts;
  4. use App\Commerce\Payments\MerchantAccountStatus;
  5. use App\Commerce\Payments\PaymentException;
  6. use App\Commerce\Payments\PaymentGateway;
  7. use App\Commerce\Payments\StripeConnect;
  8. use App\Commerce\Payments\StripeGateway;
  9. use App\Enums\OrderStatus;
  10. use App\Enums\StoreStatus;
  11. use App\Mail\OrderConfirmation;
  12. use App\Models\Order;
  13. use App\Models\Product;
  14. use App\Models\Store;
  15. use App\Models\StripeAccount;
  16. use App\Models\User;
  17. use App\StorePlan\SamplePlan;
  18. use Illuminate\Foundation\Testing\RefreshDatabase;
  19. use Illuminate\Support\Facades\Mail;
  20. use Inertia\Testing\AssertableInertia as Assert;
  21. use Tests\Support\FakeGateway;
  22. use Tests\Support\FakeMerchantAccounts;
  23. use Tests\TestCase;
  24. /**
  25. * Merchants get paid into their own Stripe account (Stripe Connect).
  26. */
  27. class StripeConnectTest extends TestCase
  28. {
  29. use RefreshDatabase;
  30. private User $user;
  31. private Store $store;
  32. private FakeMerchantAccounts $accounts;
  33. protected function setUp(): void
  34. {
  35. parent::setUp();
  36. Mail::fake();
  37. config(['services.stripe.secret' => 'sk_test_fake']);
  38. $this->accounts = new FakeMerchantAccounts;
  39. $this->app->instance(MerchantAccounts::class, $this->accounts);
  40. $this->user = User::factory()->create(['email' => 'ali@example.com']);
  41. $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali', 'plan' => null]);
  42. $this->store->plan = SamplePlan::for($this->store);
  43. $this->store->save();
  44. $this->actingAs($this->user);
  45. }
  46. private function connect()
  47. {
  48. return $this->post(route('stores.payments.connect', $this->store->slug), [], ['X-Inertia' => 'true']);
  49. }
  50. private function connectedAccount(bool $ready = true): StripeAccount
  51. {
  52. $account = $this->store->stripeAccount()->create([
  53. 'account_id' => 'acct_fake_'.$this->store->id,
  54. 'charges_enabled' => $ready,
  55. 'payouts_enabled' => $ready,
  56. 'details_submitted' => $ready,
  57. 'fpx_requested' => $ready,
  58. 'grabpay_requested' => $ready,
  59. 'checked_at' => now(),
  60. ]);
  61. $this->accounts->statuses[$account->account_id] = new MerchantAccountStatus($ready, $ready, $ready);
  62. return $account;
  63. }
  64. public function test_settings_show_that_the_store_cannot_take_orders_until_stripe_is_connected()
  65. {
  66. $this->get(route('stores.settings', $this->store->slug))
  67. ->assertInertia(fn (Assert $page) => $page
  68. ->where('payments.available', true)
  69. ->where('payments.connected', false)
  70. ->where('payments.can_take_payments', false));
  71. }
  72. public function test_connecting_opens_a_stripe_account_and_sends_the_merchant_to_stripes_form()
  73. {
  74. $response = $this->connect();
  75. $response->assertStatus(409);
  76. $this->assertSame('https://connect.stripe.test/setup/acct_fake_'.$this->store->id, $response->headers->get('X-Inertia-Location'));
  77. $this->assertSame('acct_fake_'.$this->store->id, $this->store->stripeAccount()->firstOrFail()->account_id);
  78. $this->assertSame(route('stores.payments.return', $this->store->slug), $this->accounts->links[0]['return']);
  79. $this->assertSame(route('stores.payments.resume', $this->store->slug), $this->accounts->links[0]['refresh']);
  80. // Clicking again (such as "Finish setup") uses the same account.
  81. $this->connect()->assertStatus(409);
  82. $this->assertCount(1, $this->accounts->created);
  83. $this->assertCount(2, $this->accounts->links);
  84. $this->assertSame(1, StripeAccount::count());
  85. }
  86. public function test_coming_back_unfinished_says_so()
  87. {
  88. $this->connect();
  89. $this->get(route('stores.payments.return', $this->store->slug))
  90. ->assertRedirect(route('stores.settings', $this->store->slug))
  91. ->assertInertiaFlash('toast.type', 'error');
  92. $this->get(route('stores.settings', $this->store->slug))
  93. ->assertInertia(fn (Assert $page) => $page
  94. ->where('payments.connected', true)
  95. ->where('payments.details_submitted', false)
  96. ->where('payments.can_take_payments', false));
  97. $this->assertSame([], $this->accounts->fpxRequested);
  98. }
  99. public function test_coming_back_finished_saves_the_account_and_asks_for_fpx_and_grabpay_once()
  100. {
  101. $this->connect();
  102. $this->accounts->approve('acct_fake_'.$this->store->id);
  103. $this->get(route('stores.payments.return', $this->store->slug))
  104. ->assertRedirect(route('stores.settings', $this->store->slug))
  105. ->assertInertiaFlash('toast.type', 'success');
  106. $account = $this->store->stripeAccount()->firstOrFail();
  107. $this->assertTrue($account->charges_enabled);
  108. $this->assertTrue($account->payouts_enabled);
  109. $this->assertTrue($account->fpx_requested);
  110. $this->assertTrue($account->grabpay_requested);
  111. $this->get(route('stores.payments.return', $this->store->slug));
  112. $this->assertSame(["{$account->account_id}:fpx", "{$account->account_id}:grabpay"], $this->accounts->methodsRequested);
  113. $this->get(route('stores.settings', $this->store->slug))
  114. ->assertInertia(fn (Assert $page) => $page
  115. ->where('payments.can_take_payments', true)
  116. ->where('payments.payouts_enabled', true));
  117. }
  118. public function test_an_expired_stripe_link_is_replaced_with_a_fresh_one()
  119. {
  120. $this->connectedAccount(ready: false);
  121. $this->get(route('stores.payments.resume', $this->store->slug))
  122. ->assertRedirect('https://connect.stripe.test/setup/acct_fake_'.$this->store->id);
  123. }
  124. public function test_stripe_being_down_shows_a_message_instead_of_an_error_page()
  125. {
  126. $this->accounts->down = true;
  127. $this->connect()
  128. ->assertRedirect(route('stores.settings', $this->store->slug))
  129. ->assertInertiaFlash('toast.type', 'error');
  130. $this->assertNull($this->store->stripeAccount()->first());
  131. }
  132. public function test_without_the_apps_stripe_key_connecting_is_not_offered()
  133. {
  134. config(['services.stripe.secret' => '']);
  135. $this->get(route('stores.settings', $this->store->slug))
  136. ->assertInertia(fn (Assert $page) => $page->where('payments.available', false));
  137. $this->connect()->assertRedirect(route('stores.settings', $this->store->slug));
  138. $this->assertSame([], $this->accounts->created);
  139. }
  140. public function test_another_merchants_store_cannot_be_connected()
  141. {
  142. $other = Store::factory()->create();
  143. $this->post(route('stores.payments.connect', $other->slug))->assertNotFound();
  144. $this->get(route('stores.payments.return', $other->slug))->assertNotFound();
  145. $this->get(route('stores.payments.resume', $other->slug))->assertNotFound();
  146. }
  147. public function test_a_store_takes_payments_only_once_stripe_approves_and_stripe_is_asked_at_most_once_a_minute()
  148. {
  149. $connect = app(StripeConnect::class);
  150. $this->assertFalse($connect->canTakePayments($this->store));
  151. $this->connectedAccount(ready: false);
  152. $this->store->refresh();
  153. // Checked just now, so Stripe is not asked again yet.
  154. $this->assertFalse($connect->canTakePayments($this->store));
  155. $this->assertSame(0, $this->accounts->statusCalls);
  156. $this->accounts->approve('acct_fake_'.$this->store->id);
  157. $this->travel(2)->minutes();
  158. $this->assertTrue($connect->canTakePayments($this->store->refresh()));
  159. $this->assertSame(1, $this->accounts->statusCalls);
  160. // A fully set up store is not asked about again.
  161. $this->travel(2)->minutes();
  162. $this->assertTrue($connect->canTakePayments($this->store->refresh()));
  163. $this->assertSame(1, $this->accounts->statusCalls);
  164. }
  165. public function test_a_store_set_up_before_grabpay_gets_it_switched_on_once()
  166. {
  167. // Connected and paid before GrabPay was added: FPX is on, GrabPay never asked for.
  168. $account = $this->connectedAccount();
  169. $account->forceFill(['grabpay_requested' => false, 'checked_at' => now()->subMinutes(5)])->save();
  170. $connect = app(StripeConnect::class);
  171. $this->assertTrue($connect->canTakePayments($this->store->refresh()));
  172. $this->assertSame(["{$account->account_id}:grabpay"], $this->accounts->methodsRequested);
  173. $this->assertTrue($account->fresh()->grabpay_requested);
  174. // Done: a fully set up store is not asked about again.
  175. $this->travel(2)->minutes();
  176. $this->assertTrue($connect->canTakePayments($this->store->refresh()));
  177. $this->assertSame(1, $this->accounts->statusCalls);
  178. $this->assertCount(1, $this->accounts->methodsRequested);
  179. }
  180. public function test_stripe_being_down_while_switching_on_grabpay_keeps_the_store_open_and_tries_again_later()
  181. {
  182. $account = $this->connectedAccount();
  183. $account->forceFill(['grabpay_requested' => false, 'checked_at' => now()->subMinutes(5)])->save();
  184. $this->accounts->down = true;
  185. $this->assertTrue(app(StripeConnect::class)->canTakePayments($this->store->refresh()));
  186. $this->assertFalse($account->fresh()->grabpay_requested);
  187. }
  188. public function test_the_real_gateway_will_not_open_a_payment_page_for_a_store_without_stripe()
  189. {
  190. $order = Order::factory()->for($this->store)->create();
  191. $this->assertFalse(app(StripeGateway::class)->canTakePayments($this->store));
  192. $this->expectException(PaymentException::class);
  193. app(StripeGateway::class)->startCheckout($order, 'https://shop.test/ok', 'https://shop.test/cart');
  194. }
  195. public function test_shoppers_cannot_check_out_until_the_store_can_take_payments()
  196. {
  197. $gateway = new FakeGateway;
  198. $gateway->takingPayments = false;
  199. $this->app->instance(PaymentGateway::class, $gateway);
  200. $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
  201. $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
  202. $this->get(route('stores.preview.checkout', $this->store->slug))
  203. ->assertInertia(fn (Assert $page) => $page->where('view.takingOrders', false));
  204. $this->post(route('stores.preview.checkout.store', $this->store->slug), [
  205. 'name' => 'Aminah binti Ali',
  206. 'email' => 'aminah@example.com',
  207. 'phone' => '012-345 6789',
  208. 'line1' => '12 Jalan Mawar',
  209. 'city' => 'Shah Alam',
  210. 'postcode' => '40000',
  211. 'state' => 'Selangor',
  212. ])->assertSessionHasErrors(['cart' => 'This store is not taking orders yet. Please check back soon.']);
  213. $this->assertSame(0, Order::count());
  214. $this->assertSame([], $gateway->started);
  215. }
  216. public function test_an_order_remembers_the_merchant_account_and_the_merchants_webhook_marks_it_paid()
  217. {
  218. $gateway = new FakeGateway;
  219. $this->app->instance(PaymentGateway::class, $gateway);
  220. $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
  221. $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
  222. $this->post(route('stores.preview.checkout.store', $this->store->slug), [
  223. 'name' => 'Aminah binti Ali',
  224. 'email' => 'aminah@example.com',
  225. 'phone' => '012-345 6789',
  226. 'line1' => '12 Jalan Mawar',
  227. 'city' => 'Shah Alam',
  228. 'postcode' => '40000',
  229. 'state' => 'Selangor',
  230. ]);
  231. $order = Order::firstOrFail();
  232. $account = 'acct_fake_'.$this->store->id;
  233. $this->assertSame($account, $order->payment_account);
  234. $gateway->pay($order);
  235. auth()->logout();
  236. $this->postJson(route('stripe.connect-webhook'), ['checkout_id' => $order->payment_checkout_id, 'account' => $account], ['Stripe-Signature' => 'forged'])
  237. ->assertStatus(400);
  238. // A payment in some other merchant's account never marks this order.
  239. $this->postJson(route('stripe.connect-webhook'), ['checkout_id' => $order->payment_checkout_id, 'account' => 'acct_someone_else'], ['Stripe-Signature' => 'valid-connect'])
  240. ->assertOk();
  241. $this->assertFalse($order->fresh()->isPaid());
  242. $this->postJson(route('stripe.connect-webhook'), ['checkout_id' => $order->payment_checkout_id, 'account' => $account], ['Stripe-Signature' => 'valid-connect'])
  243. ->assertOk();
  244. $this->assertTrue($order->fresh()->isPaid());
  245. $this->assertSame(9, $product->fresh()->stock);
  246. Mail::assertSent(OrderConfirmation::class, 1);
  247. }
  248. public function test_the_real_gateway_reads_merchant_messages_with_their_own_secret()
  249. {
  250. config(['services.stripe.webhook_secret' => 'whsec_ours', 'services.stripe.connect_webhook_secret' => 'whsec_merchants']);
  251. $payload = (string) json_encode([
  252. 'id' => 'evt_1',
  253. 'object' => 'event',
  254. 'account' => 'acct_123',
  255. 'type' => 'checkout.session.completed',
  256. 'data' => ['object' => [
  257. 'id' => 'cs_test_123',
  258. 'object' => 'checkout.session',
  259. 'payment_status' => 'paid',
  260. 'payment_intent' => 'pi_123',
  261. 'amount_total' => 2580,
  262. ]],
  263. ]);
  264. $time = time();
  265. $sign = fn (string $secret) => "t=$time,v1=".hash_hmac('sha256', "$time.$payload", $secret);
  266. $status = app(StripeGateway::class)->readWebhook($payload, $sign('whsec_merchants'), fromMerchants: true);
  267. $this->assertSame('cs_test_123', $status->checkoutId);
  268. $this->assertSame('acct_123', $status->account);
  269. $this->assertTrue($status->paid);
  270. $this->expectException(PaymentException::class);
  271. app(StripeGateway::class)->readWebhook($payload, $sign('whsec_ours'), fromMerchants: true);
  272. }
  273. public function test_the_overview_asks_merchants_to_connect_stripe()
  274. {
  275. $this->store->forceFill(['status' => StoreStatus::Published, 'published_plan' => $this->store->plan])->save();
  276. $this->get(route('dashboard'))
  277. ->assertInertia(fn (Assert $page) => $page->where('gettingStarted.steps.payments', false));
  278. $this->connectedAccount();
  279. $this->get(route('dashboard'))
  280. ->assertInertia(fn (Assert $page) => $page->where('gettingStarted.steps.payments', true));
  281. }
  282. public function test_a_live_store_that_cannot_take_payments_needs_attention()
  283. {
  284. $this->store->forceFill(['status' => StoreStatus::Published, 'published_plan' => $this->store->plan])->save();
  285. // A sale already made, so the overview shows its full view with "Needs attention".
  286. Order::factory()->for($this->store)->create(['status' => OrderStatus::Paid, 'paid_at' => now(), 'shipped_at' => now()]);
  287. $this->get(route('dashboard'))
  288. ->assertInertia(fn (Assert $page) => $page
  289. ->where('stats.attention.0.kind', 'payments')
  290. ->where('stats.attention.0.store.slug', $this->store->slug));
  291. $this->connectedAccount();
  292. $this->get(route('dashboard'))
  293. ->assertInertia(fn (Assert $page) => $page->where('stats.attention', fn ($items) => collect($items)->doesntContain('kind', 'payments')));
  294. }
  295. }