# Account Linking - Integration Examples

Complete code examples for linking ABA bank accounts with QR codes and deeplinks.

> **Important**: 
> - The `returnUrl` parameter MUST be base64 encoded before passing to the SDK.
> - The `returnUrl` domain must be whitelisted in your merchant profile.

## 1. React Component Example

```tsx
import { useState } from 'react';
import { PayWayClient } from 'aba-payway-sdk';

function LinkAccountButton() {
  const [qrImage, setQrImage] = useState<string | null>(null);
  const [deeplink, setDeeplink] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const initiateAccountLink = async (userId: string) => {
    setLoading(true);
    try {
      const client = new PayWayClient();
      const returnUrl = `${window.location.origin}/api/account-linked`;
      const result = await client.createLinkAccount({
        returnParam: userId,
        returnUrl: Buffer.from(returnUrl).toString('base64'),
        returnDeeplink: {
          ios_scheme: 'myapp://account/linked',
          android_scheme: 'myapp://account/linked'
        }
      });

      if (result.status.code === '00') {
        setQrImage(result.qr_image);
        setDeeplink(result.deeplink);
      } else {
        alert(`Error: ${result.status.message}`);
      }
    } catch (error) {
      console.error('Account link failed:', error);
      alert('Failed to initiate account linking');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <button onClick={() => initiateAccountLink('USER-123')} disabled={loading}>
        {loading ? 'Loading...' : 'Link ABA Account'}
      </button>
      
      {qrImage && (
        <div>
          <h3>Scan with ABA Mobile</h3>
          <img src={qrImage} alt="Link Account" style={{ width: 300, height: 300 }} />
          
          <p>Or</p>
          
          <a href={deeplink!} target="_blank" rel="noopener noreferrer">
            <button>Open ABA Mobile App</button>
          </a>
        </div>
      )}
    </div>
  );
}
```

## 2. Express.js Full Integration

```typescript
import express from 'express';
import { PayWayClient } from 'aba-payway-sdk';

const app = express();
const payway = new PayWayClient();

// Initiate account linking
app.post('/api/link-account', async (req, res) => {
  try {
    const { userId } = req.body;

    const returnUrl = `${req.protocol}://${req.get('host')}/api/account-linked`;
    const result = await payway.createLinkAccount({
      returnParam: userId,
      returnUrl: Buffer.from(returnUrl).toString('base64'),
      returnDeeplink: {
        ios_scheme: 'myapp://account/linked',
        android_scheme: 'myapp://account/linked'
      }
    });

    if (result.status.code !== '00') {
      return res.status(400).json({ error: result.status.message });
    }

    res.json({
      deeplink: result.deeplink,
      qrString: result.qr_string,
      qrImage: result.qr_image,
      expiresAt: new Date(result.expire_in * 1000).toISOString()
    });
  } catch (error) {
    console.error('Link account error:', error);
    res.status(500).json({ error: 'Failed to initiate account linking' });
  }
});

// Handle account linked callback
app.post('/api/account-linked', express.json(), async (req, res) => {
  try {
    const {
      return_param,
      account_token,
      account_name,
      account_number,
      status
    } = req.body;

    // Store account information
    await db.linkedAccounts.create({
      userId: return_param,
      token: account_token,
      name: account_name,
      accountNumber: account_number,
      linkedAt: new Date()
    });

    console.log(`Account linked for user ${return_param}`);
    res.json({ success: true });
  } catch (error) {
    console.error('Callback error:', error);
    res.status(500).json({ error: 'Failed to process callback' });
  }
});
```

## 3. React Native Mobile App

```tsx
import { useState } from 'react';
import { View, Button, Image, Linking, Platform } from 'react-native';

function LinkAccountScreen({ userId }: { userId: string }) {
  const [linkData, setLinkData] = useState<any>(null);

  const initiateLink = async () => {
    const response = await fetch('https://api.yourapp.com/link-account', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userId })
    });

    const data = await response.json();
    setLinkData(data);

    // Automatically open ABA Mobile
    if (Platform.OS === 'ios' || Platform.OS === 'android') {
      const canOpen = await Linking.canOpenURL(data.deeplink);
      if (canOpen) {
        await Linking.openURL(data.deeplink);
      }
    }
  };

  return (
    <View>
      <Button title="Link ABA Account" onPress={initiateLink} />
      
      {linkData && (
        <View>
          <Image 
            source={{ uri: linkData.qrImage }}
            style={{ width: 300, height: 300 }}
          />
          <Button 
            title="Open ABA Mobile" 
            onPress={() => Linking.openURL(linkData.deeplink)}
          />
        </View>
      )}
    </View>
  );
}
```

## 4. Fallback with Polling

```typescript
async function linkAccountWithFallback(userId: string) {
  // Step 1: Initiate linking
  const linkRequest = await client.createLinkAccount({
    returnParam: userId,
    returnUrl: Buffer.from('https://yourapp.com/api/account-linked').toString('base64')
  });

  // Display QR code
  displayQRCode(linkRequest.qr_image);

  // Step 2: Wait for webhook with timeout
  const accountDetails = await waitForWebhook(userId,60000); // 60s timeout

  if (!accountDetails) {
    // Step 3: Manual retrieval if webhook fails
    console.log('Webhook timeout, fetching manually...');
    
    const fallbackResult = await client.getLinkedAccountDetail({
      returnParam: userId
    });

    if (fallbackResult.status.code === '00') {
      await saveLinkedAccount({
        userId,
        ctid: fallbackResult.data.ctid,
        pwt: fallbackResult.data.pwt,
        maskAccount: fallbackResult.data.mask_account
      });

      return fallbackResult.data;
    }
  }

  return accountDetails;
}
```

## 5. Polling Implementation

```typescript
// Polling endpoint
app.get('/api/check-account-link/:returnParam', async (req, res) => {
  try {
    const { returnParam } = req.params;

    const result = await payway.getLinkedAccountDetail({ returnParam });

    if (result.status.code === '00') {
      res.json({
        success: true,
        data: {
          ctid: result.data.ctid,
          pwt: result.data.pwt,
          maskAccount: result.data.mask_account
        }
      });
    } else if (result.status.code === '403') {
      res.status(404).json({
        success: false,
        message: 'Account linking not completed yet'
      });
    }
  } catch (error) {
    res.status(500).json({ error: 'Failed to check status' });
  }
});

// React polling component
function AccountLinkStatus({ returnParam }: { returnParam: string }) {
  const [status, setStatus] = useState<'linking' | 'success' | 'error'>('linking');

  useEffect(() => {
    let attempts = 0;
    const maxAttempts = 20;

    const poll = setInterval(async () => {
      attempts++;
      
      const response = await fetch(`/api/check-account-link/${returnParam}`);
      
      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          setStatus('success');
          clearInterval(poll);
        }
      }

      if (attempts >= maxAttempts) {
        setStatus('error');
        clearInterval(poll);
      }
    }, 6000);

    return () => clearInterval(poll);
  }, [returnParam]);

  return <div>{status === 'linking' ? 'Waiting...' : status}</div>;
}
```

## Related Documentation

- Main documentation: [SKILL.md](SKILL.md)
- API reference: [REFERENCE.md](REFERENCE.md)
