# SoftPOS Integration Guide

## Overview

This document explains how to integrate MyPinPad with the CloudLayer SoftPOS API using OAuth2.0 authentication.

## Architecture

```
┌─────────────┐         ┌──────────────┐         ┌──────────────┐
│   Mobile    │────────▶│   MyPinPad   │────────▶│  CloudLayer  │
│   Device    │         │ Middleware   │  OAuth  │   SoftPOS    │
│ (Card Tap)  │         │              │  2.0    │     API      │
└─────────────┘         └──────────────┘         └──────────────┘
                                                          │
                                                          ▼
                                                  ┌──────────────┐
                                                  │   Payment    │
                                                  │  Providers   │
                                                  └──────────────┘
```

## Setup Instructions

### 1. Enable SoftPOS App

Set environment variable before compilation:

```bash
export INCLUDE_SOFT_POS=true
```

### 2. Install Dependencies

```bash
mix deps.get
```

### 3. Run Database Migrations

```bash
mix ecto.migrate
```

### 4. Create Development Client (Optional)

For development/testing, seed a default client:

```bash
mix run priv/repo/seeds_soft_pos.exs
```

This creates:
- Client ID: `softpos_dev_client`
- Client Secret: `dev_secret_123`

### 5. Create Production Client

For production, generate a secure client:

```bash
mix soft_pos.gen.client "MyPinPad Production" "transaction:write"
```

Save the generated credentials securely - the secret won't be shown again!

### 6. Start the Application

```bash
# Development
mix phx.server

# Production
MIX_ENV=prod mix phx.server
```

The SoftPOS API will be available on port 4066 (configurable).

## API Endpoints

### Base URL

- **Development**: `http://localhost:4066`
- **Production**: `https://your-domain.com` (configure SOFT_POS_HOST)

### 1. OAuth Token Endpoint

**Get Access Token (Client Credentials)**

```http
POST /api/soft-pos/oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials
&client_id=softpos_xxx
&client_secret=sk_xxx
&scope=transaction:write
```

**Response:**

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_expires_in": 2592000,
  "scope": "transaction:write"
}
```

**Refresh Token**

```http
POST /api/soft-pos/oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token
&refresh_token=eyJhbGc...
&client_id=softpos_xxx
&client_secret=sk_xxx
```

### 2. Transaction Processing Endpoint

**Process Transaction**

```http
POST /api/soft-pos/transactions
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "transactionType": "purchase",
  "instanceRequest": {
    "id": "uuid",
    "instanceId": "string",
    "merchantId": "string",
    "organizationId": "string",
    "retrievalReferenceNumber": "string",
    "emvRequestPayload": "base64_string",
    "pin": {
      "payload": "encrypted_data",
      "type": "DUKPT",
      "encryptedPek": "...",
      "encryptedPekType": "RSA",
      "ksn": "..."
    },
    "meta": "json_string",
    "gatewayId": "string"
  }
}
```

**Response (Success):**

```json
{
  "id": "uuid",
  "gatewayResponse": {
    "id": "transaction_id",
    "source": "soft_pos_app",
    "status": "approved",
    "actionCode": "00",
    "emvResponsePayload": "base64_response",
    "meta": "..."
  }
}
```

**Note**: HTTP 200 is returned even for declined transactions. Check `gatewayResponse.status` and `actionCode` for transaction result.

### 3. Transaction Status Endpoint

```http
GET /api/soft-pos/transactions/:id
Authorization: Bearer <access_token>
```

## Configuration for MyPinPad

Provide the following information to MyPinPad:

| Parameter | Value |
|-----------|-------|
| **Transaction Endpoint URL** | `https://your-domain.com/api/soft-pos/transactions` |
| **Access Token URL** | `https://your-domain.com/api/soft-pos/oauth/token` |
| **Client ID** | (generated from CLI) |
| **Client Secret** | (generated from CLI) |
| **Scope** | `transaction:write` |
| **Grant Type** | `client_credentials` |
| **Client Authentication** | `client_secret_post` (credentials in request body) |
| **Token Header Prefix** | `Bearer` |

## Management Commands

### List All Clients

```bash
mix soft_pos.list.clients
```

### Revoke a Client

```bash
mix soft_pos.revoke.client <client_id>
```

## Environment Variables

### Development

```bash
export INCLUDE_SOFT_POS=true
export SOFT_POS_JWT_SECRET="dev-jwt-secret-change-in-production-min-32-chars"
```

### Production

```bash
export INCLUDE_SOFT_POS=true
export SOFT_POS_HOST="api.yourdomain.com"
export SOFT_POS_PORT="4066"
export SOFT_POS_SECRET_KEY_BASE="<generate with: mix phx.gen.secret>"
export SOFT_POS_JWT_SECRET="<generate with: mix phx.gen.secret>"
```

## Testing

### Automated Test Script

```bash
chmod +x test_soft_pos_oauth.sh
./test_soft_pos_oauth.sh
```

### Manual Testing with cURL

See `test_soft_pos_oauth.sh` for example cURL commands.

## Security Considerations

1. **HTTPS Required**: Always use HTTPS in production
2. **Secure Secrets**: Store client secrets in secure vault (never in code)
3. **Token Expiry**: Access tokens expire in 1 hour, refresh tokens in 30 days
4. **Token Revocation**: Revoke compromised clients immediately
5. **Rate Limiting**: Consider implementing rate limiting on token endpoint
6. **IP Whitelisting**: Optionally restrict access to MyPinPad IPs

## Troubleshooting

### Token Validation Fails

- Check token expiry
- Verify JWT secret matches across restarts
- Check database for revoked tokens

### Transaction Processing Fails

- Verify access token is valid
- Check transaction payload format
- Review application logs

### Client Authentication Fails

- Verify client_id and client_secret are correct
- Check if client is active (`is_active = true`)
- Ensure client exists in database

## Support

For issues or questions, check:
- Application logs
- Database records in `oauth_clients`, `oauth_tokens`, `soft_pos_transactions`
- [README.md](apps/soft_pos_app/README.md)
