欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

php 使用PayPal 支付

程序员文章站 2022-06-12 19:38:32
...

paypal 一共有三种支付方式,我使用的是服务器集成方式。

这里是介绍 :https://developer.paypal.com/docs/checkout/?mark=Express%20Checkout#integration-options

沙盒测试:

登录paypal的开发者地址: https://developer.paypal.com

创建沙盒测试账户(注册时会自动生成一个个人账户和商家账户,如果不能使用就自己创建几个):https://developer.paypal.com/developer/accounts/

创建好之后去创建一个APP,用一个沙盒测试的商家用户来创建App

https://developer.paypal.com/developer/applications/

点击test1,我们会看到沙盒测试的账号、Client ID、点击show按钮会看到 Secret,Live 就是你正式上线后的**和账号

然后我们去下载php用的包文件

https://github.com/paypal/PayPal-PHP-SDK/releases

闲话不多说直接上代码了:

<?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 . '】');
    }
 
 
}

下面是php-sdk文档的地址:

http://paypal.github.io/PayPal-PHP-SDK/

沙盒测试:

https://www.sandbox.paypal.com #沙盒测试账号登陆地址

请上创建的沙盒测试个人用户查看消费的记录

请上用来创建APP的沙盒测试商家用户来查看进账记录

相关标签: paypal php