npm package: @lula-commerce/direct-sdk
Description: Lula Direct SDK for React Native - Embed Lula Direct storefront with secure authentication
Author: Lula Commerce
Latest version: 1.0.0

# Lula Direct SDK for React Native

The official Lula Direct SDK for React Native applications. Embed the Lula Direct storefront into your mobile app with secure JWT authentication and deep linking support.

## Features

- **Easy Integration**: Simple React component to embed Lula storefront
- **Secure Authentication**: Built-in JWT token generation and management
- **Deep Linking**: Navigate directly to specific products or categories
- **Customer Data Prefill**: Pass customer information for seamless checkout
- **Payment Support**: Built-in support for Apple Pay and Google Pay
- **TypeScript**: Full TypeScript support with type definitions
- **Cross-Platform**: Works on iOS and Android

## Installation

```bash
npm install @lula-commerce/direct-sdk
```

### Peer Dependencies

Make sure you have these peer dependencies installed:

```bash
npm install react-native-webview @react-native-async-storage/async-storage expo-jwt
```

Or with yarn:

```bash
yarn add react-native-webview @react-native-async-storage/async-storage expo-jwt
```

## Quick Start

### 1. Initialize the SDK

First, initialize the SDK with your configuration (typically in your App.tsx or root component):

```typescript
import { initLulaSDK } from '@lula-commerce/direct-sdk';

// For production
initLulaSDK(
  {
    baseUrl: 'https://your-company.lulacommerce.com',
    secretKey: process.env.LULA_SECRET_KEY,
    appBundleId: 'com.yourcompany.app',
    jwtExpiry: 1440, // 24 hours in minutes
  },
  true // isProd
);

// For development
initLulaSDK({
  baseUrl: 'https://dev.lulacommerce.com',
  secretKey: 'your-dev-secret-key',
  appBundleId: 'com.yourcompany.app.dev',
});
```

### 2. Use the LulaDirectView Component

```typescript
import { LulaDirectView } from '@lula-commerce/direct-sdk';

function StoreScreen() {
  return (
    <LulaDirectView
      memberId="user123"
      storeId="store456"
      customerInfo={{
        name: 'John Doe',
        email: 'john@example.com',
        phone: '+1234567890',
        age21: true,
      }}
      onOrderComplete={(order) => {
        console.log('Order completed:', order);
      }}
      enableApplePay={true}
      enableGooglePay={true}
    />
  );
}
```

## API Reference

### `initLulaSDK(config, isProd?)`

Initialize the SDK with configuration options.

**Parameters:**
- `config` (Partial<LulaSDKConfig>): SDK configuration object
  - `baseUrl`: Base URL for Lula Direct API
  - `secretKey`: Secret key for JWT signing (keep secure!)
  - `appBundleId`: Your app's bundle ID
  - `jwtExpiry`: JWT expiration time in minutes (default: 1440)
  - `defaultPath`: Default path for deep linking
- `isProd` (boolean, optional): Whether to use production defaults

**Returns:** Complete SDK configuration

### `LulaDirectView` Component

Main component for embedding the Lula storefront.

**Props:**

| Prop | Type | Required | Description |
|------|------|----------|-------------|
| `memberId` | string | Yes | Unique identifier for the customer |
| `storeId` | string | No | Store ID to display |
| `storeUrl` | string | No | Override base URL for this instance |
| `hideNav` | boolean | No | Hide navigation bar (default: true) |
| `customerInfo` | CustomerInfo | No | Pre-fill customer information |
| `deepLinkPath` | string | No | Path for deep linking to specific pages |
| `onMissingData` | function | No | Callback when required customer data is missing |
| `onOrderComplete` | function | No | Callback when order is completed |
| `sdkConfig` | Partial<LulaSDKConfig> | No | Additional SDK configuration |
| `enableApplePay` | boolean | No | Enable Apple Pay (iOS only, default: false) |
| `enableGooglePay` | boolean | No | Enable Google Pay (Android only, default: false) |

### `CustomerInfo` Interface

```typescript
interface CustomerInfo {
  name?: string;
  email?: string;
  phone?: string;
  address?: {
    line1?: string;
    line2?: string;
    city?: string;
    state?: string;
    postalCode?: string;
    country?: string;
  };
  age21?: boolean;
}
```

## Advanced Usage

### Deep Linking

Navigate to specific products, categories, or pages:

```typescript
<LulaDirectView
  memberId="user123"
  storeId="store456"
  deepLinkPath="/products/beer/craft-ipa"
  customerInfo={customerInfo}
/>
```

### Handling Order Completion

```typescript
<LulaDirectView
  memberId="user123"
  onOrderComplete={(order) => {
    // Handle order completion
    console.log('Order ID:', order.orderId);
    console.log('Total:', order.totalAmount);

    // Navigate to order confirmation screen
    navigation.navigate('OrderConfirmation', { order });
  }}
/>
```

### Handling Missing Data

```typescript
<LulaDirectView
  memberId="user123"
  onMissingData={(fields) => {
    // Prompt user to complete missing information
    console.log('Missing fields:', fields);
    navigation.navigate('CompleteProfile', { fields });
  }}
/>
```

### Custom SDK Configuration Per View

```typescript
<LulaDirectView
  memberId="user123"
  sdkConfig={{
    baseUrl: 'https://custom-store.lulacommerce.com',
    jwtExpiry: 60, // 1 hour
  }}
/>
```

## Utility Functions

### `generateLulaJWT(config)`

Generate a JWT token manually (usually not needed as the component handles this):

```typescript
import { generateLulaJWT } from '@lula-commerce/direct-sdk';

const token = await generateLulaJWT({
  memberId: 'user123',
  userName: 'John Doe',
  userEmail: 'john@example.com',
  isAdult: true,
});
```

### `getLulaUrl(path)`

Get the full URL for a specific path:

```typescript
import { getLulaUrl } from '@lula-commerce/direct-sdk';

const url = getLulaUrl('/products/beer');
console.log(url); // https://your-store.lulacommerce.com/products/beer
```

### `clearLulaJWTCache()`

Clear cached JWT tokens:

```typescript
import { clearLulaJWTCache } from '@lula-commerce/direct-sdk';

await clearLulaJWTCache();
```

## Security Best Practices

1. **Never expose your secret key in client code**
   - Use environment variables
   - Consider generating JWTs on your backend server

2. **Use appropriate JWT expiry times**
   - Shorter expiry times are more secure
   - Balance security with user experience

3. **Validate customer data**
   - Sanitize inputs before passing to the SDK
   - Verify age verification for alcohol sales

## Platform Support

- iOS: 11.0+
- Android: API 21+ (Android 5.0)
- React Native: 0.60+

## Troubleshooting

### WebView not loading

Make sure you have:
1. Installed `react-native-webview`
2. Run `pod install` on iOS
3. Rebuilt your app after installing dependencies

### JWT errors

- Verify your secret key is correct
- Check that your app bundle ID matches
- Ensure the SDK is initialized before using components

### TypeScript errors

Make sure you have `@types/react` and `@types/react-native` installed.

## License

MIT

## Support

For issues and questions:
- GitHub Issues: https://github.com/lula-commerce/lula-iframe-sdk/issues
- Documentation: https://docs.lulacommerce.com

## Changelog

See [CHANGELOG.md](./CHANGELOG.md) for version history.