Integrating Payments with QR Code in LINE Bot (Laravel)

Integrating Payments with QR Code in LINE Bot (Laravel)

To integrate a payment gateway in your LINE bot and generate a QR code for payments, you can use Omise, PromptPay, PayPal, or Stripe. In this example, I’ll guide you through PromptPay QR (Thailand) and Stripe.


1. Generate a PromptPay QR Code

PromptPay is widely used in Thailand for payments via QR codes.

Step 1: Install a QR Code Generator

Run the following command in your Laravel project:

composer require simplesoftwareio/simple-qrcode

Step 2: Create a Helper Function for QR Code

Add this function in app/Helpers/QrHelper.php:

namespace App\Helpers;

use SimpleSoftwareIO\QrCode\Facades\QrCode;

class QrHelper
{
    public static function generatePromptPayQr($phone, $amount = null)
    {
        $id = str_pad($phone, 13, '0', STR_PAD_LEFT);
        $payload = "0002010102112937$" . $id . "5303764";
        
        if ($amount) {
            $payload .= "54" . sprintf("%02d", strlen($amount)) . $amount;
        }

        $payload .= "6304"; // CRC Placeholder
        $payload .= substr(hash('crc32b', $payload), -4); // CRC Calculation

        return QrCode::size(300)->generate($payload);
    }
}

Step 3: Modify LineBotController.php to Send QR Code

use App\Helpers\QrHelper;
use LINE\LINEBot\MessageBuilder\ImageMessageBuilder;

public function webhook(Request $request)
{
    $events = $request->all();

    foreach ($events['events'] as $event) {
        $replyToken = $event['replyToken'];
        $userMessage = strtolower($event['message']['text']);

        if ($userMessage === "pay") {
            // Generate QR Code
            $qrCode = QrHelper::generatePromptPayQr("0812345678", "100.00");

            // Save QR Code as Image
            $path = public_path('qrcodes/payment.png');
            file_put_contents($path, $qrCode);

            // Send QR Code Image
            $imageMessage = new ImageMessageBuilder(
                url('/qrcodes/payment.png'),
                url('/qrcodes/payment.png')
            );
            $this->bot->replyMessage($replyToken, $imageMessage);
        }
    }

    return response()->json(['status' => 'ok']);
}

Step 4: Test Payment

  1. Type pay in LINE chat.
  2. The bot will send a QR code image for PromptPay (TH).
  3. Scan with your banking app and make a payment.

2. Integrate Stripe for Online Payments

Stripe allows secure online payments with credit/debit cards.

Step 1: Install Stripe SDK

Run:

composer require stripe/stripe-php

Step 2: Configure .env

Add:

STRIPE_KEY=your_stripe_public_key
STRIPE_SECRET=your_stripe_secret_key

Step 3: Create a Stripe Payment URL

Modify LineBotController.php:

use Stripe\Stripe;
use Stripe\Checkout\Session;

public function webhook(Request $request)
{
    $events = $request->all();

    foreach ($events['events'] as $event) {
        $replyToken = $event['replyToken'];
        $userMessage = strtolower($event['message']['text']);

        if ($userMessage === "pay") {
            // Set Stripe API Key
            Stripe::setApiKey(env('STRIPE_SECRET'));

            // Create a Checkout Session
            $session = Session::create([
                'payment_method_types' => ['card'],
                'line_items' => [[
                    'price_data' => [
                        'currency' => 'thb',
                        'product_data' => [
                            'name' => 'LINE Bot Payment',
                        ],
                        'unit_amount' => 10000, // 100 THB (in satang)
                    ],
                    'quantity' => 1,
                ]],
                'mode' => 'payment',
                'success_url' => url('/payment/success'),
                'cancel_url' => url('/payment/cancel'),
            ]);

            // Send Stripe Payment Link
            $message = new TextMessageBuilder(
                "Click to Pay: " . $session->url
            );

            $this->bot->replyMessage($replyToken, $message);
        }
    }

    return response()->json(['status' => 'ok']);
}

Step 4: Test Stripe Payment

  1. Type pay in LINE chat.
  2. The bot will send a payment link.
  3. Click the link to enter Stripe’s secure checkout.
  4. Complete the payment using a credit/debit card.

3. Store Payment Logs in the Database

Modify LineBotController.php to store transaction data.

Step 1: Create Payment Table

Run:

php artisan make:migration create_payments_table

Modify the migration:

public function up()
{
    Schema::create('payments', function (Blueprint $table) {
        $table->id();
        $table->string('user_id');
        $table->string('payment_type'); // PromptPay, Stripe
        $table->decimal('amount', 10, 2);
        $table->string('status')->default('pending');
        $table->timestamps();
    });
}

Run:

php artisan migrate

Step 2: Save Payment Records

Modify LineBotController.php:

use App\Models\Payment;

public function webhook(Request $request)
{
    $events = $request->all();

    foreach ($events['events'] as $event) {
        $replyToken = $event['replyToken'];
        $userId = $event['source']['userId'];
        $userMessage = strtolower($event['message']['text']);

        if ($userMessage === "pay") {
            $payment = Payment::create([
                'user_id' => $userId,
                'payment_type' => 'Stripe',
                'amount' => 100.00,
                'status' => 'pending'
            ]);

            $message = new TextMessageBuilder(
                "Payment record created. Waiting for confirmation."
            );

            $this->bot->replyMessage($replyToken, $message);
        }
    }

    return response()->json(['status' => 'ok']);
}

Final Testing

✅ Type pay → Gets a PromptPay QR Code or Stripe payment link.
✅ Make a payment.
✅ Check database → Logs are stored in the payments table.


Next Steps

  • Webhook for Payment Confirmation: Check when a payment is completed.
  • Automated Order Processing: Activate services after payment.
  • Expand to More Gateways: Support PayPal, TrueMoney Wallet, etc..

Leave a Comment