# Mastercard MPGS Configuration Guide

## Overview

This document describes the configuration options for the Mastercard Payment Gateway Services (MPGS) integration in the Mercury Device Middlelayer application.

## Table of Contents

1. [OAuth 1.0a Configuration](#oauth-10a-configuration)
2. [Environment Configuration](#environment-configuration)
3. [Network Configuration](#network-configuration)
4. [Security Configuration](#security-configuration)
5. [Testing Configuration](#testing-configuration)
6. [Production Deployment](#production-deployment)
7. [Troubleshooting](#troubleshooting)

## OAuth 1.0a Configuration

### Consumer Key

The consumer key is a 97-character string provided by Mastercard Developer Portal:

```elixir
config :da_product_app, :mastercard_oauth,
  consumer_key: "your_97_character_consumer_key_from_mastercard_developer_portal"
```

**Environment Variable**: `MASTERCARD_MPGS_CONSUMER_KEY`

### Signing Key

The signing key must be in PKCS#12 format (.p12 file) and should be stored securely:

```elixir
config :da_product_app, :mastercard_oauth,
  signing_key_file: "/secure/path/to/mastercard-signing-key.p12",
  signing_key_password: "your_secure_password"
```

**Environment Variables**:
- `MASTERCARD_MPGS_SIGNING_KEY_FILE`
- `MASTERCARD_MPGS_SIGNING_KEY_PASSWORD`

### OAuth Parameters

The following OAuth parameters are automatically generated:
- `oauth_nonce`: 32-character random string
- `oauth_timestamp`: Unix timestamp
- `oauth_signature_method`: RSA-SHA256
- `oauth_version`: 1.0
- `oauth_body_hash`: SHA-256 hash of request body (Google Body Hash extension)

## Environment Configuration

### Sandbox Environment

For development and testing:

```elixir
config :da_product_app, :upstream_networks,
  mastercard_mpgs_sandbox: %{
    network_type: :gateway,
    priority: 3,
    base_url: "https://test-gateway.mastercard.com",
    api_version: "version/60",
    mpgs_config: %{
      merchant_id: "TEST_MERCHANT_ID",
      endpoints: %{
        session: "/api/rest/{version}/merchant/{merchantId}/session",
        payment: "/api/rest/{version}/merchant/{merchantId}/order/{orderId}/transaction/{transactionId}",
        payment_inquiry: "/api/rest/{version}/merchant/{merchantId}/order/{orderId}"
      }
    },
    auth_config: %{
      consumer_key: "your_consumer_key",
      signing_key_file: "/path/to/signing-key.p12",
      signing_key_password: "your_password"
    }
  }
```

### Production Environment

For production deployment:

```elixir
config :da_product_app, :upstream_networks,
  mastercard_mpgs_production: %{
    network_type: :gateway,
    priority: 1,
    base_url: "https://gateway.mastercard.com",
    api_version: "version/60",
    mpgs_config: %{
      merchant_id: System.get_env("MASTERCARD_MPGS_PRODUCTION_MERCHANT_ID"),
      endpoints: %{
        session: "/api/rest/{version}/merchant/{merchantId}/session",
        payment: "/api/rest/{version}/merchant/{merchantId}/order/{orderId}/transaction/{transactionId}",
        payment_inquiry: "/api/rest/{version}/merchant/{merchantId}/order/{orderId}"
      }
    },
    auth_config: %{
      consumer_key: System.get_env("MASTERCARD_MPGS_CONSUMER_KEY"),
      signing_key_file: System.get_env("MASTERCARD_MPGS_SIGNING_KEY_FILE"),
      signing_key_password: System.get_env("MASTERCARD_MPGS_SIGNING_KEY_PASSWORD")
    }
  }
```

## Network Configuration

### Gateway Network Type

The `:gateway` network type is used for REST API-based payment gateways like MPGS:

```elixir
network_type: :gateway
```

This differs from traditional `:iso8583` networks that use TCP connections.

### Routing Priority

Lower numbers indicate higher priority:

```elixir
priority: 1  # Highest priority
priority: 2  # Medium priority  
priority: 3  # Lower priority
```

### Endpoint Configuration

MPGS endpoints use URL templates with placeholders:

```elixir
endpoints: %{
  session: "/api/rest/{version}/merchant/{merchantId}/session",
  payment: "/api/rest/{version}/merchant/{merchantId}/order/{orderId}/transaction/{transactionId}",
  payment_inquiry: "/api/rest/{version}/merchant/{merchantId}/order/{orderId}"
}
```

Placeholders are automatically replaced:
- `{version}` → API version (e.g., "version/60")
- `{merchantId}` → Merchant ID
- `{orderId}` → Order/transaction ID
- `{transactionId}` → Transaction ID

## Security Configuration

### SSL/TLS Configuration

Always use SSL in production:

```elixir
config :da_product_app, :http_client,
  ssl_verify: :verify_peer,
  ssl_verify_hostname: true,
  ssl_cacerts: :public_key.cacerts_get()
```

### Key Storage

Store signing keys securely:

1. **Development**: Use local filesystem with restricted permissions
2. **Production**: Use secure key management service (AWS KMS, HashiCorp Vault, etc.)

### PCI DSS Compliance

Ensure PCI DSS compliance:
- Never log card data
- Encrypt sensitive data at rest
- Use secure communication channels
- Implement proper access controls

## Testing Configuration

### Test Mode

Enable test mode for unit testing:

```elixir
config :da_product_app, :mastercard_oauth,
  test_mode: true
```

When test mode is enabled:
- Private key loading is mocked
- OAuth signing uses mock signatures
- Network calls can be mocked

### Mock Responses

For testing without actual API calls:

```elixir
config :da_product_app, :mastercard_mpgs,
  mock_responses: true
```

## Production Deployment

### Environment Variables

Set the following environment variables in production:

```bash
# OAuth Configuration
export MASTERCARD_MPGS_CONSUMER_KEY="your_production_consumer_key"
export MASTERCARD_MPGS_SIGNING_KEY_FILE="/secure/path/to/production-key.p12"
export MASTERCARD_MPGS_SIGNING_KEY_PASSWORD="secure_password"

# MPGS Configuration
export MASTERCARD_MPGS_PRODUCTION_MERCHANT_ID="PROD_MERCHANT_ID"
export MASTERCARD_MPGS_PRODUCTION_BASE_URL="https://gateway.mastercard.com"

# Security
export MASTERCARD_MPGS_VALIDATE_SSL="true"
export MASTERCARD_MPGS_SSL_VERIFY_HOSTNAME="true"
```

### Health Checks

Configure health check endpoints:

```elixir
config :da_product_app, :health_checks,
  mastercard_mpgs: %{
    enabled: true,
    timeout: 5000,
    interval: 60000
  }
```

### Monitoring

Enable monitoring and metrics:

```elixir
config :da_product_app, :metrics,
  mastercard_mpgs: %{
    enabled: true,
    track_requests: true,
    track_response_times: true,
    track_errors: true
  }
```

## Troubleshooting

### Common Issues

#### 1. OAuth Signature Errors

**Error**: `Invalid signature`

**Solutions**:
- Verify consumer key is correct (97 characters)
- Check signing key file path and password
- Ensure system time is synchronized
- Verify request URL and method are correct

#### 2. SSL Certificate Issues

**Error**: `SSL certificate verification failed`

**Solutions**:
- Update CA certificates: `mix deps.get`
- Check firewall and proxy settings
- Verify hostname in certificate

#### 3. Merchant ID Issues

**Error**: `Invalid merchant ID`

**Solutions**:
- Verify merchant ID from Mastercard Developer Portal
- Check environment-specific merchant IDs
- Ensure merchant account is active

#### 4. API Version Compatibility

**Error**: `Unsupported API version`

**Solutions**:
- Check current supported API version
- Update API version in configuration
- Review Mastercard MPGS documentation for changes

### Debugging

Enable debug logging:

```elixir
config :logger, level: :debug

config :da_product_app, :mastercard_mpgs,
  log_requests: true,
  log_responses: true
```

### Support

For issues related to:
- **OAuth Authentication**: Check Mastercard Developer Portal documentation
- **API Endpoints**: Review MPGS API documentation
- **Integration Issues**: Check application logs and error messages
- **Production Issues**: Contact Mastercard support with transaction details

## Configuration Validation

The application validates configuration on startup:

1. **OAuth Configuration**: Consumer key format and signing key accessibility
2. **Network Configuration**: Base URL and endpoint templates
3. **Security Configuration**: SSL settings and certificate validation
4. **Merchant Configuration**: Merchant ID format and validity

Configuration errors will prevent application startup with detailed error messages.

## Best Practices

1. **Security**:
   - Rotate signing keys regularly
   - Use environment variables for sensitive data
   - Enable SSL certificate validation
   - Monitor for security vulnerabilities

2. **Performance**:
   - Configure appropriate timeouts
   - Use connection pooling
   - Implement circuit breakers
   - Monitor response times

3. **Reliability**:
   - Implement retry logic with exponential backoff
   - Use health checks
   - Monitor API rate limits
   - Plan for failover scenarios

4. **Monitoring**:
   - Track transaction success rates
   - Monitor API response times
   - Alert on error rate increases
   - Log important events for audit purposes