您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

CreateConnectedAccount.php 2.6KB

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