You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CreateConnectedAccount.php 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\PlaidSuccess;
  4. use App\Models\Banking\Institution;
  5. use App\Models\Company;
  6. use App\Services\PlaidService;
  7. use Illuminate\Support\Facades\DB;
  8. class CreateConnectedAccount
  9. {
  10. /**
  11. * Create the event listener.
  12. */
  13. public function __construct(
  14. protected PlaidService $plaidService
  15. ) {
  16. }
  17. /**
  18. * Handle the event.
  19. */
  20. public function handle(PlaidSuccess $event): void
  21. {
  22. DB::transaction(function () use ($event) {
  23. $this->processPlaidSuccess($event);
  24. });
  25. }
  26. public function processPlaidSuccess(PlaidSuccess $event): void
  27. {
  28. $accessToken = $event->accessToken;
  29. $company = $event->company;
  30. $authResponse = $this->plaidService->getAccounts($accessToken);
  31. $institutionResponse = $this->plaidService->getInstitution($authResponse->item->institution_id, $company->profile->country);
  32. $this->processInstitution($authResponse, $institutionResponse, $company, $accessToken);
  33. }
  34. public function processInstitution($authResponse, $institutionResponse, Company $company, $accessToken): void
  35. {
  36. $institution = Institution::updateOrCreate([
  37. 'external_institution_id' => $authResponse->item->institution_id ?? null,
  38. ], [
  39. 'name' => $institutionResponse->institution->name ?? null,
  40. 'logo' => $institutionResponse->institution->logo ?? null,
  41. 'website' => $institutionResponse->institution->url ?? null,
  42. ]);
  43. foreach ($authResponse->accounts as $plaidAccount) {
  44. $this->processConnectedBankAccount($plaidAccount, $company, $institution, $authResponse, $accessToken);
  45. }
  46. }
  47. public function processConnectedBankAccount($plaidAccount, Company $company, Institution $institution, $authResponse, $accessToken): void
  48. {
  49. $identifierHash = md5($institution->external_institution_id . $plaidAccount->name . $plaidAccount->mask);
  50. $company->connectedBankAccounts()->updateOrCreate([
  51. 'identifier' => $identifierHash,
  52. ], [
  53. 'institution_id' => $institution->id,
  54. 'external_account_id' => $plaidAccount->account_id,
  55. 'access_token' => $accessToken,
  56. 'item_id' => $authResponse->item->item_id,
  57. 'currency_code' => $plaidAccount->balances->iso_currency_code ?? 'USD',
  58. 'current_balance' => $plaidAccount->balances->current ?? 0,
  59. 'name' => $plaidAccount->name,
  60. 'mask' => $plaidAccount->mask,
  61. 'type' => $plaidAccount->type,
  62. 'subtype' => $plaidAccount->subtype,
  63. 'import_transactions' => false,
  64. ]);
  65. }
  66. }