Psyter Payment Inquiry Service - Enhanced Documentation

Overview

The Psyter Payment Inquiry Service is a Windows Service that runs background tasks for the Psyter telemedicine platform. It handles critical payment processing operations including payment inquiry, refund processing, notification delivery, and automated cleanup tasks.

Key Responsibilities

  1. Payment Inquiry Processing - Verifies pending payment statuses with payment gateway
  2. Refund Processing - Handles automated refund requests and status updates
  3. Wallet & Package Payments - Processes wallet recharge and package purchase inquiries
  4. FCM Notifications - Sends Firebase Cloud Messaging notifications and appointment reminders
  5. SCHFS Card Expiry Notifications - Notifies users about expiring SCHFS insurance cards
  6. Log File Management - Automated cleanup of old log files

Architecture

Technology Stack

  • Platform: .NET Framework 4.8
  • Language: C#
  • Service Type: Windows Service (WinExe)
  • Database: Microsoft SQL Server
  • Data Access: Microsoft Enterprise Library 3.1
  • JSON: Newtonsoft.Json 13.0.1
  • IDE: Visual Studio 2017

Project Structure

PsyterPaymentInquiry/
├── DAL/                              # Data Access Layer
│   ├── DBConstants.cs                # Database stored procedure constants
│   ├── DBHelper.cs                   # Database helper with mapping utilities
│   ├── PaymentDataAccess.cs          # Payment data access operations
│   └── XmlHelper.cs                  # XML serialization utilities
├── DTO/                              # Data Transfer Objects
│   ├── AppConfigSetting.cs           # Application configuration models
│   ├── FCMNotificationModal.cs       # FCM notification models
│   ├── InquiryPayment.cs             # Payment inquiry request/response models
│   ├── PendingPaymentModal.cs        # Pending payment models
│   └── PsyterAPIAuth.cs              # API authentication models
├── Properties/                       # Assembly information
├── App.config                        # Service configuration (DB, API URLs)
├── PaymentInquiryService.cs          # Main service implementation
├── PaymentInquiryService.Designer.cs # Service designer
├── Program.cs                        # Service entry point
├── ProjectInstaller.cs               # Windows Service installer
└── packages.config                   # NuGet package references

Configuration

App.config Settings

API Endpoints

<appSettings>
  <!-- Psyter Main API -->
  <add key="PsyterAPIBaseURL" value="https://dvx.innotech-sa.com/Psyter/Master/APIs/"/>

  <!-- Scheduling API -->
  <add key="SchedulingAPIBaseURL" value="https://dvx.innotech-sa.com/Scheduling/SchedulingAPI/"/>
</appSettings>

Database Connection

<connectionStrings>
  <add name="PsyterDatabase" 
       connectionString="Data Source=devdb.innotech-sa.com;
                         Initial Catalog=psyter_v1;
                         Persist Security Info=True;
                         User Id=psyter_dev;
                         Password=p$y7erDevUser26;" 
       providerName="System.Data.SqlClient"/>
</connectionStrings>

Timer Intervals

Timer Interval Purpose
Payment Inquiry & Refund 10 minutes (600,000ms) Check pending payments/refunds
FCM Notifications 10 minutes (600,000ms) Send pending notifications/reminders
SCHFS Expiry Check 24 hours (86,400,000ms) Notify about expiring cards
Log File Cleanup 15 days (1,296,000,000ms) Delete logs older than 30 days

Setup & Installation

Prerequisites

  1. .NET Framework 4.8 installed on target server
  2. SQL Server with appropriate database schema
  3. Windows Server with service installation permissions
  4. Network access to:
    - SQL Server database
    - Psyter API endpoints
    - Scheduling API endpoints
    - Payment gateway (Smart Routing)

Installation Steps

Option 1: Using Visual Studio

  1. Build the Solution

    # Open solution in Visual Studio
    # Build > Build Solution (Ctrl+Shift+B)
    

  2. Install the Service

    # Open Developer Command Prompt as Administrator
    cd "D:\Dev\Projects\Psyter\WindowsService\PsyterPaymentInquiry\bin\Release"
    
    # Install the service
    installutil PsyterPaymentInquiry.exe
    

  3. Start the Service

    # Using Services Console (services.msc)
    # Or via command line:
    net start PsyterPaymentInquiry
    

