接入 paypal PHP-sdk 支付 / 回撥 / 退款全流程

Double-Jin發表於2019-03-29

記錄一下接入paypal 全過程

因專案的原因要用到國外的支付和國外的信用卡,查了一下paypal就內建了信用卡付款方式,所以只需要接入paypal就能基本滿足專案海外支付的需求。

查了一下文件發現web端可以接入js的支付和服務端sdk的支付,這裡選擇了php-sdk支付

一. 下載sdk

在composer.json中加入 "paypal/rest-api-sdk-php" : "1.7.4"

接入 paypal PHP-sdk 的流程

在命令列中執行 composer update

二. 註冊開發者帳號、建立應用

地址:https://developer.paypal.com

建立沙盒測試賬戶(註冊時會自動生成一個個人賬戶和商家賬戶,如果不能使用就自己建立幾個):https://developer.paypal.com/developer/accounts/

1. 建立應用

接入 paypal PHP-sdk 的流程

2. 獲取應用配置

接入 paypal PHP-sdk 的流程
shndbox為沙盒環境配置,live反之

3. 建立測試帳號

接入 paypal PHP-sdk 的流程

點選create account設定測試帳號金額和密碼

三.程式碼

調起paypal支付

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Exception\PayPalConnectionException;
use PayPal\Rest\ApiContext;
use PayPal\Api\PaymentExecution;

class paypalController extends Controller
{
    const clientId = 'xxxxxxxxx';//ID
    const clientSecret = 'xxxxxxxx';//祕鑰
    const accept_url = 'http://laravel-rbac.cc/Api/paypal/Callback';//返回地址
    const Currency = 'USD';//幣種
    protected $PayPal;

    public function __construct()
    {
        $this->PayPal = new ApiContext(
            new OAuthTokenCredential(
                self::clientId,
                self::clientSecret
            )
        );
        //如果是沙盒測試環境不設定,請註釋掉
//        $this->PayPal->setConfig(
//            array(
//                'mode' => 'live',
//            )
//        );
    }

    /**
     * @param
     * $product 商品
     * $price 價錢
     * $shipping 運費
     * $description 描述內容
     */
    public function pay()
    {
        $product = '1123';
        $price = 1;
        $shipping = 0;
        $description = '1123123';
        $paypal = $this->PayPal;
        $total = $price + $shipping;//總價

        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $item = new Item();
        $item->setName($product)->setCurrency(self::Currency)->setQuantity(1)->setPrice($price);

        $itemList = new ItemList();
        $itemList->setItems([$item]);

        $details = new Details();
        $details->setShipping($shipping)->setSubtotal($price);

        $amount = new Amount();
        $amount->setCurrency(self::Currency)->setTotal($total)->setDetails($details);

        $transaction = new Transaction();
        $transaction->setAmount($amount)->setItemList($itemList)->setDescription($description)->setInvoiceNumber(uniqid());

        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl(self::accept_url . '?success=true')->setCancelUrl(self::accept_url . '/?success=false');

        $payment = new Payment();
        $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]);

        try {
            $payment->create($paypal);
        } catch (PayPalConnectionException $e) {
            echo $e->getData();
            die();
        }

        $approvalUrl = $payment->getApprovalLink();
        header("Location: {$approvalUrl}");
    }

接入 paypal PHP-sdk 的流程

同步回撥 - 用於確認使用者是否付款

    /**
     * 回撥
     */
    public function Callback()
    {
        $success = trim($_GET['success']);

        if ($success == 'false' && !isset($_GET['paymentId']) && !isset($_GET['PayerID'])) {
            echo '取消付款';die;
        }

        $paymentId = trim($_GET['paymentId']);
        $PayerID = trim($_GET['PayerID']);

        if (!isset($success, $paymentId, $PayerID)) {
            echo '支付失敗';die;
        }

        if ((bool)$_GET['success'] === 'false') {
            echo  '支付失敗,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';die;
        }

        $payment = Payment::get($paymentId, $this->PayPal);

        $execute = new PaymentExecution();

        $execute->setPayerId($PayerID);

        try {
            $payment->execute($execute, $this->PayPal);
        } catch (Exception $e) {
            echo ',支付失敗,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';die;
        }
        echo '支付成功,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';die;
    }

非同步回撥 - 用於處理業務邏輯

要先在控制皮膚設定回撥地址,必須為Https,設定後要等一會才會生效
接入 paypal PHP-sdk 的流程

  public function notify(){

        //獲取回撥結果
        $json_data = $this->get_JsonData();

        if(!empty($json_data)){
             Log::debug("paypal notify info:\r\n".json_encode($json_data));
        }else{
            Log::debug("paypal notify fail:參加為空");
        }
          //自己列印$json_data的值看有那些是你業務上用到的
          //比如我用到
          $data['invoice'] = $json_data['resource']['invoice_number'];
          $data['txn_id'] = $json_data['resource']['id'];
          $data['total'] = $json_data['resource']['amount']['total'];
          $data['status'] = isset($json_data['status'])?$json_data['status']:'';
          $data['state'] = $json_data['resource']['state'];

        try {
                 //處理相關業務
        } catch (\Exception $e) {
            //記錄錯誤日誌
            Log::error("paypal notify fail:".$e->getMessage());

            return "fail";
        }
        return "success";
    }

    public function get_JsonData(){
        $json = file_get_contents('php://input');
        if ($json) {
            $json = str_replace("'", '', $json);
            $json = json_decode($json,true);
        }
        return $json;
    }

退款

   public function returnMoney()
    {

        try {
            $txn_id = "xxxxxxx";  //非同步加調中拿到的id
            $amt = new Amount();
            $amt->setCurrency('USD')
                ->setTotal('99');  // 退款的費用

            $refund = new Refund();
            $refund->setAmount($amt);

            $sale = new Sale();
            $sale->setId($txn_id);

            $refundedSale = $sale->refund($refund, $this->PayPal);
        } catch (\Exception $e) {
            // PayPal無效退款
            return json_decode(json_encode(['message' => $e->getMessage(), 'code' => $e->getCode(), 'state' => $e->getMessage()]));  // to object
        }
        // 退款完成
        return $refundedSale; 
    }

檢視相關流水

支付成為後到測試帳號裡檢視流水https://www.sandbox.paypal.com/myaccount/home

接入 paypal PHP-sdk 的流程

結語

Paypal 由於是英文文件查了很多部落格結合著文件來做的,下面是
php-sdk文件的地址:
http://paypal.github.io/PayPal-PHP-SDK/

相關文章