Code Monkey home page Code Monkey logo

laravel-ecpay's Introduction

Total Downloads Latest Stable Version License

Laravel ECPay

Laravel ECPay 為串接綠界的非官方套件

系統需求

  • v3.x
    • PHP >= 8.0
    • Laravel >= 9.0
  • v2.x
    • PHP >= 7.2 且 < 8.0
    • Laravel < 9 且 >= 6.0
  • v1.x (不維護更新)
    • PHP >= 7 且 < 8.0
    • Laravel < 6.0 且 >= 5.7

安裝

composer require tsaiyihua/laravel-ecpay

環境設定

php artisan vendor:publish --tag=ecpay

這裡會將設定檔 ecpay.php 複製一份到 config 的目錄下。

.env 裡加入

ECPAY_MERCHANT_ID=
ECPAY_HASH_KEY=
ECPAY_HASH_IV=
ECPAY_INVOICE_HASH_KEY=
ECPAY_INVOICE_HASH_IV=
  • 金流測試用的參數值請參考介接文件 ecpay_gw_p110.pdf 第11頁。
  • 查詢發票用的參數請請參考介接文件 ecpay_004.pdf 第6頁。

用法

基本用法

  • 產品資料單筆時可簡單只傳送 ItemName 及 TotalAmount
use TsaiYiHua\ECPay\Checkout;

class CheckoutController extends Controller
{
    protected $checkout;
    
    public function __construct(Checkout $checkout)
    {
        $this->checkout = $checkout;
    }

    public function sendOrder()
    {
        $formData = [
            'UserId' => 1, // 用戶ID , Optional
            'ItemDescription' => '產品簡介',
            'ItemName' => 'Product Name',
            'TotalAmount' => '2000',
            'PaymentMethod' => 'Credit', // ALL, Credit, ATM, WebATM
        ];
        return $this->checkout->setPostData($formData)->send();
    }

需要分期付款時

  • 加上 withInstallment(分期期數)
  • 信用卡分期可用參數為:3,6,12,18,24
  • ex: 3,6 範例
    承上,在 return 時,加上 withInstallment 即可
    return $this->checkout->setPostData($formData)->withInstallment('3,6')->send();

定期定額扣款

  • 加上 withPeriodAmount($periodAmt)
範例
承上,加上參數,帶入 withPeriodAmount 即可
...
    $periodAmt = [
        'PeriodAmount' => 2550,
        'PeriodType' => 'M',
        'Frequency' => '1',
        'ExecTimes' => 10,
        'PeriodReturnURL'
    ];
    return $this->checkout->setPostData($formData)->withPeriodAmount($periodAmt)->send();

需要開立發票時

  • 加上 withInvoice($invData) 即可。
  • 開立發票時,產品內容必須要符合即定格式傳送,不能只帶 ItemName 及 TotalAmount
  • 開立發票時,特店必須要有會員系統並傳送會員相關資料
  • 測試開立發票時,MerchantID 請設 2000132
範例
use TsaiYiHua\ECPay\Checkout;

class CheckoutController extends Controller
{
    protected $checkout;
    
    public function __construct(Checkout $checkout)
    {
        $this->checkout = $checkout;
    }

    public function sendOrder()
    {
        $items[0] = [
            'name' => '產品333',
            'qty' => '3',
            'unit' => '個',
            'price' => '150'
        ];
        $formData = [
            'itemDescription' => '產品簡介',
            'items' => $items,
            'paymentMethod' => 'Credit',
            'userId' => 1
        ];
        $invData = [
            'Items' => $items,
            'UserId' => 1,
            'CustomerName' => 'User Name',
            'CustomerAddr' => 'ABC 123',
            'CustomerEmail' => 'email@address'
        ];
        return $this->checkout->setPostData($formData)->withInvoice($invData)->send();
    }

查詢訂單

use TsaiYiHua\ECPay\QueryTradeInfo;

class QueryTradeController extends Controller
{
    protected $queryTradeInfo;
    
    public function __construct(QueryTradeInfo $queryTradeInfo)
    {
        $this->queryTradeInfo = $queryTradeInfo;
    }
    
    public function queryInfo($orderId)
    {
        return $this->queryTradeInfo->getData($orderId)->query();
    }
}

查詢發票

use TsaiYiHua\ECPay\QueryInvoice;

class QueryInvoiceController extends Controller
{
    protected $queryInvoice;

