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 Bundle Laravel Package

dimafe6/bank-id-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dimafe6/bank-id-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):

    Dimafe6\BankIDBundle\BankIDBundle::class => ['all' => true],
    
  2. Configuration Add minimal config in config/packages/dimafe6_bank_id.yaml (Symfony 4+) or config.yml:

    bank_id:
        wsdl_url: 'https://appapi2.test.bankid.com/rp/v4?wsdl'  # Test environment
        ssl: false
    

    For production, use:

    wsdl_url: 'https://appapi2.bankid.com/rp/v4?wsdl'
    ssl: true
    
  3. First Use Case Trigger authentication in a controller:

    use Dimafe6\BankIDBundle\Service\BankIDService;
    
    class AuthController extends AbstractController
    {
        public function authenticate(BankIDService $bankIdService)
        {
            $auth = $bankIdService->authenticate([
                'personal_number' => '1912121212', // Swedish personal ID
                'callback_url' => $this->generateUrl('bankid_callback'),
            ]);
            return $auth->getRedirectUrl(); // Redirect to BankID
        }
    }
    

Implementation Patterns

Core Workflow

  1. Initiate Authentication Use BankIDService to start the flow:

    $bankIdService->authenticate([
        'personal_number' => '1912121212',
        'callback_url' => route('bankid_callback'),
        'user_agent' => 'MyApp/1.0', // Optional
        'auto_start' => true,       // Auto-start BankID (default: false)
    ]);
    
    • auto_start: false: Returns a BankIDAuth object with a getRedirectUrl() for manual redirection.
    • auto_start: true: Immediately redirects the user (use in Symfony controllers with return $auth->getRedirectUrl()).
  2. Handle Callback Create a route (e.g., bankid_callback) to process the response:

    public function callback(BankIDService $bankIdService, Request $request)
    {
        $response = $bankIdService->processCallback($request);
        if ($response->isAuthenticated()) {
            $cert = $response->getCertificate();
            // Save user data (e.g., $cert->getPersonalNumber())
        }
        return new RedirectResponse('/success');
    }
    
  3. Error Handling Check $response->getErrors() for issues (e.g., invalid personal number, timeout).


Integration Tips

  • Symfony Forms: Bind BankID data to a form for seamless user creation:

    $form = $this->createForm(UserType::class, $user);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $bankIdData = $bankIdService->processCallback($request);
        $user->setBankIdCert($bankIdData->getCertificate());
    }
    
  • Twig Integration Display BankID status in templates:

    {% if app.request.attributes.get('bankid_auth') %}
        <p>Redirecting to BankID...</p>
    {% endif %}
    
  • Environment-Specific Config Use Symfony’s %kernel.environment% to switch WSDL URLs:

    bank_id:
        wsdl_url: '%env(BANKID_WSDL_URL)%'
    

    Set BANKID_WSDL_URL in .env:

    BANKID_WSDL_URL=https://appapi2.test.bankid.com/rp/v4?wsdl
    
  • Logging Enable debug mode in config.yml to log BankID responses:

    bank_id:
        debug: true
    

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle

    • Last release in 2017; may not support Symfony 5+. Test thoroughly.
    • Workaround: Fork the repo and update dependencies (e.g., symfony/http-foundation to ^5.0).
  2. SSL Requirements

    • Production must use ssl: true. Test environments often fail if SSL is enforced.
    • Error: cURL error 60 (SSL certificate problem). Fix by ensuring openssl is enabled in PHP.
  3. Callback Route

    • BankID expects a POST callback with raw body data. Ensure your route handles this:
      # config/routes.yaml
      bankid_callback:
          path: /bankid/callback
          controller: App\Controller\BankIDController::callback
          methods: POST
      
  4. Personal Number Validation

    • BankID rejects malformed Swedish personal numbers (e.g., 191212121 instead of 1912121212).
    • Tip: Validate with a regex:
      if (!preg_match('/^\d{10}$|^\d{12}$/', $personalNumber)) {
          throw new \InvalidArgumentException('Invalid personal number');
      }
      
  5. Session Handling

    • The bundle uses Symfony’s session. Ensure session.storage.handler is configured (e.g., file or redis).
    • Error: SessionNotFoundException. Verify session.start() is called before BankID operations.

Debugging Tips

  1. Enable Debug Mode

    bank_id:
        debug: true
    

    Logs raw BankID responses to var/log/dev.log.

  2. Test with Sandbox Use the test WSDL (appapi2.test.bankid.com) and dummy credentials:

    • Personal number: 1912121212 (valid test ID).
    • Avoid real credentials in test environments.
  3. cURL Debugging Inspect raw HTTP requests with:

    $client = new \GuzzleHttp\Client();
    $response = $client->post($bankIdService->getWsdlUrl(), [
        'body' => $bankIdService->getSoapRequest($data),
        'headers' => ['Content-Type' => 'text/xml'],
        'debug' => true,
    ]);
    file_put_contents('debug.log', $response->getDebugInfo());
    

Extension Points

  1. Custom Certificate Handling Extend BankIDCertificate to add metadata:

    class ExtendedCertificate extends \Dimafe6\BankIDBundle\Model\BankIDCertificate
    {
        public function getFullName()
        {
            return $this->getFirstName() . ' ' . $this->getLastName();
        }
    }
    

    Override the service to use your class:

    bank_id:
        certificate_class: App\Entity\ExtendedCertificate
    
  2. Pre/Post-Auth Hooks Subscribe to events (if the bundle supports them) or wrap the service:

    $bankIdService->authenticate($data);
    // Post-auth logic
    $cert = $bankIdService->processCallback($request);
    $this->logAuthentication($cert);
    
  3. Multi-Tenant Support Store tenant-specific WSDL URLs in a database and dynamically set them:

    $bankIdService->setWsdlUrl($tenant->getBankIdWsdlUrl());
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours