PHP code example of ycs77 / laravel-newebpay

1. Go to this page and download the library: Download ycs77/laravel-newebpay library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ycs77 / laravel-newebpay example snippets


use Ycs77\NewebPay\Facades\NewebPay;

Route::post('/pay', function () {
    return NewebPay::payment()
        ->withOrder('Order'.time())       // 訂單編號
        ->withAmount(120)                 // 交易金額
        ->withItemDescription('我的商品')  // 商品名稱
        ->withEmail('[email protected]')   // 付款人信箱
        ->withCredit()                    // 啟用信用卡付款
        ->withReturnUrl('/pay/callback')  // 支付完成返回網址 (Callback)
        ->submit();
});

use Illuminate\Http\Request;
use Ycs77\NewebPay\Facades\NewebPay;

Route::post('/pay/callback', function (Request $request) {
    $result = NewebPay::result($request);

    if ($result->isFail()) {
        return redirect()
            ->to('/pay')
            ->with('error', $result->message());
    }

    // 訂單付款成功,處理訂單邏輯...

    return redirect()
        ->to('/pay')
        ->with('success', '付款成功');
});

->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: [
        '/pay/callback',
    ]);
})

use Ycs77\NewebPay\Enums\CreditInst;

NewebPay::payment()
    ...
    // 啟用信用卡,預設為一次付清
    ->withCredit()
    // 啟用紅利折抵
    ->withCredit(red: true)
    // 分期付款:3、6 期
    ->withCredit(inst: [CreditInst::P3, CreditInst::P6])
    ->submit();

NewebPay::payment()
    ...
    ->withCreditRemember('[email protected]')
    ->submit();

NewebPay::payment()
    ...
    // 必填信用卡到期日
    ->withCreditRemember('[email protected]', CreditRememberDemand::EXPIRATION_DATE)
    // 必填背面末三碼
    ->withCreditRemember('[email protected]', CreditRememberDemand::CVC)
    ->submit();

NewebPay::payment()
    ...
    // 啟用 WebATM
    ->withWebAtm()
    // 啟用 ATM 轉帳
    ->withAtmTransfer()
    ->submit();

use Ycs77\NewebPay\Enums\Bank;

NewebPay::payment()
    ...
    ->withAtmTransfer()
    ->withBank([Bank::BOT, Bank::HNCB]) // 台灣銀行、華南銀行
    ->submit();

use Ycs77\NewebPay\Enums\NTCBLocate;

NewebPay::payment()
    ...
    ->withNationalTravelCard(NTCBLocate::HsinchuCity, '2020-01-01', '2020-12-31')
    ->submit();

NewebPay::payment()
    ...
    ->withGooglePay()       // Google Pay
    ->withSamsungPay()      // Samsung Pay
    ->withLinePay()         // LINE Pay
    ->withUnionPay()        // 銀聯卡
    ->withAmericanExpress() // 美國運通卡
    ->withEsunWallet()      // 玉山 Wallet
    ->withTaiwanPay()       // 台灣 Pay
    ->submit();

NewebPay::payment()
    ...
    ->withLinePay(imageUrl: 'http://example.com/logo.png')
    ->submit();

NewebPay::payment()
    ...
    ->withEzPay()       // ezPay 電子錢包
    ->withEzPayWeChat() // ezPay 微信支付
    ->withEzPayAlipay() // ezPay 支付寶
    ->submit();

NewebPay::payment()
    ...
    ->withCvsCode() // 超商代碼繳費
    ->withBarcode() // 條碼繳費
    ->submit();

use Ycs77\NewebPay\Enums\CVSCOM;
use Ycs77\NewebPay\Enums\LgsType;

NewebPay::payment()
    ...
    // 物流方式
    ->withLogisticsPayment(CVSCOM::NOT_PAY_AND_PAY)
    // 物流型態
    ->withLogisticsType(LgsType::C2C)
    ->submit();

NewebPay::payment()
    ...
    ->withTradeLimit(900)  // 交易秒數限制 (60~900 秒)
    ->withExpireDays(14)   // 交易截止日 (天數,最多 180 天)
    ->submit();

NewebPay::payment()
    ...
    ->disableEmailModify()
    ->submit();

NewebPay::payment()
    ...
    ->withOrderComment('這是訂單備註')
    ->submit();

NewebPay::payment()
    ...
    ->withReturnUrl('/pay/callback')    // 支付完成返回網址 (Callback)
    ->withNotifyUrl('/pay/notify')      // 支付通知網址 (Notify)
    ->withCustomerUrl('/pay/customer')  // 商店取號網址
    ->withClientBackUrl('/pay/back')    // 返回按鈕網址
    ->submit();

use Illuminate\Http\Request;
use Ycs77\NewebPay\Facades\NewebPay;

Route::post('/pay/callback', function (Request $request) {
    $result = NewebPay::result($request);

    if ($result->isFail()) {
        return redirect()
            ->to('/pay')
            ->with('error', $result->message());
    }

    return redirect()
        ->to('/pay')
        ->with('success', '付款成功');
});

use Illuminate\Http\Request;
use Ycs77\NewebPay\Facades\NewebPay;

Route::post('/pay/notify', function (Request $request) {
    $result = NewebPay::result($request);

    if ($result->isFail()) {
        // 交易失敗,紀錄錯誤訊息...
        return;
    }

    logger('藍新金流 交易資訊 notify', ['result' => $result->toArray()]);

    // 訂單付款成功,處理訂單邏輯...
});

->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: [
        '/pay/callback',
        '/pay/notify',
    ]);
})

$result = NewebPay::result($request);
$result->status()       // 交易狀態:'SUCCESS' 或錯誤代碼
$result->isSuccess()    // 交易是否成功
$result->isFail()       // 交易是否失敗
$result->message()      // 交易狀態描述:'授權成功'
$result->result()       // 回傳參數 (陣列)
$result->merchantID()   // 藍新金流商店代號:'MS3311...'
$result->amount()       // 交易金額:120
$result->tradeNo()      // 藍新金流交易序號:'23061500000000000'
$result->orderNo()      // 商店訂單編號:'1686759318'
$result->paymentType()  // 付款方式:PaymentType::CREDIT
$result->payTime()      // 支付完成時間:Carbon 實例
$result->ip()           // 交易 IP:'127.0.0.1'
$result->escrowBank()   // 款項保管銀行:'HNCB'

if ($result->hasCredit()) {
    $credit = $result->credit();
    $credit->authBank()           // 收單金融機構:'CTBC'
    $credit->authBankName()       // 收單金融機構中文名稱:'中國信託銀行'
    $credit->cardBank()           // 發卡金融機構
    $credit->respondCode()        // 金融機構回應碼:'00'
    $credit->auth()               // 授權碼:'115468'
    $credit->card6No()            // 卡號前六碼:'400000'
    $credit->card4No()            // 卡號末四碼:'1111'
    $credit->inst()               // 分期-期別:12
    $credit->instFirst()          // 分期-首期金額:300
    $credit->instEach()           // 分期-每期金額:300
    $credit->ECI()                // ECI 值:'1'
    $credit->tokenUseStatus()     // 信用卡快速結帳使用狀態:TokenUseStatus::NOT_USED
    $credit->redAmt()             // 紅利折抵後實際金額:null
    $credit->paymentMethod()      // 交易類別:'CREDIT'
    $credit->paymentMethodName()  // 交易類別中文名稱:'台灣發卡機構核發之信用卡'
    $credit->dccAmt()             // 外幣金額:null
    $credit->dccRate()            // 匯率:null
    $credit->dccMarkup()          // 風險匯率:null
    $credit->dccCurrency()        // 幣別:null
    $credit->dccCurrencyCode()    // 幣別代碼:null
}

if ($result->hasAtm()) {
    $atm = $result->atm();
    $atm->payBankCode()        // 付款人金融機構代碼:'809'
    $atm->payerAccount5Code()  // 付款人金融機構帳號末五碼:'12345'
}

if ($result->hasStoreCode()) {
    $storeCode = $result->storeCode();
    $storeCode->codeNo()         // 繳費代碼:'TEST1234567890'
    $storeCode->storeType()      // 繳費門市類別:PaymentStoreType::HI_LIFE
    $storeCode->storeTypeName()  // 繳費超商中文名稱:'萊爾富'
    $storeCode->storeId()        // 繳費門市代號:'S9999'
}