    public function __construct(QueryInvoice $queryInvoice)
    {
        $this->queryInvoice = $queryInvoice;
    }

    public function queryInvInfo($orderId)
    {
        return $this->queryInvoice->getData($orderId)->query();
    }
}

開立發票

use TsaiYiHua\ECPay\Invoice;
use TsaiYiHua\ECPay\Constants\ECPayDonation;
use TsaiYiHua\ECPay\Services\StringService;

class InvoiceController extends Controller
{
    public function __construct(Invoice $invoice)
    {
        $this->invoice = $invoice;
    }

    public function issueInvoice()
    {
        $itemData[] = [
            'name' => 'product name',
            'qty' => 1,
            'unit' => 'piece',
            'price' => 5000
        ];
        $invData = [
            'UserId' => 1,
            'Items' => $itemData,
            'CustomerName' => 'User Name',
            'CustomerEmail' => '[email protected]',
            'CustomerPhone' => '0912345678',
            'OrderId' => StringService::identifyNumberGenerator('O'),
            'Donation' => ECPayDonation::Yes,
            'LoveCode' => 168001,
            'Print' => 0,
            'CarruerType' => 1
        ];
        return $this->invoice->setPostData($invData)->send();
    }
}

套件中有設定和綠界溝通用的route及基本處理方法,如果要有自己的處理邏輯要用自己寫好的route,擔心和套件原設定的route衝突時

  • 在 app/Http/Providers/AppServiceProvider 的 register 加入
ECPay::ignoreRoutes();

如果要用自己傳送資料的頁面

  • 方法一: 在 .env 裡使用 ECPAY_SEND_FORM 的環境變數來指定。
  • 方法二: 直接指定 ECPay::$sendForm 的值來指定。

所有文件列的參數基本上都可用,參數用法請參考綠界串接文件

  • 回傳參數的背景通知(ReturnURL),套件裡有預設的網址,但只止於通知,如果要有寫入資料庫的設計,要再設計自己的回傳通知網址。
  • OrderResultURL 為結帳完返回自已站台的網址,不能與 ReturnURL 相同。

參考文件

  • 綠界科技全方位金流信用卡介接技術文件 (2021-08-19)
    • V 5.2.8
    • 文件編號 gw_p110
    • 文件位置 documents/ecpay_gw_p110.pdf
  • 綠界科技B2C電子發票介接技術文件 (2022-01-03)
    • V 3.6.4
    • 文件編號 gw_i100
    • 文件位置 documents/ecpay_004.pdf
  • 綠界科技全方位金流介接技術文件 (2021-11-30)
    • V 5.3.11
    • 文件編號 gw_p100
    • 文件位置 documents/ecpay_011.pdf

laravel-ecpay's People

Contributors

tsaiyihua avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

laravel-ecpay's Issues

查詢訂單問題

當我使用範例如:
$formData = ['orderId'=>'O154320382117474878'];
return $this->queryTradeInfo->getData($formData)->query();.
顯示錯誤
Array to string conversion在StringService.php 的$checkCodeStr .= '&'.$key.'='.$val;

我嘗試做一些修正,但顯示
ECPayException
HTTP Error with code 0

想請教如何修正才能正確查詢訂單內容?

開放PostData資料取得

能否開放PostData取得?

例如:

// 取得PostData資料 (取得後另作彈性用途,例如保存成Log等等)
$getPostData = $this->ecpayCheckout->setPostData($formData)->getPostData();

// 送出
$this->ecpayCheckout->send();

About setting MerchantTradeDate

請問交易時間可以開放自訂嗎?

例如說程式與資料庫分兩台主機,
可能需要以資料庫時間為主,
那就有這個需求,謝謝。

結帳開立發票無法正常。

