Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Bank Id Laravel Package

dimafe6/bank-id

Laravel package for working with BankID: send authentication/sign requests, collect results, and handle statuses. Includes configurable client setup, helpers, and examples for integrating BankID flows into your PHP app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dimafe6/bank-id
    

    Ensure your server meets BankID’s technical requirements.

  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Dimafe6\BankId\BankIdServiceProvider"
    

    Update .env with your BankID credentials (from BankID Developer Portal):

    BANKID_CLIENT_ID=your_client_id
    BANKID_CLIENT_SECRET=your_client_secret
    BANKID_REDIRECT_URI=http://your-app.com/bankid/callback
    
  3. First Use Case: Authentication Flow Trigger the BankID authentication in a controller:

    use Dimafe6\BankId\Facades\BankId;
    
    public function authenticate()
    {
        $authUrl = BankId::authenticate()->getUrl();
        return redirect()->to($authUrl);
    }
    

    Handle the callback in a route:

    Route::get('/bankid/callback', [BankIdController::class, 'callback']);
    

    Process the response in the controller:

    public function callback(Request $request)
    {
        $response = BankId::authenticate()->handleCallback($request);
        if ($response->isSuccessful()) {
            // User is authenticated; proceed with session/DB logic
            $userData = $response->getUserData();
        } else {
            // Handle errors (e.g., redirect to retry or show message)
        }
    }
    
  4. Verify Dependencies

    • Ensure your app uses PHP 7.4+ (BankID SDK compatibility).
    • Check config/bankid.php for additional settings (e.g., timeout, logging).

Implementation Patterns

Common Workflows

1. User Authentication

  • Pattern: Use BankID for passwordless login or MFA.
  • Example:
    // In a login controller
    $auth = BankId::authenticate()
                 ->setScope('authenticate') // Optional: Limit to specific scopes
                 ->getUrl();
    
    return redirect()->to($auth);
    
  • Post-Callback:
    $response = BankId::authenticate()->handleCallback($request);
    if ($response->isAuthenticated()) {
        $user = User::firstOrCreate([
            'email' => $response->getEmail(),
            'name'  => $response->getName(),
        ]);
        auth()->login($user);
    }
    

2. Signing Documents (BankID Signature)

  • Pattern: Use BankID’s signature flow for legally binding actions.
  • Example:
    $signatureUrl = BankId::signature()
                         ->setPersonalNumber('12345678901') // Optional: Pre-fill
                         ->setData(['contract_id' => 123])
                         ->getUrl();
    
    return redirect()->to($signatureUrl);
    
  • Callback Handling:
    $signatureResponse = BankId::signature()->handleCallback($request);
    if ($signatureResponse->isSigned()) {
        $contract = Contract::find($signatureResponse->getData('contract_id'));
        $contract->markAsSigned();
    }
    

3. Identity Verification

  • Pattern: Verify user identity (e.g., for KYC).
  • Example:
    $verification = BankId::verifyIdentity()
                         ->setPersonalNumber('12345678901')
                         ->getUrl();
    
    return redirect()->to($verification);
    
  • Post-Callback:
    $verification = BankId::verifyIdentity()->handleCallback($request);
    if ($verification->isVerified()) {
        $user->update(['verified_at' => now()]);
    }
    

4. Integration with Laravel Sessions

  • Pattern: Store BankID tokens in the session for multi-step flows.
  • Example:
    $request->session()->put('bankid_state', $auth->getState());
    // Later, resume the flow:
    $auth = BankId::authenticate()->setState($request->session()->get('bankid_state'));
    

Advanced Patterns

1. Customizing the BankID UI

  • Override the default BankID iframe/redirect behavior by extending the BankId facade:
    // In a service provider
    $this->app->extend('bankid', function ($bankid) {
        $bankid->setCustomParams(['theme' => 'dark']);
        return $bankid;
    });
    

2. Webhook Handling

  • BankID supports webhooks for async events (e.g., signature completion).
  • Example:
    Route::post('/bankid/webhook', function (Request $request) {
        $event = BankId::webhook()->handle($request);
        if ($event->isSignature()) {
            // Process signature event
        }
    });
    

3. Rate Limiting

  • Throttle BankID requests to avoid hitting API limits:
    use Illuminate\Cache\RateLimiter;
    
    RateLimiter::for('bankid', function ($request) {
        return Limit::perMinute(5)->by($request->user()?->id);
    });
    
    // In controller:
    if (RateLimiter::tooManyAttempts($request, 'bankid')) {
        abort(429, 'Too many BankID requests');
    }
    

Gotchas and Tips

Common Pitfalls

  1. Redirect URI Mismatch

    • Issue: BankID callback fails with invalid_redirect_uri.
    • Fix: Ensure BANKID_REDIRECT_URI in .env exactly matches the URI registered in the BankID Developer Portal.
    • Debug: Check the error field in the callback response for details.
  2. State Parameter Missing

    • Issue: CSRF attacks or lost state in multi-step flows.
    • Fix: Always pass and validate the state parameter:
      $auth = BankId::authenticate()->setState($request->session()->get('bankid_state'));
      
  3. Personal Number Validation

    • Issue: Invalid personalNumber format causes failures.
    • Fix: Validate using BankID’s format (e.g., Swedish: YYYYMMDDXXXX):
      if (!preg_match('/^\d{10,12}$/', $personalNumber)) {
          throw new \InvalidArgumentException('Invalid personal number');
      }
      
  4. Token Expiry

    • Issue: Short-lived tokens (e.g., access_token) expire quickly.
    • Fix: Cache tokens or refresh them proactively:
      $token = BankId::authenticate()->getAccessToken();
      Cache::put('bankid_token', $token, now()->addMinutes(5));
      
  5. Logging and Debugging

    • Issue: Silent failures without logs.
    • Fix: Enable debug mode in config/bankid.php:
      'debug' => env('BANKID_DEBUG', false),
      
    • Tip: Use Laravel’s logging to track BankID responses:
      \Log::debug('BankID Response', $response->toArray());
      

Configuration Quirks

  1. Environment-Specific Settings

    • Use Laravel’s .env to switch between sandbox and production:
      BANKID_ENV=sandbox  # or 'production'
      
    • Override config in config/bankid.php:
      'environment' => env('BANKID_ENV', 'production'),
      
  2. Custom Headers

    • Add headers to BankID requests (e.g., for proxy setups):
      BankId::setHeaders(['X-Forwarded-For' => $request->ip()]);
      
  3. Timeouts

    • Adjust timeout for slow responses:
      'timeout' => 30, // seconds
      

Extension Points

  1. Custom Responses

    • Extend the BankIdResponse class to add domain-specific data:
      namespace App\Services;
      
      use Dimafe6\BankId\Responses\BankIdResponse;
      
      class CustomBankIdResponse extends BankIdResponse
      {
          public function getContractId()
          {
              return $this->data['contract_id'] ?? null;
          }
      }
      
    • Bind it in a service provider:
      $this->app->bind(
          Dimafe6\BankId\Contracts\BankIdResponse::class,
          App\Services\CustomBankIdResponse::class
      );
      
  2. Mocking for Testing

    • Use Laravel’s mocking to test BankID flows:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity