npm package: @mybambu/mygalileo-sdk
Description: TypeScript interface for interacting with MyGalileo APIs
Author: MyBambu
Latest version: 1.0.1

# MyGalileo SDK

A comprehensive TypeScript SDK for interacting with MyGalileo APIs, providing type-safe access to all Galileo financial services including accounts, transactions, BNPL, loans, and more.

## Features

- **Type-Safe Client** - Full TypeScript support with automatic type inference
- **Auto Authentication** - Automatic token management across all services
- **All Services** - Unified interface for accounts, transactions, BNPL, loans, risk, and recipes
- **Error Handling** - Typed error responses with detailed messages
- **Tree-Shaking** - Individual service imports for optimal bundle size
- **Timeout Control** - Configurable request timeouts with abort support

## Installation

```bash
npm install @mybambu/mygalileo-sdk
```

## Quick Start

```typescript
import { MyGalileoClient } from '@mybambu/mygalileo-sdk';

// Initialize the client
const client = new MyGalileoClient({
  baseUrl: 'http://localhost:8050',
  timeout: 30000 // optional
});

// Login and authenticate
const { user } = await client.login('user@example.com', 'password123');
console.log(`Logged in as ${user.email}`);

// Use the SDK
const overview = await client.accounts.getAccountOverview('12345678');
console.log(`Balance: $${overview.balance}`);
```

## Authentication

The SDK provides multiple authentication methods with automatic token management.

### Method 1: User Login

```typescript
const { user, access_token } = await client.login(
  'user@example.com',
  'password123'
);
// Token is automatically set for all subsequent requests
```

### Method 2: Access Key Authentication

```typescript
await client.loginWithAccessKey(
  process.env.MYGALILEO_ACCESS_KEY!,
  process.env.MYGALILEO_ACCESS_SECRET!
);
// Token is automatically set for all subsequent requests
```

### Method 3: Manual Token Management

```typescript
const client = new MyGalileoClient({
  baseUrl: 'http://localhost:8050',
  accessToken: 'your-jwt-token' // Set token on initialization
});

// Or set it later
client.setAccessToken('your-jwt-token');

// Clear token
client.clearAccessToken();

// Logout
client.logout();
```

### Register New User

```typescript
const response = await client.auth.register({
  email: 'newuser@example.com',
  username: 'newuser',
  password: 'securePassword123'
});
// Token is returned but not automatically set
client.setAccessToken(response.access_token);
```

### Get User Profile

```typescript
const profile = await client.auth.getProfile();
console.log(profile.email);
```

## Account APIs

Manage Galileo customer accounts including creation, balance inquiries, and limit management.

### Create Account

```typescript
const account = await client.accounts.createAccount({
  firstName: 'John',
  lastName: 'Doe',
  prodId: '2769',
  email: 'john@example.com',
  phoneNumber: '+1234567890',
  loadAmount: 100
});
console.log(`Account created: ${account.accountNo}`);
```

### Get Account Overview

```typescript
const overview = await client.accounts.getAccountOverview('12345678');
console.log(`Balance: $${overview.balance}`);
```

### Get Account Balance

```typescript
const balance = await client.accounts.getAccountBalance('12345678');
console.log(`Available: $${balance.availableBalance}`);
```

### Search Accounts

```typescript
const results = await client.accounts.searchAccounts({
  firstName: 'John',
  status: 'ACTIVE',
  recordCnt: 10
});
console.log(`Found ${results.accounts.length} accounts`);
```

### Update Account Limits

```typescript
await client.accounts.updateAccountLimits('12345678', {
  dailyPurchaseLimit: 5000,
  dailyWithdrawalLimit: 1000,
  singleTransactionLimit: 2000,
  monthlyLimit: 50000
});
```

## Transaction APIs

Process payments, transfers, and manage transaction history for Galileo accounts.

### Create Payment

```typescript
const payment = await client.transactions.createPayment({
  accountNo: '12345678',
  amount: 50.00,
  description: 'Payment for services',
  externalId: 'order-12345'
});
console.log(`Payment ID: ${payment.transactionId}`);
```