    public function sendOrder(Request $r)
    {
        $cartList = session()->get('cart.pid');
        if (Session::has('cart.pid') && count($cartList)) {
            $productList = product::find($cartList);
        }
        $total     = 0;
        $certCount = 0;
        foreach ($productList as $key => $value) {
            $qty = $r['qty.' . $value->id];
            $total += $value->price * $qty;
            $ItemName[] = "{$value->name}($ {$value->price})×{$qty}";
            $items[]    = [
                'pid'   => $value->id,
                'name'  => $value->name,
                'qty'   => $qty,
                'unit'  => '張',
                'price' => $value->price,
            ];
            $certCount += $qty;
        }
        $couponDiscount = 0;
        $off            = 100;
        $orderNumber        = Str::padLeft(Auth::guard('web')->user()->id, 5, 0) . strtoupper(date('yMdhis'));
        $formData = [
            'OrderId'         => $orderNumber,
            'UserId'          => Auth::user()->id,
            'ItemDescription' => implode('#', $ItemName),
            'ItemName'        => implode('#', $ItemName),
            'items'           => $items,
            'TotalAmount'     => $total,
            'PaymentMethod'   => 'ALL', // ALL, Credit, ATM, WebATM
            'ReturnURL'       => route('ecpay.notify'),
            'ClientBackURL'   => route('ecpay.return'),
            'InvoiceMark'     => "Y",
        ];

        $invData = [
            'Items'         => $items,
            'UserId'        => Auth::user()->id,
            'CustomerName'  => Auth::user()->familyName . Auth::user()->givenName,
            'CustomerAddr'  => Auth::user()->mergeAddress,
            'CustomerEmail' => Auth::user()->email,
            'Donation'      => ECPayDonation::No,
            'Print'         => 0,
            'CarruerType'   => 1,
        ];

        return $this->checkout->setNotifyUrl(route('ecpay.notify'))->setPostData($formData)->withInvoice($invData)->send();
    }

能正常完成綠界結帳流程,但不會開立發票。

Undefined index: UserId

環境:
Laravel 5.8 homestead

按照範例使用時
呼叫 $this->checkout->setPostData($formData)->send();

出現錯誤 Undefined index: UserId
CheckoutPostCollection.php function optimize() 126行

想請問如何處理

關於取得 MerchantTradeNo

想請問
return $this->checkout->setPostData($formData)->send(); 之前
會建立一筆訂單資料在資料庫,這時候會需要 MerchantTradeNo
以便在收到綠界扣款通知時,可以拿 MerchantTradeNo 去更改該筆訂單狀態

MerchantTradeNo 的產生是包在 setBasicInfo()
但目前很像沒提供外部可以拿到的方法

CustomerIdentifier 驗證

src/Validations/InvoiceValidation.php

$validator = Validator::make($data, [
            'Items' => 'required|array',
            'OrderId' => 'alpha_num|max:30',
            'CustomerID' => 'alpha_dash|max:20',
            'CustomerIdentifier' => 'int|max:8', <-----此處被驗證為小於8
            'CustomerName' => 'required_if:Print,1|max:60',
            'CustomerAddr' => 'required_if:Print,1|max:200',
            'CustomerPhone' => 'required_if:CustomerEmail,null|max:20',
            'CustomerEmail' => 'required_if:CustomerPhone,null|max:200',
            'ClearanceMark' => 'in:'.implode(',', ECPayClearanceMark::getConstantValues()->toArray()),
            'TaxType' => 'in:'.implode(',', ECPayTaxType::getConstantValues()->toArray()),
            'CarruerType' => 'in:'.implode(',', ECPayCarruerType::getConstantValues()->toArray()),
            'CarruerNum' => 'max:64',
            'Donation' => 'in:'.implode(',', ECPayDonation::getConstantValues()->toArray()),
            'LoveCode' => 'required_if:Donation,1|max:7',
            'Print' => 'in:'.implode(',', ECPayPrintMark::getConstantValues()->toArray()),
            'DelayDay' => 'int|min:0|max:15',
            'InvType' => 'in:'.implode(',', ECPayInvType::getConstantValues()->toArray())
        ]);

composer install因中文檔名解壓失敗

執行composer install會因帶有中文名稱檔案解壓失敗,是否方便將文件B2C電子發票介接技術文件.pdf改為英文名稱呢?感謝!

  - Downloading tsaiyihua/laravel-ecpay (2.4.1)
  - Installing tsaiyihua/laravel-ecpay (2.4.1): Extracting archive
    Install of tsaiyihua/laravel-ecpay failed

  [RuntimeException]                                                          
  Failed to extract tsaiyihua/laravel-ecpay: (50) unzip -qq -o '/Path/to/my/project/vendor/composer/tmp-be59cf6afb2c62a561e3640d4061341  
  e' -d '/Path/to/my/project/vendor/composer/d98d78ca'        
                                                                               