if ($result->hasStoreBarcode()) {
    $storeBarcode = $result->storeBarcode();
    $storeBarcode->barcode1()      // 繳費條碼第一段條碼:'TEST1'
    $storeBarcode->barcode2()      // 繳費條碼第二段條碼:'TEST2'
    $storeBarcode->barcode3()      // 繳費條碼第三段條碼:'TEST3'
    $storeBarcode->repayTimes()    // 付款次數:0
    $storeBarcode->payStore()      // 繳費超商:'SEVEN'
    $storeBarcode->payStoreName()  // 繳費超商中文名稱:'7-11'
}

if ($result->hasLgs()) {
    $lgs = $result->lgs();
    $lgs->storeCode()    // 超商門市編號:'019666'
    $lgs->storeName()    // 取貨門市中文名稱:'全家台灣大道店'
    $lgs->storeType()    // 超商類別名稱:'全家'
    $lgs->storeAddr()    // 超商門市地址:'台中市中區台灣大道一段531號'
    $lgs->tradeType()    // 取件交易方式:LgsTradeType::PAY_ON_PICKUP
    $lgs->cvscomName()   // 取貨人姓名:'王小明'
    $lgs->cvscomPhone()  // 取貨人手機號碼:'0900111222'
    $lgs->lgsNo()        // 物流寄件單號:'-'
    $lgs->lgsType()      // 物流型態:LgsType::C2C
}

if ($result->hasEzPay()) {
    $ezPay = $result->ezPay();
    $ezPay->isEzPay()      // 是否為 ezPay 交易:true
    $ezPay->channelId()    // 跨境通路類型:EzPayChannel::ALIPAY
    $ezPay->channelName()  // 跨境通路中文名稱:'支付寶'
    $ezPay->channelNo()    // 跨境通路交易序號:'NO0000000001'
}

if ($result->hasEsunWallet()) {
    $esunWallet = $result->esunWallet();
    $esunWallet->payAmt()     // 實際付款金額:120
    $esunWallet->redDisAmt()  // 紅利折抵金額:0
}

if ($result->hasTaiwanPay()) {
    $taiwanPay = $result->taiwanPay();
    $taiwanPay->payAmt()  // 實際付款金額:120
}

use Illuminate\Http\Request;
use Ycs77\NewebPay\Facades\NewebPay;

Route::post('/pay/customer', function (Request $request) {
    $result = NewebPay::customer($request);

    if ($result->isFail()) {
        // 取號錯誤...
        return;
    }

    // 自訂取號結果頁面...
});

->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: [
        ...
        '/pay/customer',
    ]);
})

$result = NewebPay::customer($request);
$result->merchantID()   // 藍新金流商店代號:'MS3311...'
$result->amount()       // 交易金額:120
$result->tradeNo()      // 藍新金流交易序號:'23061500000000000'
$result->orderNo()      // 商店訂單編號:'1686763446'
$result->paymentType()  // 付款方式:PaymentType::BARCODE
$result->expireTime()   // 繳費截止日期:Carbon 實例

if ($result->hasAtm()) {
    $atm = $result->atm();
    $atm->bankCode()  // 金融機構代碼:'007'
    $atm->codeNo()    // 繳費代碼:'TestAccount12345'
}

if ($result->hasStoreCode()) {
    $storeCode = $result->storeCode();
    $storeCode->codeNo()  // 繳費代碼:'TEST1234567890'
}

if ($result->hasStoreBarcode()) {
    $storeBarcode = $result->storeBarcode();
    $storeBarcode->barcode1()  // 繳費條碼第一段條碼:'TEST1'
    $storeBarcode->barcode2()  // 繳費條碼第二段條碼:'TEST2'
    $storeBarcode->barcode3()  // 繳費條碼第三段條碼:'TEST3'
}

if ($result->hasLgs()) {
    $lgs = $result->lgs();
    $lgs->storeCode()    // 超商門市編號:'019666'
    $lgs->storeName()    // 取貨門市中文名稱:'全家台灣大道店'
    $lgs->storeType()    // 超商類別名稱:'全家'
    $lgs->storeAddr()    // 超商門市地址:'台中市中區台灣大道一段531號'
    $lgs->tradeType()    // 取件交易方式:1(取貨付款)
    $lgs->cvscomName()   // 取貨人姓名:'王小明'
    $lgs->cvscomPhone()  // 取貨人手機號碼:'0900111222'
    $lgs->lgsNo()        // 物流寄件單號:'-'
    $lgs->lgsType()      // 物流型態:LgsType::C2C
}

use Ycs77\NewebPay\Facades\NewebPay;

