PHP实现PayPal支付对接

PHP实现PayPal支付对接

博主搭建成功链接:

充值中心

paypal用户账号密码(密码最后一位是个点):

sb-koedx14427358@personal.example.com

yXm2upL.

Paypal开发者模式注册地址:

PayPal Developer

注册成功后会有黑箱测试程序的clientId和clientSecret:

PHP实现PayPal支付对接

PHP实现PayPal支付对接

获取paypal的黑箱用户支付账户和商家账号:

PHP实现PayPal支付对接

获取账号对应的登录密码:(用户支付时使用,商家查询明细时使用)

PHP实现PayPal支付对接

PHP实现PayPal支付对接

知道了这些信息后,接线来就是码农的ShowTime:

百度出来的PHP都需要用到composer来加载依赖,博主这边使用了后已经将vendor的所有资源整合在一起了,通过文章的下载链接即可部署使用,无需安装composer.。如果你要使用composer来实现,只需要将composer.json文件改为以下内容即可:

{
    "require" : {
        "paypal/rest-api-sdk-php" : "1.13.0"
    }
}

 然后运行:composer install 执行即可

PHP实现PayPal支付对接

 博主使用的PHP中的CI框架,文件夹格式如下:

PHP实现PayPal支付对接

Paypal.php代码:

<?php
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use Illuminate\Http\Request;
use PayPal\Api\Refund;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Exception\PayPalConnectionException;
use PayPal\Api\Sale;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
require "vendor/autoload.php"; //载入sdk的自动加载文件
class Paypal extends CI_Controller {
    const clientId     = 'AfP_eC9BY2YgnxxsimyfautHLoLL0g0nzB1nKv7PoenlbCIroaypXresiVIlZNe4pTAYD3DvIoU7UYid';
    const clientSecret = 'EBKB53uJ0lrCgspuFOMbODcwso1PiKVFWDFrG7tmWluFyzBktmC-3I7YgXlSLAp0g_IDHjeVld9UwAcd';
    const Currency     = 'USD';//币种
    const accept_url   = 'http://pay.tongfawuye.com/paypal/paypal_recharge';//回调地址
    const success_url   = 'http://pay.tongfawuye.com/demo/pay';//支付成功后返回地址
    protected $PayPal;
    function __construct()
    {
        parent::__construct(false);
        $this->load->model('Pay_log_model');
        $this->PayPal = new ApiContext(
            new OAuthTokenCredential(
                self::clientId,
                self::clientSecret
            )
        );
        //黑箱模式下请屏蔽此行代码,生产环境放开即可
        //$this->PayPal->setConfig(['mode' => 'live']);
    }
    /**
     * 手机端网页支付
     */
    public function paypal_detail(){
        $amount = (float)$this->input->get('amount');
        $phone = $this->input->get('phone');
        $address = $this->input->get('address');
        //插入支付日志
        $pay_log = array();
        $pay_log['pay_user'] = $phone;
        $pay_log['name'] = $address;
        $pay_log['amount'] = $amount;
        $pay_log['pay_mode'] = 3;
        $pay_log['add_time'] = time();
        $pay_log['add_time_ymd'] = date("Y-m-d H:i:s");
        $this->Pay_log_model->save($pay_log);
        $log_id = $pay_log['log_id'];
        $product     = $address;
        $description = $address;
        $paypal      = $this->PayPal;
        $total       = $amount;//总价
        $shipping = 0;
        $order = '1001'.date("YmdHis").$log_id;
        $payer = new Payer();
        $payer->setPaymentMethod("paypal");
        $item = new Item();
        $item->setName($product)->setCurrency(self::Currency)->setQuantity(1)->setPrice($total);
        $itemList = new ItemList();
        $itemList->setItems([$item]);
        $details = new Details();
        $details->setShipping($shipping)->setSubtotal($total);
        $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&paymemtRecordID=$log_id&orderId=$order&amount=$total")->setCancelUrl(self::accept_url."?success=false&paymemtRecordID=$log_id&orderId=$order&amount=$total");
        //$redirectUrls->setReturnUrl(self::success_url)->setCancelUrl(self::cancel_url);
        $payment = new Payment();
        $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]);
        try {
            $payment->create($paypal);
        } catch (PayPalConnectionException $e) {
            log_message('error', "POST:" . print_r($e, true));
            echo $e->getData();
            die();
        }
        $approvalUrl = $payment->getApprovalLink();
        header ( 'Location: '.$approvalUrl );
    }
    /**
     * 回调
     * @param Request $request
     * @return void
     */
    public function paypal_recharge() {
        log_message('error', "GET:" . print_r($_GET, true));
        $tPaymentRecordId = trim($_GET['paymemtRecordID']);
        $appOrderNO       = trim($_GET['orderId']);
        //业务逻辑,查询订单表
        $success = trim($_GET['success']);
        if ($success == 'false' && !isset($_GET['paymentId']) && !isset($_GET['PayerID'])) {
            echo '取消付款';
            log_message('error', "paypal 取消付款");
            return;
        }
        $paymentId = trim($_GET['paymentId']);
        $PayerID   = trim($_GET['PayerID']);
        if (!isset($success, $paymentId, $PayerID)) {
            log_message('error', "paypal 支付失败");
            echo '支付失败';
            return;
        }
        if ((bool)$_GET['success'] === 'false') {
            $log = '支付失败,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';
            log_message('error', "paypal 支付失败 $log");
            echo $log;
            return;
        }
        $payment = Payment::get($paymentId, $this->PayPal);
        $execute = new PaymentExecution();
        $execute->setPayerId($PayerID);
        try {
            $payment->execute($execute, $this->PayPal);
        } catch (\Exception $e) {
            $log = '支付失败,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';
            log_message('error', "paypal 支付失败 $log");
            return;
        }
        $log = '支付成功,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';
        log_message('error', "paypal 支付成功 $log");
        //支付成功的后续操作
        $pay_log = $this->Pay_log_model->get_info($tPaymentRecordId);
        if(!empty($pay_log))
        {
            if($pay_log['pay_status'] == 0)
            {
                //修改支付状态
                $log_data = array(
                    'pay_status'=>1,
                    'trade_no'=>$appOrderNO,
                    'pay_trans_id'=>$paymentId,
                    'pay_code'=>$success
                );
                $this->Pay_log_model->save($log_data, $tPaymentRecordId);
            }
        }
        //跳转支付成功后的地址,看业务
        header("Location: ".self::success_url);
        exit;
    }
    /**
     * 回调
     * @param Request $request
     * @return void
     */
    public function paypal_recharge_notify() {
        log_message('error', "GET:" . print_r($_GET, true));
        echo("success");
        exit;
    }
}

 页面上去访问链接即可跳转到paypal支付页面:http://localhost/paypal/paypal_detail?amount=XX&phone=XX&address=XX

PHP实现PayPal支付对接

至于数据库和model等的实现可以看我之前的文章:

PHP支付宝手机网页和PC网页支付对接_我是小木木的博客-CSDN博客

 PHP微信支付JSAPI网页支付Native原生支付_我是小木木的博客-CSDN博客_php 微信native支付

vendor文件资源下载链接:

PHP对接PayPal支付composer生成的vendor所有文件夹-PHP文档类资源-CSDN下载

                       

点击阅读全文

上一篇 2023年 6月 7日 am10:24
下一篇 2023年 6月 7日 am10:25