Setting Up BayarCash in Laravel the Right Way
If you build SaaS for the Malaysian market, you will eventually need FPX. BayarCash is a common choice.
The SDK is not the problem. The problem is your architecture. If you call the SDK from a controller or hardcode status codes in your views, you will face issues in production.
I have shipped BayarCash across three different Laravel apps. Here is the pattern that works every time.
Key Terms To Master
- Portal: Your merchant checkout config. Use the portal_key.
- API Token: This authenticates your outgoing calls.
- Secret Key: This signs your payloads and verifies webhooks. Keep this safe.
- Payment Intent: You post a charge, receive a URL, and redirect the user.
- Channel: Always use SDK constants instead of raw numbers.
Structure Your Code Well
Your domain code should never see a raw BayarCash payload. You need three layers:
- A thin client wrapper: This handles config and provides typed methods.
- A gateway: This implements an interface and speaks your domain language.
- A factory: This picks the active gateway so you can swap BayarCash for Stripe easily.
Binding a Fake Gateway
If you do not provide an API token, bind a Fake provider in your service container. This allows your tests to run without a network and lets your local builds run without active billing.
Webhook Best Practices
The webhook is your source of truth. Follow these rules to avoid a production storm:
- CSRF Exempt: Your webhook route must bypass CSRF protection.
- Verify Signatures: Always verify the signature before doing anything else.
- The 200 Rule: Once you verify the signature, return a 2xx response.
- Avoid Retries: If you return a 500 error, BayarCash will retry your webhook 40 times. This can crash your server. Log errors, but still return a 200.
- Idempotency: Make sure your logic can handle the same webhook twice without creating duplicate orders.
Checklist for Success
• Use the order_number as a correlation key. Keep it under 30 characters. • Save a pending local record before you redirect the user. • Use the server-to-server callback as your main authority. • Use the return URL as a safety net for reconciliation. • Map integer status codes to your own Enums immediately.
Payment integrations touch real money. Test your signature verification and idempotency more than anything else.
Source: https://dev.to/nasrulhazim/setting-up-bayarcash-fpx-in-laravel-the-right-way-4b2n
