1. 程式人生 > >php 使用PayPal 支付

php 使用PayPal 支付

paypal 一共有三種支付方式,我使用的是伺服器整合方式。

沙盒測試:

建立好之後去建立一個APP,用一個沙盒測試的商家使用者來建立App

點選test1,我們會看到沙盒測試的賬號、Client ID、點選show按鈕會看到 Secret,Live 就是你正式上線後的金鑰和賬號

然後我們去下載php用的包檔案

閒話不多說直接上程式碼了:

<?php

namespace app\index\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 Paypal
{
    const clientId = '你的clientId ';//ID

    const clientSecret = '你的clientSecret';//祕鑰

    const accept_url = 'pay.test.com/Paypal/Callback';//返回地址

    const Currency = 'USD';//幣種

    const error_log = 'PayPal-error.log';//錯誤日誌

    const success_log = 'PayPal-success.log';//成功日誌


    protected $PayPal;

    public function __construct()
    {

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

    public function index()
    {
        $product = input('product');
        if (empty($product)) {
            return ajax_return(400, '商品不能為空');
        }

        $price = input('price');
        if (empty($price)) {
            return ajax_return(400, '價格不能為空');
        }

        $shipping = input('shipping', 0);


        $description = input('description');
        if (empty($description)) {
            return ajax_return(400, '描述內容不能為空');
        }

        $this->pay($product, $price, $shipping, $description);
    }

    /**
     * @param
     * $product 商品
     * $price 價錢
     * $shipping 運費
     * $description 描述內容
     */
    public function pay($product, $price, $shipping = 0, $description)
    {
        $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}");
    }

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

        if ($success == 'false' && !isset($_GET['paymentId']) && !isset($_GET['PayerID'])) {
            pay_logs(self::error_log, '取消付款');
            exit();
        }

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

        if (!isset($success, $paymentId, $PayerID)) {
            pay_logs(self::error_log, '支付失敗');
            exit();
        }

        if ((bool)$_GET['success'] === 'false') {
            pay_logs(self::error_log, '支付失敗,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】');
            exit();
        }

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

        $execute = new PaymentExecution();

        $execute->setPayerId($PayerID);

        try {
            $payment->execute($execute, $this->PayPal);
        } catch (Exception $e) {
            pay_logs(self::error_log, $e . ',支付失敗,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】');
            exit();
        }
        pay_logs(self::success_log, '支付成功,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】');
    }


}

Paypal 由於是英文文件,而且比較雜亂,英語又比較渣,藉助了好多部落格結合著文件來做的,下面是php-sdk文件的地址:

沙盒測試:

請上建立的沙盒測試個人使用者檢視消費的記錄

請上用來建立APP的沙盒測試商家使用者來檢視進賬記錄

如果有疑問,請留言,共同進步學習。