  error:  cannot create /Path/to/my/project/vendor/composer/  
  d98d78ca/tsaiyihua-laravel-ecpay-f5eead2/documents/B2C??+?????+????+???????  
  ???????+?.pdf                                                                
          Illegal byte sequence                                                

InvoicePostCollection can`t get Checkout`s MerchantTradeNo

InvoicePostCollection.php Line 70-71
Need to change to
$this->put('RelateNumber', $this->attributes['MerchantTradeNo']??StringService::identifyNumberGenerator('O'));

InvoicePostCollection.php Line 189
Need to change to
$this->put('RelateNumber', $this->attributes['MerchantTradeNo']??StringService::identifyNumberGenerator('O'));

退款問題

非常感謝您提供這個好用的套件省下很多介接綠界金流的時間

想請問下,不知道是否也可以提供退款的範例呢?
謝謝您

取不到 MerchantID 值

    public function test()
    {
        $formData = [
            'UserId' => 1, // 用戶ID , Optional
            'ItemDescription' => '產品簡介',
            'ItemName' => 'Product Name',
            'TotalAmount' => '2000',
            'PaymentMethod' => 'Credit', // ALL, Credit, ATM, WebATM
        ];
        dd($this->checkout->setPostData($formData));

        return $this->checkout->setPostData($formData)->send();
    }

結果

Checkout {#470 ▼
  #apiUrl: "https://payment-stage.ecpay.com.tw/Cashier/AioCheckOut/V5"
  #postData: CheckoutPostCollection {#471 ▼
    +merchantId: null
    +attributes: array:5 [▼
      "UserId" => 1
      "ItemDescription" => "產品簡介"
      "ItemName" => "Product Name"
      "TotalAmount" => "2000"
      "PaymentMethod" => "Credit"
    ]
    +notifyUrl: "https://www.test.com.tw/ecpay/notify"
    +returnUrl: "https://www.test.com.tw/ecpay/return"
    #items: array:13 [▼
      "MerchantID" => null
      "MerchantTradeDate" => "2019/11/07 21:29:13"
      "PaymentType" => "aio"
      "ReturnURL" => "https://www.test.com.tw/ecpay/notify"
      "OrderResultURL" => "https://www.test.com.tw/ecpay/return"
      "ChoosePayment" => "Credit"
      "EncryptType" => 1
      "MerchantTradeNo" => "O157313335304085837"
      "TotalAmount" => "2000"
      "TradeDesc" => "%E7%94%A2%E5%93%81%E7%B0%A1%E4%BB%8B"
      "ItemName" => "Product Name"
      "BindingCard" => 0
      "MerchantMemberID" => "1"
    ]
  }
  #platform: null
  #merchantId: null
  #hashKey: null
  #hashIv: null
  #encryptType: "sha256"
  #notifyUrl: null
  #itemValidation: null
}

2.4.9 的 Laravel 相依性是 9.0

2.4.9 修正了 Donation 不應等於 2 的問題
但是相依性變成了 "laravel/framework": "^9.0"
有機會改成 2.4.8 的 "laravel/framework": "^6|7.30.4|^8.40.0" ?

About setting returnUrl and notifyUrl

想請問
我去設置了自己的 return url 和 notify url
return $this->checkout->setNotifyUrl(route('notify'))->setReturnUrl(route('return'))->setPostData($formData)->send();

輸入卡號與手機驗證碼後,成功轉回自己的網站 /return 時,出現 419逾時
我看 Log notify 和 return 都沒成功進入的樣子

我這邊的理解
notify 應該會收到綠界回傳的 post date,然後我們要回傳 ok
return 則是綠界會導到該頁,讓站方可以秀結帳成功的畫面

但不知道哪個環節有問題?導致這個狀況發生
再麻煩了,需要更多資訊的話我再提供
感謝

關於超商付款的回傳值

先感謝作者大大的分享。

目前遇到使用超商條碼或ATM 付款成功後沒有回寫到資料庫,但是信用卡刷卡又是正常,一直找不出原因,想請大大指點迷津XD

process_return 例外處理發生錯誤

hi 你好

在執行 ECPay_INVOICE_VOID 這個服務時

因為 /Invoice/IssueInvalid 這支API 不會回傳Reason 參數

所以當Request/Response 共用 checkException時

會發生 $arParameters['Reason'] is not defined 的錯誤 :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.