### Create Account Transfer

```typescript
const transfer = await client.transactions.createTransfer({
  fromAccountNo: '12345678',
  toAccountNo: '87654321',
  amount: 100.00,
  description: 'Transfer between accounts'
});
console.log(`Transfer complete: ${transfer.transactionId}`);
```

### Get Transaction History

```typescript
const history = await client.transactions.getTransactionHistory('12345678', {
  startDate: '2024-01-01',
  endDate: '2024-12-31',
  recordCount: 50
});
console.log(`Found ${history.transactions.length} transactions`);
```

## BNPL (Buy Now Pay Later) APIs

Manage BNPL plans and purchases with flexible installment options.

### Create BNPL Plan

```typescript
const plan = await client.bnpl.createPlan({
  planName: '4-Month Plan',
  description: 'Pay in 4 monthly installments',
  numberOfInstallments: 4,
  installmentFrequency: 'monthly',
  interestRate: 0,
  minPurchaseAmount: 50,
  maxPurchaseAmount: 5000
});
console.log(`Plan created: ${plan.planId}`);
```

### Create BNPL Purchase

```typescript
const purchase = await client.bnpl.createPurchase({
  accountNo: '12345678',
  planId: 'plan-001',
  amount: 500,
  merchantName: 'Electronics Store',
  description: 'Laptop purchase'
});
console.log(`Purchase ID: ${purchase.purchaseId}`);
```

### Get BNPL Purchase Details

```typescript
const details = await client.bnpl.getPurchaseDetails('purchase-123');
console.log(`Remaining: ${details.remainingInstallments} installments`);
```

## Loan APIs

Comprehensive loan management including simulation, creation, and payment tracking.

### Simulate Loan

```typescript
const simulation = await client.loans.simulateLoan({
  accountNo: '12345678',
  loanAmount: 5000,
  numberOfPayments: 12,
  interestRate: 5.99
});
console.log(`Monthly payment: $${simulation.monthlyPayment}`);
```

### Create Loan

```typescript
const loan = await client.loans.createLoan({
  accountNo: '12345678',
  loanAmount: 5000,
  numberOfPayments: 12,
  interestRate: 5.99,
  firstPaymentDate: '2024-02-01'
});
console.log(`Loan created: ${loan.loanId}`);
```

### Get Loan Status

```typescript
const status = await client.loans.getLoanStatus('loan-123');
console.log(`Remaining balance: $${status.remainingBalance}`);
```

### Create Loan Payment

```typescript
const payment = await client.loans.createPayment('loan-123', {
  accountNo: '12345678',
  amount: 450.00,
  paymentType: 'regular'
});
console.log(`Payment processed: ${payment.paymentId}`);
```

## Risk APIs

Fraud detection and identity verification services powered by Galileo's Payment Risk Platform.

### Check Card Transaction Fraud

```typescript
const fraudCheck = await client.risk.checkCardTransactionFraud({
  riskServiceId: 'risk-service-123',
  accountNo: '12345678',
  pan: '4111111111111111',
  amount: 299.99,
  merchantName: 'Online Store',
  merchantLocation: 'New York, NY'
});
console.log(`Risk level: ${fraudCheck.riskLevel}`);
```

**Response:**
```typescript
{
  riskServiceId: "risk-service-123",
  riskScore: 25,
  riskLevel: "low",
  recommendation: "approve",
  fraudIndicators: [],
  velocityChecks: {
    last24Hours: 3,
    last7Days: 15,
    last30Days: 45
  }
}
```

### Instant Identity Verification

```typescript
const verification = await client.risk.verifyIdentity({
  riskServiceId: 'risk-service-123',
  firstName: 'John',
  lastName: 'Doe',
  dateOfBirth: '1990-01-15',
  ssn4: '1234',
  email: 'john@example.com',
  phone: '+12025551234',
  address: '123 Main St',
  city: 'New York',
  state: 'NY',
  zip: '10001'
});
console.log(`Verification score: ${verification.verificationScore}`);
```

