AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

StripeConnectTest.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. 'checked_at' => now(),
  58. ]);
  59. $this->accounts->statuses[$account->account_id] = new MerchantAccountStatus($ready, $ready, $ready);
  60. return $account;
  61. }
  62. public function test_settings_show_that_the_store_cannot_take_orders_until_stripe_is_connected()
  63. {
  64. $this->get(route('stores.settings', $this->store->slug))
  65. ->assertInertia(fn (Assert $page) => $page
  66. ->where('payments.available', true)
  67. ->where('payments.connected', false)
  68. ->where('payments.can_take_payments', false));
  69. }
  70. public function test_connecting_opens_a_stripe_account_and_sends_the_merchant_to_stripes_form()
  71. {
  72. $response = $this->connect();
  73. $response->assertStatus(409);
  74. $this->assertSame('https://connect.stripe.test/setup/acct_fake_'.$this->store->id, $response->headers->get('X-Inertia-Location'));
  75. $this->assertSame('acct_fake_'.$this->store->id, $this->store->stripeAccount()->firstOrFail()->account_id);
  76. $this->assertSame(route('stores.payments.return', $this->store->slug), $this->accounts->links[0]['return']);
  77. $this->assertSame(route('stores.payments.resume', $this->store->slug), $this->accounts->links[0]['refresh']);
  78. // Clicking again (such as "Finish setup") uses the same account.
  79. $this->connect()->assertStatus(409);
  80. $this->assertCount(1, $this->accounts->created);
  81. $this->assertCount(2, $this->accounts->links);
  82. $this->assertSame(1, StripeAccount::count());
  83. }
  84. public function test_coming_back_unfinished_says_so()
  85. {
  86. $this->connect();
  87. $this->get(route('stores.payments.return', $this->store->slug))
  88. ->assertRedirect(route('stores.settings', $this->store->slug))
  89. ->assertInertiaFlash('toast.type', 'error');
  90. $this->get(route('stores.settings', $this->store->slug))
  91. ->assertInertia(fn (Assert $page) => $page
  92. ->where('payments.connected', true)
  93. ->where('payments.details_submitted', false)
  94. ->where('payments.can_take_payments', false));
  95. $this->assertSame([], $this->accounts->fpxRequested);
  96. }
  97. public function test_coming_back_finished_saves_the_account_and_asks_for_fpx_once()
  98. {
  99. $this->connect();
  100. $this->accounts->approve('acct_fake_'.$this->store->id);
  101. $this->get(route('stores.payments.return', $this->store->slug))
  102. ->assertRedirect(route('stores.settings', $this->store->slug))
  103. ->assertInertiaFlash('toast.type', 'success');
  104. $account = $this->store->stripeAccount()->firstOrFail();
  105. $this->assertTrue($account->charges_enabled);
  106. $this->assertTrue($account->payouts_enabled);
  107. $this->assertTrue($account->fpx_requested);
  108. $this->get(route('stores.payments.return', $this->store->slug));
  109. $this->assertCount(1, $this->accounts->fpxRequested);
  110. $this->get(route('stores.settings', $this->store->slug))
  111. ->assertInertia(fn (Assert $page) => $page
  112. ->where('payments.can_take_payments', true)
  113. ->where('payments.payouts_enabled', true));
  114. }
  115. public function test_an_expired_stripe_link_is_replaced_with_a_fresh_one()
  116. {
  117. $this->connectedAccount(ready: false);
  118. $this->get(route('stores.payments.resume', $this->store->slug))
  119. ->assertRedirect('https://connect.stripe.test/setup/acct_fake_'.$this->store->id);
  120. }
  121. public function test_stripe_being_down_shows_a_message_instead_of_an_error_page()
  122. {
  123. $this->accounts->down = true;
  124. $this->connect()
  125. ->assertRedirect(route('stores.settings', $this->store->slug))
  126. ->assertInertiaFlash('toast.type', 'error');
  127. $this->assertNull($this->store->stripeAccount()->first());
  128. }
  129. public function test_without_the_apps_stripe_key_connecting_is_not_offered()
  130. {
  131. config(['services.stripe.secret' => '']);
  132. $this->get(route('stores.settings', $this->store->slug))
  133. ->assertInertia(fn (Assert $page) => $page->where('payments.available', false));
  134. $this->connect()->assertRedirect(route('stores.settings', $this->store->slug));
  135. $this->assertSame([], $this->accounts->created);
  136. }
  137. public function test_another_merchants_store_cannot_be_connected()
  138. {
  139. $other = Store::factory()->create();
  140. $this->post(route('stores.payments.connect', $other->slug))->assertNotFound();
  141. $this->get(route('stores.payments.return', $other->slug))->assertNotFound();
  142. $this->get(route('stores.payments.resume', $other->slug))->assertNotFound();
  143. }
  144. public function test_a_store_takes_payments_only_once_stripe_approves_and_stripe_is_asked_at_most_once_a_minute()
  145. {
  146. $connect = app(StripeConnect::class);
  147. $this->assertFalse($connect->canTakePayments($this->store));
  148. $this->connectedAccount(ready: false);
  149. $this->store->refresh();
  150. // Checked just now, so Stripe is not asked again yet.
  151. $this->assertFalse($connect->canTakePayments($this->store));
  152. $this->assertSame(0, $this->accounts->statusCalls);
  153. $this->accounts->approve('acct_fake_'.$this->store->id);
  154. $this->travel(2)->minutes();
  155. $this->assertTrue($connect->canTakePayments($this->store->refresh()));
  156. $this->assertSame(1, $this->accounts->statusCalls);
  157. // A fully set up store is not asked about again.
  158. $this->travel(2)->minutes();
  159. $this->assertTrue($connect->canTakePayments($this->store->refresh()));
  160. $this->assertSame(1, $this->accounts->statusCalls);
  161. }
  162. public function test_the_real_gateway_will_not_open_a_payment_page_for_a_store_without_stripe()
  163. {
  164. $order = Order::factory()->for($this->store)->create();
  165. $this->assertFalse(app(StripeGateway::class)->canTakePayments($this->store));
  166. $this->expectException(PaymentException::class);
  167. app(StripeGateway::class)->startCheckout($order, 'https://shop.test/ok', 'https://shop.test/cart');
  168. }
  169. public function test_shoppers_cannot_check_out_until_the_store_can_take_payments()
  170. {
  171. $gateway = new FakeGateway;
  172. $gateway->takingPayments = false;
  173. $this->app->instance(PaymentGateway::class, $gateway);
  174. $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
  175. $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
  176. $this->get(route('stores.preview.checkout', $this->store->slug))
  177. ->assertInertia(fn (Assert $page) => $page->where('view.takingOrders', false));
  178. $this->post(route('stores.preview.checkout.store', $this->store->slug), [
  179. 'name' => 'Aminah binti Ali',
  180. 'email' => 'aminah@example.com',
  181. 'phone' => '012-345 6789',
  182. 'line1' => '12 Jalan Mawar',
  183. 'city' => 'Shah Alam',
  184. 'postcode' => '40000',
  185. 'state' => 'Selangor',
  186. ])->assertSessionHasErrors(['cart' => 'This store is not taking orders yet. Please check back soon.']);
  187. $this->assertSame(0, Order::count());
  188. $this->assertSame([], $gateway->started);
  189. }
  190. public function test_an_order_remembers_the_merchant_account_and_the_merchants_webhook_marks_it_paid()
  191. {
  192. $gateway = new FakeGateway;
  193. $this->app->instance(PaymentGateway::class, $gateway);
  194. $product = Product::factory()->for($this->store)->create(['price' => 1290, 'stock' => 10]);
  195. $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
  196. $this->post(route('stores.preview.checkout.store', $this->store->slug), [
  197. 'name' => 'Aminah binti Ali',
  198. 'email' => 'aminah@example.com',
  199. 'phone' => '012-345 6789',
  200. 'line1' => '12 Jalan Mawar',
  201. 'city' => 'Shah Alam',
  202. 'postcode' => '40000',
  203. 'state' => 'Selangor',
  204. ]);
  205. $order = Order::firstOrFail();
  206. $account = 'acct_fake_'.$this->store->id;
  207. $this->assertSame($account, $order->payment_account);
  208. $gateway->pay($order);
  209. auth()->logout();
  210. $this->postJson(route('stripe.connect-webhook'), ['checkout_id' => $order->payment_checkout_id, 'account' => $account], ['Stripe-Signature' => 'forged'])
  211. ->assertStatus(400);
  212. // A payment in some other merchant's account never marks this order.
  213. $this->postJson(route('stripe.connect-webhook'), ['checkout_id' => $order->payment_checkout_id, 'account' => 'acct_someone_else'], ['Stripe-Signature' => 'valid-connect'])
  214. ->assertOk();
  215. $this->assertFalse($order->fresh()->isPaid());
  216. $this->postJson(route('stripe.connect-webhook'), ['checkout_id' => $order->payment_checkout_id, 'account' => $account], ['Stripe-Signature' => 'valid-connect'])
  217. ->assertOk();
  218. $this->assertTrue($order->fresh()->isPaid());
  219. $this->assertSame(9, $product->fresh()->stock);
  220. Mail::assertSent(OrderConfirmation::class, 1);
  221. }
  222. public function test_the_real_gateway_reads_merchant_messages_with_their_own_secret()
  223. {
  224. config(['services.stripe.webhook_secret' => 'whsec_ours', 'services.stripe.connect_webhook_secret' => 'whsec_merchants']);
  225. $payload = (string) json_encode([
  226. 'id' => 'evt_1',
  227. 'object' => 'event',
  228. 'account' => 'acct_123',
  229. 'type' => 'checkout.session.completed',
  230. 'data' => ['object' => [
  231. 'id' => 'cs_test_123',
  232. 'object' => 'checkout.session',
  233. 'payment_status' => 'paid',
  234. 'payment_intent' => 'pi_123',
  235. 'amount_total' => 2580,
  236. ]],
  237. ]);
  238. $time = time();
  239. $sign = fn (string $secret) => "t=$time,v1=".hash_hmac('sha256', "$time.$payload", $secret);
  240. $status = app(StripeGateway::class)->readWebhook($payload, $sign('whsec_merchants'), fromMerchants: true);
  241. $this->assertSame('cs_test_123', $status->checkoutId);
  242. $this->assertSame('acct_123', $status->account);
  243. $this->assertTrue($status->paid);
  244. $this->expectException(PaymentException::class);
  245. app(StripeGateway::class)->readWebhook($payload, $sign('whsec_ours'), fromMerchants: true);
  246. }
  247. public function test_the_overview_asks_merchants_to_connect_stripe()
  248. {
  249. $this->store->forceFill(['status' => StoreStatus::Published, 'published_plan' => $this->store->plan])->save();
  250. $this->get(route('dashboard'))
  251. ->assertInertia(fn (Assert $page) => $page->where('gettingStarted.steps.payments', false));
  252. $this->connectedAccount();
  253. $this->get(route('dashboard'))
  254. ->assertInertia(fn (Assert $page) => $page->where('gettingStarted.steps.payments', true));
  255. }
  256. public function test_a_live_store_that_cannot_take_payments_needs_attention()
  257. {
  258. $this->store->forceFill(['status' => StoreStatus::Published, 'published_plan' => $this->store->plan])->save();
  259. // A sale already made, so the overview shows its full view with "Needs attention".
  260. Order::factory()->for($this->store)->create(['status' => OrderStatus::Paid, 'paid_at' => now(), 'shipped_at' => now()]);
  261. $this->get(route('dashboard'))
  262. ->assertInertia(fn (Assert $page) => $page
  263. ->where('stats.attention.0.kind', 'payments')
  264. ->where('stats.attention.0.store.slug', $this->store->slug));
  265. $this->connectedAccount();
  266. $this->get(route('dashboard'))
  267. ->assertInertia(fn (Assert $page) => $page->where('stats.attention', fn ($items) => collect($items)->doesntContain('kind', 'payments')));
  268. }
  269. }