$result = NewebPay::query()
    ->withOrder('Order001') // 該筆交易的訂單編號
    ->withAmount(1050)      // 該筆交易的金額
    ->get();

$result->merchantID()   // 藍新金流商店代號:'TestMerchantID1234'
$result->orderNo()      // 商店訂單編號:'Order001'
$result->tradeNo()      // 藍新金流交易序號:'23061500000000000'
$result->amount()       // 交易金額:1050
$result->paymentType()  // 付款方式:PaymentType::CREDIT

$result = NewebPay::query()
    ->withOrder('Order001')
    ->withAmount(1050)
    ->forCompositeStore()
    ->get();

if ($result->hasCredit()) {
    $credit = $result->credit();
    $credit->respondCode()        // 金融機構回應碼:'00'
    $credit->auth()               // 授權碼:'222111'
    $credit->ECI()                // ECI 值:''
    $credit->closeAmt()           // 請款金額:120
    $credit->closeStatus()        // 請款狀態:CaptureStatus::NOT_CAPTURED
    $credit->backBalance()        // 可退款餘額:120
    $credit->backStatus()         // 退款狀態:RefundStatus::NOT_REFUNDED
    $credit->respondMsg()         // 授權結果訊息:'授權測試'
    $credit->inst()               // 分期-期別:0
    $credit->instFirst()          // 分期-首期金額:0
    $credit->instEach()           // 分期-每期金額:0
    $credit->paymentMethod()      // 交易類別:'CREDIT'
    $credit->paymentMethodName()  // 交易類別中文名稱:'台灣發卡機構核發之信用卡'
    $credit->card6No()            // 卡號前六碼:'400022'
    $credit->card4No()            // 卡號末四碼:'1111'
    $credit->authBank()           // 收單金融機構:'CTBC'
    $credit->authBankName()       // 收單金融機構中文名稱:'中國信託銀行'
}

if ($result->hasPaymentStatus()) {
    $paymentStatus = $result->paymentStatus();
    $paymentStatus->payInfo()      // 付款資訊:'(822)12345678901234'
    $paymentStatus->expireDate()   // 繳費有效期限:'2023-01-02 23:59:59'
    $paymentStatus->orderStatus()  // 交易狀態:OrderStatus::UNPAID
}

if ($result->hasLgs()) {
    $lgs = $result->lgs();
    $lgs->storeCode()  // 超商門市編號:'019666'
    $lgs->storeName()  // 取貨門市中文名稱:'全家台灣大道店'
    $lgs->storeType()  // 超商類別名稱:'全家'
    $lgs->lgsNo()      // 物流訂單編號:'LGS23061500000001'
    $lgs->lgsType()    // 物流型態:LgsType::C2C
}

if ($result->hasDigitalWallet()) {
    $digitalWallet = $result->digitalWallet();
    $digitalWallet->respondCode()        // 金融機構回應碼:'00'
    $digitalWallet->closeAmt()           // 請款金額:120
    $digitalWallet->closeStatus()        // 請款狀態:CaptureStatus::NOT_CAPTURED
    $digitalWallet->backBalance()        // 可退款餘額:120(LINE Pay 不支援)
    $digitalWallet->backStatus()         // 退款狀態:RefundStatus::NOT_REFUNDED
    $digitalWallet->respondMsg()         // 授權結果訊息:'交易成功'
    $digitalWallet->paymentMethod()      // 交易類別:PaymentType::LINEPAY
    $digitalWallet->paymentMethodName()  // 交易類別中文名稱:'LINE Pay 付款'
    $digitalWallet->authBank()           // 收單金融機構:'Linepay'
    $digitalWallet->authBankName()       // 收單金融機構中文名稱:'LINE Pay'
}

if ($result->hasBNPL()) {
    $bnpl = $result->BNPL();
    $bnpl->respondCode()        // 金融機構回應碼:'00'
    $bnpl->respondMsg()         // 授權結果訊息:'交易成功'
    $bnpl->closeAmt()           // 請款金額:120
    $bnpl->closeStatus()        // 請款狀態:BNPLCaptureStatus::NOT_CAPTURED
    $bnpl->backBalance()        // 可退款餘額:120
    $bnpl->backStatus()         // 退款狀態:BNPLRefundStatus::NOT_REFUNDED
    $bnpl->inst()               // 分期期別:0(一次付清)
    $bnpl->paymentMethod()      // 交易類別:PaymentType::AFTEE
    $bnpl->paymentMethodName()  // 交易類別中文名稱:'AFTEE 先享後付'
}