Option 2: Using Advanced Installer

  1. Build the Installer
    - Open Psyter Payment Inquiry Service\Psyter Payment Inquiry Service.aip
    - Build the installer package

  2. Deploy
    - Run the generated MSI/EXE installer on target server
    - Follow installation wizard

Configuration Steps

  1. Update App.config

    <!-- Set production endpoints -->
    <add key="PsyterAPIBaseURL" value="https://webapis.psyter.com/" />
    <add key="SchedulingAPIBaseURL" value="https://scheduling.innotech-sa.com/" />
    
    <!-- Set production database -->
    <add name="PsyterDatabase" 
         connectionString="[Production Connection String]" />
    

  2. Verify Database Stored Procedures
    Ensure these stored procedures exist:
    - ws_GetPendingPaymentsList_AppConfigSetting
    - ws_GetPendingPaymentsListForRefund_AppConfigSetting
    - ws_GetPendingWalletPurchasesList_AppConfigSetting
    - ws_GetPendingPackagePaymentsList_AppConfigSetting
    - ws_UpdatePaymentInquiryStatus
    - ws_UpdatePendingPaymentRefundStatus
    - Notification_GetNotificationsListToSentUsingFCM
    - Notification_UpdateNotificationSentStatus
    - Reminder_UpdateReminderSentStatus

  3. Configure Windows Service

    # Set service to Auto-start
    sc config PsyterPaymentInquiry start= auto
    
    # Set recovery options
    sc failure PsyterPaymentInquiry reset= 86400 actions= restart/60000/restart/60000/restart/60000
    

Operational Guide

Service Lifecycle

OnStart()
  ├── Initialize 4 timers
  ├── Log service start
  ├── Start timer threads:
  │   ├── Payment Inquiry/Refund (10 min)
  │   ├── FCM Notifications (10 min)
  │   ├── SCHFS Expiry Check (24 hrs)
  │   └── Log Cleanup (15 days)
  └── Return

OnElapsedTime()
  ├── CreateThread() for payment processing
  └── Spawn background worker thread

Processing Flow

Payment Inquiry Flow

1. Fetch pending payments from DB
2. Retrieve payment gateway configuration
3. For each pending payment:
   ├── Generate secure hash (SHA256)
   ├── Send inquiry to payment gateway
   ├── Parse response
   ├── Update payment status in DB
   ├── If successful (00000):
   │   └── Update booking status to "Booked" via Scheduling API
   └── If failed after 3 attempts:
       └── Cancel booking (status = 8)

Refund Processing Flow

1. Fetch pending refund requests from DB
2. For each refund:
   ├── Generate refund transaction ID
   ├── Create secure hash with amount
   ├── Submit refund to payment gateway
   ├── Parse response
   ├── Update refund status in DB
   └── If successful:
       └── Send refund notification via Psyter API

FCM Notification Flow

1. Fetch pending notifications/reminders from DB
2. For each reminder:
   ├── Build FCM payload with booking details
   ├── Include user/provider information
   ├── Call Psyter API to send notification
   ├── Mark reminder as sent in DB
   └── Create notification log entry

Logging

Log File Locations

[Service Directory]\Logs\
  ├── ServiceLog_Inquiry_[Date].txt
  ├── ServiceLog_Refund_[Date].txt
  ├── ServiceLog_NotifySCHFSCardExpiry_[Date].txt
  ├── ServiceLog_DeleteFileLog_[Date].txt
  └── ServiceLog_SendFCMNotificationAndReminders_[Date].txt

Log File Retention

  • Retention Period: 30 days
  • Cleanup Frequency: Every 15 days
  • Log Format: Plain text with timestamps

Sample Log Entries

Service is started at 11/10/2025 10:00:00 AM
Service is recall at 11/10/2025 10:10:00 AM
Pending Payments Count : 5
TransactionId =PSY1234567890, OrderId =123
Payment Gateway Response : Response.StatusCode=00000&Response.StatusDescription=Success
Response Description : Success
-----------------------------END--------------------------------

