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¶
- Payment Inquiry Processing - Verifies pending payment statuses with payment gateway
- Refund Processing - Handles automated refund requests and status updates
- Wallet & Package Payments - Processes wallet recharge and package purchase inquiries
- FCM Notifications - Sends Firebase Cloud Messaging notifications and appointment reminders
- SCHFS Card Expiry Notifications - Notifies users about expiring SCHFS insurance cards
- 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¶
- .NET Framework 4.8 installed on target server
- SQL Server with appropriate database schema
- Windows Server with service installation permissions
- Network access to:
- SQL Server database
- Psyter API endpoints
- Scheduling API endpoints
- Payment gateway (Smart Routing)
Installation Steps¶
Option 1: Using Visual Studio¶
-
Build the Solution
# Open solution in Visual Studio # Build > Build Solution (Ctrl+Shift+B) -
Install the Service
# Open Developer Command Prompt as Administrator cd "D:\Dev\Projects\Psyter\WindowsService\PsyterPaymentInquiry\bin\Release" # Install the service installutil PsyterPaymentInquiry.exe -
Start the Service
# Using Services Console (services.msc) # Or via command line: net start PsyterPaymentInquiry
Option 2: Using Advanced Installer¶
-
Build the Installer
- OpenPsyter Payment Inquiry Service\Psyter Payment Inquiry Service.aip
- Build the installer package -
Deploy
- Run the generated MSI/EXE installer on target server
- Follow installation wizard
Configuration Steps¶
-
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]" /> -
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 -
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¶
-
Service Health
- Service running status
- Thread states (alive/terminated)
- Timer execution frequency -
Payment Processing
- Pending payment count
- Successful inquiry rate
- Failed payment count
- Average processing time -
Notification Delivery
- Pending notification count
- Successful delivery rate
- Failed notification count -
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:
-
Check Logs
Get-Content ".\Logs\ServiceLog_Inquiry_*.txt" -Tail 50 -
Verify Payment Gateway Connectivity
// Check SmartRoutingRefundInquiryUrl is accessible // Verify SecureHash generation is correct -
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:
-
Check Service Logs
Get-Content ".\Logs\ServiceLog_SendFCMNotificationAndReminders_*.txt" -
Verify API Authentication
# Check if PsyterAPIAuthToken is being generated # Look for "Psyter API Call Token Created" in logs -
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¶
- App.config contains:
- Database credentials (plaintext)
- API endpoint URLs
Recommendation: Use Windows DPAPI or encrypted configuration sections
-
Payment Gateway Credentials
- Stored in databaseAppConfigSettingstable
- SecureHash using SHA256
- Merchant ID and secret key -
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¶
- Parallel Processing: Process multiple payments concurrently
- Caching: Cache API tokens to reduce authentication calls
- Batching: Batch database updates instead of individual calls
- 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¶
- Psyter API - Main application API
- Scheduling API - Booking management
- Payment Gateway - Smart Routing payment processor
- SQL Server - Data persistence
- FCM - Push notification delivery (called via Psyter API)
Maintenance¶
Regular Tasks¶
- Weekly: Review service logs for errors
- Monthly: Verify service is running and timers executing
- Quarterly: Review and optimize database stored procedures
- Annually: Update NuGet packages and security patches
Update Procedures¶
-
Stop Service
net stop PsyterPaymentInquiry -
Backup Current Version
Copy-Item "C:\Program Files\PsyterPaymentInquiry" "C:\Backups\PsyterPaymentInquiry_$(Get-Date -Format 'yyyyMMdd')" -Recurse -
Deploy New Version
- Copy new binaries
- Update App.config if needed -
Start Service
net start PsyterPaymentInquiry -
Verify Operation
Get-Content ".\Logs\ServiceLog_Inquiry_*.txt" -Tail 20
Development & Debugging¶
Debug Mode¶
To run in debug mode (for development):
-
Uncomment debug code in
Program.cs:
//For Debugging PaymentInquiryService service = new PaymentInquiryService(); service.GetPendingFCMNotificationsAndReminders(); System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); -
Run from Visual Studio (F5)
- 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