use Ycs77\NewebPay\Facades\NewebPay;

$result = NewebPay::creditCard()
    ->reverse()
    ->withOrder('Order001') // 該筆交易的訂單編號
    ->withAmount(1050)      // 該筆交易的金額
    ->send();

$result->merchantID()  // 藍新金流商店代號:'TestMerchantID1234'
$result->orderNo()     // 商店訂單編號:'Order001'
$result->tradeNo()     // 藍新金流交易序號:'23061500000000000'
$result->amount()      // 取消授權金額:1050

$result = NewebPay::creditCard()
    ->reverse()
    ->withTrade('23061500000000000') // 藍新金流交易序號
    ->withAmount(1050)
    ->send();

use Ycs77\NewebPay\Facades\NewebPay;

$result = NewebPay::creditCard()
    ->capture()
    ->withOrder('Order001') // 該筆交易的訂單編號
    ->withAmount(1050)      // 該筆交易的金額
    ->send();

$result->merchantID()  // 藍新金流商店代號:'TestMerchantID1234'
$result->orderNo()     // 商店訂單編號:'Order001'
$result->tradeNo()     // 藍新金流交易序號:'23061500000000000'
$result->amount()      // 請款金額:1050

$result = NewebPay::creditCard()
    ->capture()
    ->withOrder('Order001')
    ->withAmount(1050)
    ->reverse() // 取消請款
    ->send();

use Ycs77\NewebPay\Facades\NewebPay;

$result = NewebPay::creditCard()
    ->refund()
    ->withOrder('Order001') // 該筆交易的訂單編號
    ->withAmount(1050)      // 該筆交易的金額
    ->send();

$result->merchantID()  // 藍新金流商店代號:'TestMerchantID1234'
$result->orderNo()     // 商店訂單編號:'Order001'
$result->tradeNo()     // 藍新金流交易序號:'23061500000000000'
$result->amount()      // 退款金額:1050

$result = NewebPay::creditCard()
    ->refund()
    ->withOrder('Order001')
    ->withAmount(1050)
    ->reverse() // 取消退款
    ->send();

use Ycs77\NewebPay\Facades\NewebPay;

Route::post('/subscribe', function () {
    return NewebPay::period()
        ->create()
        ->withOrder('Order'.time())              // 訂單編號
        ->withAmount(120)                        // 交易金額
        ->withItemDescription('我的訂閱制商品')   // 商品名稱
        ->withEmail('[email protected]')          // 付款人信箱
        ->withReturnUrl('/pay/period/callback')  // 前景回傳網址 (Callback)
        ->withNotifyUrl('/pay/period/notify')    // 背景通知網址 (Notify)
        ->everyFewDays(2)                        // 每隔 2 天授權一次
        ->times(3)                               // 共授權 3 次
        ->submit();
});

NewebPay::period()
    ->create()
    ...
    ->everyFewDays(40)
    ->times(1)
    ->submit();

NewebPay::period()
    ->create()
    ...
    ->weekly(7)
    ->times(1)
    ->submit();

NewebPay::period()
    ->create()
    ...
    ->monthly(20)
    ->times(1)
    ->submit();

NewebPay::period()
    ->create()
    ...
    ->yearly(3, 4)
    ->times(1)
    ->submit();

NewebPay::period()
    ->create()
    ...
    ->monthly(4)
    ->times(6)
    ->submit();

NewebPay::period()
    ->create()
    ...
    ->startWithTenDollarAuth()
    ->submit();

NewebPay::period()
    ->create()
    ...
    ->startWithImmediateAuth()
    ->submit();

NewebPay::period()
    ->create()
    ...
    ->startWithoutAuth()
    ->submit();

NewebPay::period()
    ->create()
    ...
    ->firstChargeAt(2023, 3, 1)
    ->submit();

use Illuminate\Http\Request;
use Ycs77\NewebPay\Facades\NewebPay;

