Learn how to implement digital receipts and integrate them with the WhatsApp Business API for operational efficiency. This article covers technical steps, code examples, and best practices for your SIMRS or POS system.
In this fast-paced digital era, operational efficiency and customer experience are key to success, especially in the healthcare sector. Hospital information management systems (SIMRS) or traditional Point of Sales (POS) systems often still rely on paper-based physical receipts. This practice not only incurs significant operational costs for paper, ink, and printer maintenance, but is also less environmentally friendly and prone to loss or damage. Imagine how many sheets of paper are wasted every day in a clinic or large hospital; on average, a small clinic can print 500-1000 receipts per month, with paper and ink costs reaching tens of millions of rupiah per year for a hospital scale. Not to mention, physical receipts often do not provide easy access to transaction history data for patients and management. This article will guide you through the process of implementing efficient digital receipts and their integration with the WhatsApp Business API for automatic receipt delivery. We will discuss basic concepts, infrastructure preparation, implementation details with real code examples, error handling, and best practices to ensure a robust, secure, and scalable solution, utilizing the latest technologies such as Laravel 11 and WhatsApp Cloud API.
Basic Concepts of Digital Receipts and WhatsApp Receipt
A digital receipt is an electronic representation of proof of transaction or payment, usually in the form of a PDF document or other digital format. Unlike paper receipts that are prone to loss and fading, digital receipts offer advantages in terms of storage, accessibility, and sustainability. In the context of SIMRS or POS, digital receipts can include details of payment for medical services, medicines, or other retail goods. The main benefits include reduced operational costs (savings of up to 70% on paper and ink costs), increased efficiency (no need to refill paper or replace ink), and increased patient satisfaction as they can easily store and access their transaction history on digital devices.
WhatsApp Receipt integration refers to the process of automatically sending these digital receipts through the WhatsApp Business API (WABA) platform. Why WhatsApp? In Indonesia, WhatsApp has a very high user penetration, reaching more than 90% of total internet users. This makes it the most effective and direct communication channel to reach patients or customers. With WABA, your system can send structured messages, including PDF documents, automatically and in real-time after a transaction is completed. This is not just sending an ordinary message, but using message templates approved by Meta to ensure the message arrives and is considered official communication.
Key components in this system include: (1) Backend System (SIMRS/POS) responsible for processing transactions and triggering the creation of digital receipts. (2) PDF Generator Module that converts transaction data into professional PDF format. (3) WhatsApp Business API as a bridge to send the PDF document to the patient's WhatsApp number. (4) Webhook Mechanism to receive message delivery status (sent, read, failed), which is important for monitoring and audit. As a concrete example, a clinic that implemented this system reported a 15% increase in patient satisfaction due to the ease of receiving receipts directly on their phones, while cutting printing costs by Rp 5 million per month.
The implementation of digital receipts and WhatsApp receipts is not just following a trend, but a strategic step for service modernization. This aligns with government initiatives such as SatuSehat that encourage digitalization of medical records and health transactions. Thus, the system we build is not only efficient but also future-oriented and ready to face the regulatory challenges of digitalizing healthcare services.
Infrastructure Preparation and Development Environment
To build a robust digital receipt and WhatsApp receipt integration solution, we need thorough infrastructure preparation and a suitable development environment. The right technology choices will ensure scalability, security, and ease of system maintenance.
1. Backend System: We will use PHP with the Laravel 11.x framework as the backend foundation. Laravel is known for its expressive syntax, rich ecosystem, and built-in features that facilitate enterprise-scale application development. Make sure you use PHP version 8.2 or higher and Composer 2.x for dependency management. For the database, PostgreSQL 16 is a highly recommended choice due to its reliability, data integrity, and superior performance for transactional data, especially in a SIMRS environment that requires high data consistency. Another alternative is Node.js 20 LTS if your team is more familiar with JavaScript on the server side.
2. PDF Generator Library: To generate digital receipts in PDF format from HTML, we will rely on dompdf/dompdf version 2.0 and above for PHP. This library allows us to render Laravel Blade views directly to PDF, providing full flexibility in receipt design. If using Node.js, Puppeteer can be used to control the headless Chrome browser and print HTML to PDF.
3. WhatsApp Business API (WABA): The main integration will use Meta's WhatsApp Business Platform Cloud API. This is a more manageable option compared to the On-Premise API because Meta manages the server infrastructure. You need to have a verified Facebook Business Manager Account, a WhatsApp Business Account, and a phone number that will be used to send messages. The registration process involves business verification and message template approval. Make sure you have configured the Webhook in the Facebook Developer Console to receive message status notifications.
4. Hosting Environment: For deployment, we recommend cloud services such as AWS EC2 (Ubuntu 22.04 LTS) or Google Cloud Run. EC2 provides full control over the server, allowing configuration of Nginx 1.22+ as a web server and supervisor for queue process management. Cloud Run offers automatic scalability and minimal serverless management. Ensure the server has adequate specifications, for example t3.medium (2 vCPU, 4GB RAM) for starters. The use of queue services such as Redis 7.x or RabbitMQ is highly recommended to process WhatsApp sending asynchronously, avoiding blocking in the main application.
5. Security: All communication must be encrypted using HTTPS. Use SSL/TLS certificates from Let's Encrypt or other providers. API Keys or Access Tokens for the WhatsApp API must be stored securely, for example in environment variables (.env file) and must not be hardcoded. Consider using AWS Secrets Manager or HashiCorp Vault for more advanced credential management. Ensure the firewall is properly configured to only allow relevant ports (80, 443, 22).
As an implementation scenario, assume an existing SIMRS based on Laravel 9.x that wants to add this feature. Rather than modifying the core of the SIMRS, we can build a separate microservice using Laravel 11.x specifically for the receipt generation and WhatsApp sending functions. This microservice will communicate with the main SIMRS through an internal API (for example, RESTful API) to obtain transaction data. This approach minimizes risk to the main system and allows independent development of new features.
Backend Implementation for Receipt Generation and Sending
This section will discuss the details of backend implementation using Laravel 11.x to manage digital receipt generation and trigger sending via WhatsApp. We will focus on two main components: a controller to generate PDF and a service to interact with the WhatsApp Business API. To ensure performance and reliability, we will utilize Laravel Queues for asynchronous processing.
1. Controller for PDF Receipt Generation
First, we prepare a controller that will receive requests to create receipts and convert them to PDF. Assume we have a Transaction model that contains payment transaction details.
<?phpnamespace App\'Http\Controllers;'use App\Models\Transaction;use Illuminate\Http\Request;use Dompdf\Dompdf;use Dompdf\Options;use Illuminate\Support\Facades\Storage;class ReceiptController extends Controller{ public function generatePdf(string $transactionId) { $transaction = Transaction::with(['patient', 'items'])->findOrFail($transactionId); $options = new Options(); $options->set('isHtml5ParserEnabled', true); $options->set('isRemoteEnabled', true); $dompdf = new Dompdf($options); $html = view('receipts.invoice', compact('transaction'))->render(); $dompdf->loadHtml($html); $dompdf->setPaper('A4', 'portrait'); $dompdf->render(); $output = $dompdf->output(); $filename = 'receipt-'. $transaction->id .'-'. now()->format('YmdHis') .'.pdf'; Storage::disk('public')->put('receipts/'. $filename, $output); return Storage::disk('public')->url('receipts/'. $filename); }}Code explanation: The generatePdf function takes a transaction ID, loads transaction data along with its relations (patient, service/medicine items). Then, it initializes Dompdf with options that allow HTML5 parsing and remote asset loading (e.g., logo images). The HTML content of the receipt is taken from the Blade view receipts.invoice, which is filled with transaction data. After rendering, the PDF is saved to the public disk (e.g., in the storage/app/public/receipts folder) and its public access URL is returned. It is important to run php artisan storage:link so that the public folder can be accessed via the web.
2. Service for Sending WhatsApp Message
Next, we create a Laravel Job that will handle sending WhatsApp messages asynchronously. This will prevent the main application from waiting for a response from the WhatsApp API, improving system responsiveness.
<?phpnamespace App\Jobs;'use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;class SendWhatsAppReceipt implements ShouldQueue{ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected string $recipientPhoneNumber; protected string $receiptUrl; protected string $caption; public int $tries = 3; // Retry up to 3 times public int $backoff = 5; // Wait 5 seconds before retrying public function __construct(string $recipientPhoneNumber, string $receiptUrl, string $caption = 'Struk Pembayaran Anda') { $this->recipientPhoneNumber = $recipientPhoneNumber; $this->receiptUrl = $receiptUrl; $this->caption = $caption; } public function handle(): void { $whatsappApiUrl = config('services.whatsapp.api_url') . config('services.whatsapp.phone_number_id') . '/messages'; $accessToken = config('services.whatsapp.access_token'); try { $response = Http::withToken($accessToken)->post($whatsappApiUrl, [ 'messaging_product' => 'whatsapp', 'recipient_type' => 'individual', 'to' => $this->recipientPhoneNumber, 'type' => 'document', 'document' => [ 'link' => $this->receiptUrl, 'caption' => $this->caption ] ]); if ($response->successful()) { Log::info('WhatsApp receipt sent successfully', ['phone' => $this->recipientPhoneNumber, 'receipt_url' => $this->receiptUrl, 'response' => $response->json()]); } else { Log::error('Failed to send WhatsApp receipt', ['phone' => $this->recipientPhoneNumber, 'receipt_url' => $this->receiptUrl, 'response' => $response->json()]); $this->fail($response->body()); } } catch (\Exception $e) { Log::error('Exception sending WhatsApp receipt', ['error' => $e->getMessage(), 'phone' => $this->recipientPhoneNumber]); $this->fail($e->getMessage()); } }}Code explanation: The SendWhatsAppReceipt job receives the recipient's phone number, PDF receipt URL, and caption. Inside the handle() method, it makes an HTTP POST call to the WhatsApp Cloud API. The API URL and access token are taken from the Laravel configuration (e.g. config/services.php and .env). The payload contains messaging_product, recipient_type, the to number, and the message type document with a link to the PDF we created. Logs are used to record success or failure. If it fails, the job will be marked for retry ($this->tries) or marked as permanently failed. To trigger this job, you can call SendWhatsAppReceipt::dispatch($phoneNumber, $receiptUrl) from a controller after the PDF is successfully created. Make sure you have configured a queue driver in Laravel (e.g. Redis or database) and run the queue worker (php artisan queue:work).
Example Payload, Error Handling, and Monitoring
Understanding the correct payload structure, how to handle errors, and monitor the system is crucial for a stable and reliable implementation. Errors in sending digital receipts can directly impact patient experience and hospital operations.
Example WhatsApp Cloud API Payload for Documents
When sending documents such as PDF receipts via the WhatsApp Business API, the following JSON payload is the expected format. This ensures that the document is sent correctly and includes relevant metadata.
{ "messaging_product": "whatsapp", "recipient_type": "individual", "to": "6281234567890", "type": "document", "document": { "link": "https://your-domain.com/storage/receipts/receipt-TXN001-20231027103000.pdf", "caption": "Struk Pembayaran Anda No. TXN001 dari Klinik Sehat Selalu. Terima kasih telah mempercayakan layanan kami!" }}Explanation:
messaging_product: Always 'whatsapp' for the WhatsApp Business API.recipient_type: 'individual' to send to a single user.to: The recipient's phone number in E.164 format (including country code without the '+' sign).type: 'document' because we are sending a PDF file.document: An object containing the document details.link: A publicly accessible URL to the PDF receipt file. It is important that this URL is accessible by the WhatsApp server (e.g., not behind a firewall or requiring authentication).caption: Text that will accompany the PDF document. This is a good place to add the transaction number, clinic name, and a thank-you message.
Example Error Messages and Their Handling
Although the WhatsApp API is quite stable, errors can occur. Here are examples of error messages you might encounter and strategies for handling them:
{ "error": { "message": "(#131009) Parameter value is not valid", "type": "OAuthException", "code": 131009, "error_data": { "messaging_product": "whatsapp", "details": "The document URL is invalid." }, "fbtrace_id": "Abcdef1234567890" }}This error message (code: 131009) specifically indicates that the document URL you provided is invalid. This could mean:
- The URL is not public or requires authentication.
- The URL is misspelled or does not point to the actual file.
- The file at the URL does not exist or is corrupted.
- The URL does not use HTTPS (WhatsApp requires secure URLs).
Error Handling Strategy:
- Detailed Logging: Every API response, whether successful or failed, must be logged in detail in the application log. Include the transaction ID, recipient phone number, and the entire API response (including
fbtrace_idfor debugging with Meta). Example:Log::error('Failed to send WhatsApp receipt for TXN001', ['phone' => '62812...', 'error_code' => 131009, 'response' => $response->json()]); - Retry Mechanism: For transient errors (for example, temporary network issues on WhatsApp's side or your server), implement a retry mechanism with exponential backoff. Laravel Queues automatically supports this through the
$triesand$backoffproperties on the Job. If it still fails after several attempts, consider it a permanent failure. - Fallback Mechanism: If WhatsApp delivery persistently fails (for example, invalid number, or an API issue that cannot be resolved by retry), the system must have a fallback path. The best alternative is to send the receipt via email to the patient or provide a download link on the patient portal.
- Admin Notification: For critical or persistent failures, send an automatic notification (for example via Slack, Telegram, or email) to the IT or operations team so it can be investigated immediately.
- URL Monitoring: Ensure the generated URL for the PDF receipt is always valid and accessible. Perform regular checks on files stored in storage.
System Monitoring
Monitoring is key to maintaining system health. Implement the following:
- API Metrics: Monitor the success rate and response time (latency) of WhatsApp API calls. Use tools such as Prometheus and Grafana for metric visualization.
- Queue Status: Monitor the number of pending, processing, and failed jobs in the Laravel Queue. This will provide an overview of the workload and potential bottlenecks.
- Log Aggregation: Use a centralized logging system such as the ELK Stack (Elasticsearch, Logstash, Kibana) or Splunk to collect, analyze, and search logs from your various services.
- Alerting: Configure alerts for important metrics, for example if the WhatsApp delivery failure rate exceeds a certain threshold (for example >5% within 5 minutes) or if there is a job queue that is too long.
With this combination, you can not only detect problems quickly but also have enough data to analyze the root cause and continuously improve system reliability.
Best Practices
- Strict Data Security: Always encrypt sensitive patient data (name, transaction details, phone number) both at rest and in transit. Use HTTPS for all API communication. Ensure the WhatsApp API key is stored in environment variables and not hardcoded in the source code. Apply the principle of least privilege for access to data and APIs. Conduct regular security audits to identify and address potential vulnerabilities.
- Scalability Through Message Queues: Utilize a message queue system (such as Laravel Queues with Redis or RabbitMQ) to process digital receipt delivery and WhatsApp API calls asynchronously. This will prevent the main application from becoming blocking, improve system responsiveness, and enable handling high transaction volumes without performance degradation. Design services to be stateless to facilitate horizontal scaling.
- Regulatory and WhatsApp Policy Compliance: Ensure your implementation complies with local regulations such as Permenkes No. 24 of 2022 concerning Electronic Medical Records in Indonesia for health data, as well as the ITE Law for electronic transactions. In addition, comply with the WhatsApp Business Policy, especially regarding user opt-in to receive messages and the use of approved message templates for transactional communication.
- Efficient Message Template Management: For transactional messages such as receipts, always use WhatsApp Message Templates approved by Meta. This ensures messages are delivered without issues and reduces the risk of being blocked as spam. Design templates that are clear, concise, and informative. Revise templates if there are changes to important information and resubmit for approval.
- Robust Error Handling and Logging: Implement comprehensive logging mechanisms for every step of the process, from PDF generation to WhatsApp delivery status. Use a centralized logging system (e.g., ELK Stack) to facilitate analysis. Include transaction IDs and relevant error details. Implement a retry mechanism with exponential backoff for transient errors and fallback (e.g., send via email) for persistent failures.
- User Experience (UX) Optimization: Ensure digital receipts are easy to read, informative, and professionally designed. Include all important details such as patient name, date, list of services/medications, total cost, and clinic/hospital contact information. Provide patients with the option to re-download receipts if needed, for example through a patient portal or a link that is valid for a certain period.
- Comprehensive Testing: Perform thorough unit, integration, and end-to-end testing to ensure all components function correctly. Test various scenarios, including successful transactions, failed transactions, invalid WhatsApp numbers, API failures, and high transaction volumes. Use realistic and non-sensitive test data.
- Version Management and Documentation: Use a version control system such as Git to manage source code. Apply semantic versioning practices. Fully document the system architecture, workflows, API endpoints, and configuration. Good documentation is essential for long-term maintenance and onboarding new teams.
FAQ
- What is the difference between WhatsApp Business App and WhatsApp Business Platform API?
WhatsApp Business App is a free application intended for small businesses, with limited features such as business profile, catalog, and quick replies, and can only be used by a few devices. In contrast, WhatsApp Business Platform API is a paid solution intended for medium to large-scale businesses, enabling integration with backend systems (such as SIMRS or POS) for large-scale message delivery automation, supporting many agents, and offering more advanced features such as structured message templates and webhooks for delivery status. This API is essential for automated digital receipt delivery solutions.
- How much does WhatsApp Business API integration cost?
The cost of WhatsApp Business API integration varies. There is a cost for using the API itself, calculated per conversation (conversation-based pricing) by Meta, with different conversation categories (utility, authentication, marketing, service). In addition, there may be fees from a business solution provider (BSP/Business Solution Provider) if you do not integrate directly with Meta's Cloud API. For Meta's Cloud API, you need to consider server hosting, development, and maintenance costs. Initial estimates can range from a few million to tens of millions of rupiah depending on complexity and message volume.
- How can patient data privacy be ensured on digital receipts?
Patient data privacy is the top priority. Ensure digital receipts are only sent to WhatsApp numbers that have been registered and verified by the patient (through a clear opt-in process). Use end-to-end encryption when data is stored and transferred. Ensure the uploaded PDF receipt URL has a limited validity period or is protected with an access token. Finally, comply with data privacy standards such as the Personal Data Protection Law and Permenkes No. 24 of 2022 concerning Electronic Medical Records.
- Is this digital receipt legally valid in Indonesia?
Yes, a digital receipt can be considered legally valid in Indonesia. Based on Law Number 11 of 2008 concerning Electronic Information and Transactions (UU ITE), electronic documents and electronic signatures have the same legal force as physical documents, provided they meet the validity requirements. This means that a digital receipt generated by a trusted and non-modifiable system can be accepted as valid transaction evidence. It is important to ensure the data integrity and auditability of the digital receipt.
- What if the patient does not have WhatsApp or their number changes?
It is important to provide alternative communication channels. If the patient does not have WhatsApp, the system must have an option to send the receipt via email or print it physically as a fallback. For cases where the number changes, patients must have a mechanism to update their contact information in your SIMRS or POS system. The system must also be able to detect WhatsApp delivery failures (via status webhook) and automatically trigger alternative delivery methods.
- Can this digital receipt be integrated with other systems such as BPJS or SatuSehat?
This digital receipt is essentially proof of a payment transaction. Its integration with BPJS or SatuSehat would be more related to the transaction data itself, not the receipt format. The transaction data underlying the receipt (for example, service details, fees, transaction code) can be integrated into SatuSehat through the FHIR R4 or HL7 v2.5.1 standards for healthcare service reporting. The digital receipt itself is not directly integrated with BPJS or SatuSehat, but it is the result of a transaction process whose data can be reported to those systems. Nugroho Setiawan has experience in bridging integration to BPJS and SatuSehat, so this is very feasible.
The implementation of digital receipts and WhatsApp receipt integration is not merely a feature enhancement, but a fundamental transformation in how hospitals or clinics operate. It is a strategic step toward higher efficiency, significant reduction in operational costs, and a drastic improvement in patient experience. By following this in-depth guide, you have been equipped with knowledge and concrete examples to start this digitalization journey. From choosing modern technologies such as Laravel 11.x and PostgreSQL 16 to an in-depth understanding of the WhatsApp Business Platform Cloud API, you are now ready to build a robust and scalable solution. Do not let legacy systems hinder your growth potential. Nugroho Setiawan and the team are ready to be your strategic partner in realizing this digital transformation. With our expertise in SIMRS, SIM Klinik, BPJS/SatuSehat/FHIR integration, and POS, we can help you design, develop, and implement a digital receipt solution tailored to your organization's specific needs. Contact us now for a free consultation or a demo of a solution that can improve your efficiency and patient satisfaction.
This article is part of the education by Nugroho Setiawan, an IT consultant in Jogja. Related solutions: PilarPOS SIMRS Integrator Bridging SatuSehat. Need a free consultation?
Komentar
Belum ada komentar. Jadilah yang pertama!
Saya membantu konsultasi IT & pengembangan aplikasi untuk rumah sakit, klinik, dan bisnis di Yogyakarta (DIY), Magelang, dan sekitarnya.