# 3 - Merchant Validation Example

### Frontend Implementation (React)

The following example demonstrates how to validate your merchant from your frontend application:

#### Frontend Request Implementation

```javascript
// Example: ApplePayButton.js - Merchant validation function
const validateMerchant = async () => {
  try {
    console.log("🏪 Validating merchant with backend...");
    
    // Configure your API endpoint
    const baseUrl = process.env.REACT_APP_API_BASE_URL || "";
    const url = baseUrl 
      ? `${baseUrl}/api/applepay/validate-merchant` 
      : "/api/applepay/validate-merchant";
    
    // Send validation request to your backend
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        domainName: "merchant.demo.novattipayments.com",
        displayName: "Demo Merchant",
      }),
      credentials: "include",
    });

    // Handle response
    if (!response.ok) {
      throw new Error(`Merchant validation failed: ${response.status}`);
    }

    const merchantSession = await response.json();
    console.log("✅ Merchant validation successful:", merchantSession);

    // Optional: Add logging for debugging
    addLog({
      id: "MERCHANT_VALIDATION_SUCCESS",
      title: "Merchant Validation Successful",
      method: "POST",
      url: url,
      payload: {
        domainName: "merchant.demo.novattipayments.com",
        displayName: "Demo Merchant",
      },
      response: merchantSession,
    });

    return merchantSession;
    
  } catch (error) {
    console.error("❌ Merchant validation failed:", error);
    
    // Optional: Add error logging
    addLog({
      id: "MERCHANT_VALIDATION_FAILED",
      title: "Merchant Validation Failed",
      method: "POST",
      url: "/api/applepay/validate-merchant",
      payload: {
        domainName: "merchant.demo.novattipayments.com",
        displayName: "Demo Merchant",
      },
      response: { error: error.message },
    });
    
    throw error;
  }
};
```

#### Request Payload Structure

Your frontend should send the following data structure to your backend:

```text
{
  "domainName": "merchant.demo.novattipayments.com",
  "displayName": "Demo Merchant"
}
```

**Important Notes:**

-   Replace `merchant.demo.novattipayments.com` with your actual merchant domain
-   Update `Demo Merchant` with your business display name
-   Ensure your domain is properly configured in your Apple Pay merchant account

#### Expected Response from Your Backend

Your backend should return a merchant session object like this:

```text
{
  "merchantIdentifier": "merchant.demo.novattipayments.com",
  "displayName": "Demo Merchant",
  "domainName": "merchant.demo.novattipayments.com",
  "merchantSessionIdentifier": "merchant_session_123456789",
  "expiresAt": 1640995200000,
  "epochTimestamp": 1640995200,
  "nonce": "nonce_abc123",
  "pspId": "psp_123",
  "retries": 0,
  "signature": "signature_xyz789",
  "operationalAnalyticsIdentifier": "analytics_456"
}
```

### Backend Implementation (AWS Lambda Example)

Your backend needs to communicate with Novatti's validation endpoint. Here's how to structure your requests:

#### Request to Novatti's Validation Endpoint

Send this payload to Novatti's merchant validation API:

```text
{
  "Header": {
    "TransactionType": "ValidateApplePayMerchant",
    "MerchantID": "MERCHANT_12345",
    "UserID": "USER_67890",
    "Version": "2"
  },
  "Merchant": {
    "InitiativeContext": "demoapplepay.novattipayments.com",
    "Initiative": "web",
    "DisplayName": "Demo Merchant",
    "MerchantIdentifier": "merchant.demo.novattipayments.com"
  }
}
```

**Configuration Required:**

-   Replace `MERCHANT_12345` with your actual Novatti merchant ID
-   Replace `USER_67890` with your user ID
-   Update the domain and merchant identifier fields with your values

#### Expected Response from Novatti

Novatti will return a validation response in this format:

```text
{
  "Result": {
    "ResponseCode": "00",
    "ResponseMessage": "Success"
  },
  "Merchant": {
    "MerchantIdentifier": "merchant.demo.novattipayments.com",
    "DisplayName": "Demo Merchant",
    "DomainName": "demoapplepay.novattipayments.com",
    "MerchantSessionIdentifier": "merchant_session_123456789",
    "ExpiresAt": 1640995200000,
    "EpochTimestamp": 1640995200,
    "Nonce": "nonce_abc123",
    "PspId": "psp_123",
    "Retries": 0,
    "Signature": "signature_xyz789",
    "OperationalAnalyticsIdentifier": "analytics_456"
  }
}
```

### Implementation Tips

1.  **Error Handling**: Always implement proper error handling for network failures and validation errors
2.  **Security**: Never expose your merchant credentials in frontend code
3.  **Testing**: Use the demo domains provided during development, then switch to your production domains
4.  **Logging**: Consider adding comprehensive logging for debugging purposes
5.  **Session Management**: Merchant sessions have expiration times - handle them appropriately

### Next Steps

Once you have merchant validation working, you can proceed to implement the payment processing flow. If you need assistance with any part of this implementation, please don't hesitate to reach out to our support team.

* * *

*This implementation guide uses example values. Please replace all demo credentials and domains with your actual production values.*
