LINE Pay 串接筆記
在正式商店還沒申請下來時,我們可以直接申請 Sandbox 進行串接測試。不過要注意的是 Sandbox 不會保留交易紀錄,所以如果有要接退費 api 會失敗。
用 composer 安裝。
一、申請 Sandbox
進入 Sandbox 網頁,點「註冊sandbox帳號」。 側邊會開啟註冊表單,輸入後送出。 信箱會收到 LINE Pay 寄來的測試帳號信件。二、取得認證訊息
到 合作商店中心,輸入信箱收到的 sandbox 帳密登入。 點選商家中心右上角的「測試環境」,會開啟一個新視窗。 點選左側選單「管理付款連結→管理連結金鑰」,進入頁面後點「查詢」。 LINE Pay 會寄一封驗證碼信到註冊信箱,輸入信中的驗證碼。 此時可以在下方欄位看到 Channel ID 和 secret。三、安裝 SDK
我安裝的是 LINE Pay SDK for PHP 這個套件。用 composer 安裝。
composer require yidas/line-pay-sdk ~3.0.0搭配 Laravel 範例程式:
- <?php
- namespace App\Http\Controllers;
- use App\Http\Controllers\Controller;
- use Illuminate\Http\Request;
- use yidas\linePay\Client;
- class LinePayController extends Controller
- {
- /**
- * 請求付款
- */
- public function checkout()
- {
- $linePay = new Client([
- 'channelId' => 'Channel ID',
- 'channelSecret' => 'Channel Secret Key',
- 'isSandbox' => config('app.env') == 'production' ? false : true,
- ]);
- $response = $linePay->request([
- 'amount' => '訂單金額',
- 'currency' => 'TWD',
- 'orderId' => '訂單 ID',
- 'packages' => [
- [
- 'id' => '商店 ID',
- 'amount' => '商店消費金額',
- 'products' => [
- [
- 'name' => '商品名稱',
- 'quantity' => '商品數量',
- 'price' => '商品金額',
- ],
- ],
- ],
- ],
- 'redirectUrls' => [
- 'confirmUrl' => '付款授權頁面',
- 'cancelUrl' => '付款取消頁面',
- ],
- ]);
- if ($response->isSuccessful()) {
- // 付款請求成功
- return redirect()->away($response->getPaymentUrl());
- } else {
- // 付款請求失敗,記錄錯誤訊息
- logger('付款失敗:(' . $response['returnCode'] . ') ' . $response['returnMessage'] . '。');
- }
- }
- /**
- * 付款授權頁面
- */
- public function confirm(Request $request)
- {
- // 已付款,更新訂單為已付款
- return redirect()->route('orders.show');
- }
- /**
- * 付款取消頁面
- */
- public function cancel(Request $request)
- {
- // 取消付款
- return Inertia::render('Order/Cancel', [
- 'message' => '付款取消。',
- 'url' => route('orders.index'),
- ]);
- }
- }
留言
張貼留言