Monitoring

Key Metrics to Monitor

  1. Service Health
    - Service running status
    - Thread states (alive/terminated)
    - Timer execution frequency

  2. Payment Processing
    - Pending payment count
    - Successful inquiry rate
    - Failed payment count
    - Average processing time

  3. Notification Delivery
    - Pending notification count
    - Successful delivery rate
    - Failed notification count

  4. Database Operations
    - Connection failures
    - Query execution time
    - Deadlock occurrences

Health Check Queries

-- Check pending payments
EXEC ws_GetPendingPaymentsList_AppConfigSetting

-- Check pending refunds
EXEC ws_GetPendingPaymentsListForRefund_AppConfigSetting

-- Check pending notifications
EXEC Notification_GetNotificationsListToSentUsingFCM

Troubleshooting Guide

Common Issues

1. Service Won’t Start

Symptoms: Service fails to start or immediately stops

Possible Causes:
- Database connection failure
- Missing stored procedures
- Configuration errors
- Permission issues

Solutions:

# Check Windows Event Log
eventvwr.msc
# Look in: Windows Logs > Application

# Verify database connectivity
sqlcmd -S devdb.innotech-sa.com -U psyter_dev -P [password] -d psyter_v1

# Test service in debug mode
# Uncomment debug code in Program.cs:
# PaymentInquiryService service = new PaymentInquiryService();
# service.GetPendingFCMNotificationsAndReminders();

2. Payment Inquiries Not Processing

Symptoms: Payments remain in “pending” status

Debugging Steps:

  1. Check Logs

    Get-Content ".\Logs\ServiceLog_Inquiry_*.txt" -Tail 50
    

  2. Verify Payment Gateway Connectivity

    // Check SmartRoutingRefundInquiryUrl is accessible
    // Verify SecureHash generation is correct
    

  3. Check Database Configuration

    -- Verify app config settings
    SELECT * FROM AppConfigSettings 
    WHERE TitlePLang IN (
      'SmartRoutingSecretKey',
      'SmartRoutingMerchantId',
      'SmartRoutingRefundInquiryUrl'
    )
    

3. Notifications Not Sending

Symptoms: Reminders/notifications not delivered to users

Debugging Steps:

  1. Check Service Logs

    Get-Content ".\Logs\ServiceLog_SendFCMNotificationAndReminders_*.txt"
    

  2. Verify API Authentication

    # Check if PsyterAPIAuthToken is being generated
    # Look for "Psyter API Call Token Created" in logs
    

  3. Test API Endpoint

    # Test Psyter API is accessible
    Invoke-RestMethod -Uri "https://dvx.innotech-sa.com/Psyter/Master/APIs/Notification/SendNotificationWithCustomData" -Method Post
    

4. Thread Already Running

Symptoms: Log shows “Service thread is already in running state”

Explanation: Previous execution is still running. This is normal if:
- Large number of pending items to process
- Payment gateway is slow to respond
- Database operations are slow

Action: Monitor if thread eventually completes. If stuck for >30 minutes, restart service.

5. Database Connection Errors

Symptoms: Exception logs showing connection failures

Solutions:

# Test connection string
$connString = "Data Source=devdb.innotech-sa.com;Initial Catalog=psyter_v1;User Id=psyter_dev;Password=***"
$conn = New-Object System.Data.SqlClient.SqlConnection($connString)
$conn.Open()
$conn.State  # Should show "Open"
$conn.Close()

# Check firewall rules
Test-NetConnection -ComputerName devdb.innotech-sa.com -Port 1433

# Verify SQL Server authentication
# Ensure mixed mode authentication is enabled

6. API Authentication Failures

Symptoms: 401 Unauthorized errors in logs

Solutions:
1. Verify application token in database
2. Check API endpoint URLs are correct
3. Ensure tokens are being refreshed properly
4. Verify system clock is synchronized (for token expiry)

Error Codes

Payment Gateway Response Codes

Code Description Action
00000 Success Payment confirmed
00019 Transaction not found Continue inquiry attempts
01111 Transaction pending Continue inquiry attempts
Other Various errors Log error and update status

Recovery Procedures