Route::post('/pay/period/callback', function (Request $request) {
    $result = NewebPay::periodResult($request);

    if ($result->isFail()) {
        return redirect()->to('/pay')->with('error', $result->message());
    }

    $result->merchantID()         // 藍新金流商店代號:'TestMerchantID1234'
    $result->orderNo()            // 商店訂單編號:'Order001'
    $result->tradeNo()            // 藍新金流交易序號:'23061500000000000'
    $result->periodNo()           // 委託單號:'20200101000000001'
    $result->periodAmount()       // 委託金額:1050
    $result->periodType()         // 委託週期:PeriodType::EVERY_FEW_DAYS(固定天期制)
    $result->authTimes()          // 委託總授權期數:3
    $result->authTime()           // 每期授權時間:10
    $result->dateArray()          // 委託所有授權日期排程:['2020-01-01', '2020-01-11', '2020-01-21']
    $result->cardNo()             // 卡號前六與後四碼:'400000******1111'
    $result->authCode()           // 授權碼:'123456'
    $result->respondCode()        // 銀行回應碼:'00'
    $result->escrowBank()         // 款項保管銀行:'HNCB'
    $result->authBank()           // 收單金融機構:'CTBC'
    $result->authBankName()       // 收單金融機構中文名稱:'中國信託銀行'
    $result->paymentMethod()      // 交易類別:'CREDIT'
    $result->paymentMethodName()  // 交易類別中文名稱:'台灣發卡機構核發之信用卡'

    return redirect()->to('/pay')->with('success', '付款成功');
});

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Ycs77\NewebPay\Facades\NewebPay;

Route::post('/pay/period/notify', function (Request $request) {
    $result = NewebPay::periodNotify($request);

    if ($result->isFail()) {
        Log::error('藍新金流 定期定額 定期交易錯誤', $result->toArray());

        return;
    }

    $result->merchantID()         // 藍新金流商店代號:'TestMerchantID1234'
    $result->orderNo()            // 商店訂單編號:'Order001'
    $result->tradeNo()            // 藍新金流交易序號:'23061500000000000'
    $result->periodNo()           // 委託單號:'20200101000000001'
    $result->authAmount()       // 委託單本期授權金額:300
    $result->authDate()          // 委託之本期授權時間:'2020-01-01'
    $result->totalTimes()          // 委託之總授權期數:3
    $result->alreadyTimes()          // 委託之已授權期數,包含授權失敗期數:1
    $result->authCode()           // 授權碼:'123456'
    $result->escrowBank()         // 款項保管銀行:'HNCB'
    $result->authBank()           // 收單金融機構:'CTBC'
    $result->authBankName()       // 收單金融機構中文名稱:'中國信託銀行'
    $result->nextAuthDate()                 // 下期委託授權日期:'2020-01-11'

    // 委託授權成功,處理訂單邏輯...
});

->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: [
        ...
        '/pay/period/callback',
        '/pay/period/notify',
    ]);
})

use Ycs77\NewebPay\Facades\NewebPay;

$result = NewebPay::period()
    ->alterStatus()
    ->withOrder('Order001')                // 訂單編號
    ->withPeriod('20200101000000001')       // 委託單號
    ->terminate();                         // 終止委託

$result->orderNo()       // 商店訂單編號:'Order001'
$result->periodNo()      // 委託單號:'20200101000000001'
$result->periodStatus()  // 委託狀態:PeriodStatus::TERMINATE

$result = NewebPay::period()
    ->alterStatus()
    ->withOrder('Order001')
    ->withPeriod('20200101000000001')
    ->suspend(); // 暫停委託

$result = NewebPay::period()
    ->alterStatus()
    ->withOrder('Order001')
    ->withPeriod('20200101000000001')
    ->resume(); // 重新啟用委託

use Ycs77\NewebPay\Facades\NewebPay;

$result = NewebPay::period()
    ->alter()
    ->withOrder('Order001')            // 訂單編號
    ->withPeriod('20200101000000001')  // 委託單號
    ->withAmount(1000)                 // 新的委託金額
    ->everyFewDays(3)                  // 新的授權週期
    ->times(10)                        // 新的授權次數
    ->send();

$result->orderNo()       // 商店訂單編號:'Order001'
$result->periodNo()      // 委託單號:'20200101000000001'
$result->periodAmount()  // 新的委託金額:1000

use Ycs77\NewebPay\Exceptions\NewebPayException;

try {
    $result = NewebPay::query()
        ->withOrder('Order001')
        ->withAmount(1050)
        ->get();
} catch (NewebPayException $e) {
    $status = $e->getApiStatus();    // 'MPG01001'
    $message = $e->getApiMessage();  // '商店代號不存在'

    // 記錄錯誤日誌...
    logger()->error($e->getMessage(), $e->context());

    // 顯示錯誤訊息給使用者...
    return response()->json([
        'error' => $message,
    ], 400);
}