## Recipe APIs

Pre-built workflows that combine multiple API calls to accomplish common tasks in a single request.

### Customer Onboarding

Combines identity verification and account creation with automatic limit setting based on verification score.

```typescript
const result = await client.recipes.customerOnboarding({
  firstName: 'Jane',
  lastName: 'Smith',
  email: 'jane@example.com',
  ssn: '123-45-6789',
  dateOfBirth: '1995-05-15',
  prodId: 'PROD123',
  address: '456 Oak Ave',
  city: 'Seattle',
  state: 'WA',
  zip: '98101'
});
console.log(`Account created: ${result.accountNo}`);
```

**Response:**
```typescript
{
  success: true,
  accountNo: "123456789",
  verificationStatus: "verified",
  verificationScore: 95,
  riskLevel: "low",
  steps: [
    { step: "identity_verification", status: "success" },
    { step: "account_creation", status: "success" },
    { step: "set_limits", status: "success" }
  ]
}
```

### Secure Payment

Performs fraud check before processing payment, automatically declining high-risk transactions.

```typescript
const result = await client.recipes.securePayment({
  riskServiceId: 'risk-service-123',
  accountNo: '12345678',
  amount: 150.00,
  merchantName: 'Coffee Shop',
  merchantLocation: 'Seattle, WA'
});
console.log(`Payment ${result.approved ? 'approved' : 'declined'}`);
```

## Error Handling

The SDK provides comprehensive error handling with typed errors:

```typescript
import { MyGalileoClient } from '@mybambu/mygalileo-sdk';

try {
  const client = new MyGalileoClient({
    baseUrl: 'http://localhost:8050'
  });

  await client.loginWithAccessKey('invalid-key', 'invalid-secret');
  const account = await client.accounts.createAccount({
    firstName: 'John',
    lastName: 'Doe',
    prodId: '2769',
    email: 'john@example.com'
  });
} catch (error) {
  if (error instanceof Error) {
    console.error('Error:', error.message);

    // Handle specific error types
    if (error.message.includes('401')) {
      console.error('Authentication failed');
    } else if (error.message.includes('400')) {
      console.error('Validation error');
    }
  }
}
```

### Common Error Codes

| Code | Description |
|------|-------------|
| `400` | Bad Request - validation error or missing required fields |
| `401` | Unauthorized - invalid or expired access token |
| `404` | Not Found - resource doesn't exist |
| `409` | Conflict - duplicate resource (e.g., account already exists) |
| `500` | Internal Server Error - unexpected server error |

## Best Practices

1. **Secure Token Storage:** Store access tokens securely using encrypted storage or environment variables. Never commit tokens to version control.

2. **Token Refresh:** Implement token refresh logic before expiration (tokens expire after 24 hours).

3. **Error Handling:** Always handle API errors gracefully and provide meaningful feedback to users.

4. **HTTPS Only:** Always use HTTPS in production environments.

5. **Environment Variables:** Store access keys and secrets in environment variables:
   ```typescript
   await client.loginWithAccessKey(
     process.env.MYGALILEO_ACCESS_KEY!,
     process.env.MYGALILEO_ACCESS_SECRET!
   );
   ```

6. **Type Safety:** Leverage TypeScript types for compile-time error detection.

7. **Individual Service Imports:** For smaller bundle sizes, import only what you need:
   ```typescript
   import { AccountService } from '@mybambu/mygalileo-sdk';

   const accountService = new AccountService({
     baseUrl: 'http://localhost:8050',
     accessToken: 'your-token'
   });
   ```

8. **Timeout Configuration:** Configure appropriate timeouts for your use case:
   ```typescript
   const client = new MyGalileoClient({
     baseUrl: 'http://localhost:8050',
     timeout: 60000 // 60 seconds
   });
   ```

## Support

For issues or questions, please contact the MyBambu development team.