Service Hang Recovery

# Stop service
net stop PsyterPaymentInquiry

# Wait 10 seconds
Start-Sleep -Seconds 10

# Start service
net start PsyterPaymentInquiry

# Monitor logs
Get-Content ".\Logs\ServiceLog_Inquiry_*.txt" -Wait

Database Deadlock Recovery

  • Service will automatically retry on next timer interval
  • No manual intervention required
  • Check logs for recurring deadlocks

Log File Cleanup Issues

# If automatic cleanup fails, manually delete old logs
Get-ChildItem ".\Logs" -Filter "ServiceLog_*.txt" | 
  Where-Object {$_.CreationTime -lt (Get-Date).AddDays(-30)} | 
  Remove-Item -Force

Security Considerations

Sensitive Data

  1. App.config contains:
    - Database credentials (plaintext)
    - API endpoint URLs

Recommendation: Use Windows DPAPI or encrypted configuration sections

  1. Payment Gateway Credentials
    - Stored in database AppConfigSettings table
    - SecureHash using SHA256
    - Merchant ID and secret key

  2. API Tokens
    - Refreshed on each service cycle
    - Not persisted to disk
    - Transmitted over HTTPS

Network Security

  • All API communications use HTTPS
  • Database connections should use encrypted connections
  • Service should run under least-privilege account

Performance Optimization

Current Performance Characteristics

  • Timer Intervals: 10 minutes for most operations
  • Thread Management: Single thread per operation type
  • Batch Processing: Processes all pending items in sequence

Optimization Opportunities

  1. Parallel Processing: Process multiple payments concurrently
  2. Caching: Cache API tokens to reduce authentication calls
  3. Batching: Batch database updates instead of individual calls
  4. Connection Pooling: Ensure proper SQL connection pooling

Dependencies

NuGet Packages

<packages>
  <package id="Microsoft.Practices.EnterpriseLibrary.Common.dll" version="3.1.0" />
  <package id="Microsoft.Practices.EnterpriseLibrary.Data.dll" version="3.1.0" />
  <package id="Microsoft.Practices.ObjectBuilder.dll" version="3.1.0" />
  <package id="Newtonsoft.Json" version="13.0.1" />
</packages>

External Services

  1. Psyter API - Main application API
  2. Scheduling API - Booking management
  3. Payment Gateway - Smart Routing payment processor
  4. SQL Server - Data persistence
  5. FCM - Push notification delivery (called via Psyter API)

Maintenance

Regular Tasks

  1. Weekly: Review service logs for errors
  2. Monthly: Verify service is running and timers executing
  3. Quarterly: Review and optimize database stored procedures
  4. Annually: Update NuGet packages and security patches

Update Procedures

  1. Stop Service

    net stop PsyterPaymentInquiry
    

  2. Backup Current Version

    Copy-Item "C:\Program Files\PsyterPaymentInquiry" "C:\Backups\PsyterPaymentInquiry_$(Get-Date -Format 'yyyyMMdd')" -Recurse
    

  3. Deploy New Version
    - Copy new binaries
    - Update App.config if needed

  4. Start Service

    net start PsyterPaymentInquiry
    

  5. Verify Operation

    Get-Content ".\Logs\ServiceLog_Inquiry_*.txt" -Tail 20
    

Development & Debugging

Debug Mode

To run in debug mode (for development):

  1. Uncomment debug code in Program.cs:

    //For Debugging
    PaymentInquiryService service = new PaymentInquiryService();
    service.GetPendingFCMNotificationsAndReminders();
    System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
    

  2. Run from Visual Studio (F5)

  3. Set breakpoints in service methods

Testing

Unit Test Approach:
- Extract business logic into testable methods
- Mock PaymentDataAccess for database operations
- Mock HTTP calls for API integrations

Integration Test Approach:
- Use test database with sample data
- Run service in debug mode
- Verify database updates and log outputs

Support & Contact

For issues or questions:
- Check logs in Logs\ directory
- Review Windows Event Viewer
- Contact development team with log excerpts

Version History

Version Date Changes
Current 2025 Active development version

Last Updated: November 10, 2025
Maintained By: Psyter Development Team