use Ycs77\NewebPay\Facades\NewebPay;
use Ycs77\NewebPay\Options\Trade\QueryOptions;
use Ycs77\NewebPay\Resources\PaymentQuery;
use Ycs77\NewebPay\Results\Trade\QueryResult;

test('can query trade', function () {
    // 模擬交易查詢 API 回應
    NewebPay::fake([
        // 模擬交易查詢回應
        // 需要使用實際呼叫的 Result 類別來建立模擬回應
        //
        // 因為下面使用 NewebPay::query()->get() 來查詢交易
        // 因此模擬的回應類別需要使用 QueryResult 類別
        QueryResult::make([
            'Status' => 'SUCCESS',
            'Message' => '查詢成功',
            'Result' => [
                'MerchantID' => 'TestMerchantID1234',
                'Amt' => 1050,
                'TradeNo' => '23061500000000000',
                'MerchantOrderNo' => 'Order001',
                'TradeStatus' => '1',
                'PaymentType' => 'CREDIT',
                'CreateTime' => '2023-01-01 00:00:00',
                'PayTime' => '2023-01-01 00:00:00',
                'CheckCode' => '123456789',
                'FundTime' => '2023-01-01',
                'RespondCode' => '00',
                'Auth' => '222111',
                'ECI' => '',
                'CloseAmt' => 120,
                'CloseStatus' => 0,
                'BackBalance' => 120,
                'BackStatus' => 0,
                'RespondMsg' => '授權測試',
                'Inst' => 0,
                'InstFirst' => 0,
                'InstEach' => 0,
                'PaymentMethod' => 'CREDIT',
                'Card6No' => '400022',
                'Card4No' => '1111',
                'AuthBank' => 'CTBC',
            ],
        ]),
    ]);

    // 測試發送交易查詢請求
    $result = NewebPay::query()
        ->withOrder('Order001')
        ->withAmount(1050)
        ->get();

    // 斷言發送參數
    //
    // 因為上面是呼叫 NewebPay::query()
    //
    // 因此斷言的資源類別和方法名稱分別是:
    // - PaymentQuery::class 是 query() 方法回傳的資源類別
    // - 'query' 是呼叫的方法名稱
    NewebPay::assertSent(PaymentQuery::class, 'query', function (QueryOptions $options) {
        return $options->orderNo === 'Order001'
            && $options->amount === 1050;
    });

    expect($result->orderNo())->toBe('Order001')
        ->and($result->tradeNo())->toBe('23061500000000000')
        ->and($result->amount())->toBe(1050);
});

use Ycs77\NewebPay\Facades\NewebPay;
use Ycs77\NewebPay\Options\CreditCard\CaptureOptions;
use Ycs77\NewebPay\Resources\CreditCard;
use Ycs77\NewebPay\Results\CreditCard\CaptureResult;

test('can capture credit card', function () {
    NewebPay::fake([
        CaptureResult::make([
            'Status' => 'SUCCESS',
            'Message' => '請款成功',
            'Result' => [
                'MerchantID' => 'TestMerchantID1234',
                'Amt' => 1050,
                'TradeNo' => '23061500000000000',
                'MerchantOrderNo' => 'Order001',
            ],
        ]),
    ]);

    $result = NewebPay::creditCard()
        ->capture()
        ->withOrder('Order001')
        ->withAmount(1050)
        ->send();

    NewebPay::assertSent(CreditCard::class, 'capture', function (CaptureOptions $options) {
        return $options->orderNo === 'Order001'
            && $options->amount === 1050
            && $options->reverse === false;
    });

    expect($result->orderNo())->toBe('Order001')
        ->and($result->amount())->toBe(1050);
});

use Ycs77\NewebPay\Options\Options;

$result = NewebPay::query()
    ->withOrder('Order001')
    ->withAmount(1050)
    ->onPreparedOptions(function (Options $options) {
        dd($options->toArray()); // 查看請求參數資料
    })
    ->get();

dd($result->toArray()); // 查看回應資料
bash
php artisan vendor:publish --tag=newebpay-config
html
<form action="/pay" method="POST">
    @csrf
    <button>付款</button>
</form>
html
<form action="/subscribe" method="POST">
    @csrf
    <button>訂閱</button>
</form>