PHP 对接paypal支付平台

对接paypal支付平台

【前言】:最近公司需要做一款海外股票的app,其中有需要购买会员权益的一个模块,这里需要国际类型的支付。支付宝及微信在国内比较活跃,国外的话可能不太理想,所以就用了paypal.

<?php
/**
 * @author: xusir
 * @date: 2021/11/24
 * @createTime: 10:09 上午
 * @desc:
 */
namespace Home\Controller;

require_once "Modules/Lib/PayPal-PHP-SDK/autoload.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 PayPal\Api\PaymentExecution;
use PayPal\Exception\PayPalConnectionException;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;


class PayInfoController extends CommonController
{

    const clientId     = '';//app的Client ID
    const clientSecret = '';//app的Secret
    const Currency     = 'USD';//币种
    public static $accept_url   = '';//回调地址

    protected $PayPal;

    public function __construct() {
        self::$accept_url = "http://".$_SERVER['SERVER_NAME'].'/wxapp.php?s=/PayInfo/Callback';//地址
        $this->PayPal = new ApiContext(
            new OAuthTokenCredential(
                self::clientId,
                self::clientSecret
            )
        );

        //设置线上还是沙箱模式
        $this->PayPal->setConfig([
//            'mode' => 'live',
            'mode' => 'sandbox',
        ]);
    }


    /**
     * @param mixed $arg1
     * @author xusir
     * @date: 2021/11/24
     * @createTime: 1:59 下午
     * @remark:
     * $product 商品
     * $price 价钱
     * $shipping 运费
     * $description 描述内容
     */
    public function pay() {
        $request = I("request.");
        $interes_id = $request['interes_id'];
        $price = $request['price'];
        if(!$request['interes_id'] || !$request['price']){
            echo json_encode(['code'=>1,'msg'=>'参数不全']);exit;
        }
        $shipping = 0;
        $order = time().rand("1111,9999");//订单号


        $product     = '会员权益';
        $description = '会员权益';
        $paypal      = $this->PayPal;
        $total       = $price + $shipping;

        //todo 在paypal下单
        $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);

        //todo paypal账户余额详情
        $amount = new Amount();
        $amount->setCurrency(self::Currency)->setTotal($total)->setDetails($details);

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

        //todo 设置回调地址
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl(self::$accept_url . "&success=true&orderId=$order&interes_id=$interes_id")
            ->setCancelUrl(self::$accept_url . "&success=false&orderId=$order");

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

        //异常获取
        try {
            $payment->create($paypal);
        } catch (PayPalConnectionException $e) {
            echo json_encode(['code'=>1,'msg'=>$e->getData()]);exit;
        }
        //返回paypal授权地址
        $approvalUrl = $payment->getApprovalLink();
        echo json_encode(['code'=>0,'msg'=>'success','url'=>$approvalUrl]);exit;
    }

    /**
     * 回调
     * @param Request $request
     * @return void
     */
    public function Callback() {
        $success = trim($_GET['success']);

        if ($success == 'false' && !isset($_GET['paymentId']) && !isset($_GET['PayerID'])) {
            echo json_encode(['code'=>1,'msg'=>'支付失败','data'=>"取消付款"]);exit;
        }

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

        if (!isset($success, $paymentId, $PayerID)) {
            echo json_encode(['code'=>1,'msg'=>"支付失败"]);exit;
        }

        if ((bool)$_GET['success'] === 'false') {
            echo json_encode(['code'=>1,'msg'=>'支付失败']);exit;
        }

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

        $execute = new PaymentExecution();

        $execute->setPayerId($PayerID);

        try {
            $payment->execute($execute, $this->PayPal);
        } catch (\Exception $e) {
            echo json_encode(['code'=>1,'msg'=>$e->getData()]);exit;
        }

        //支付成功后业务处理逻辑
       


       echo json_encode(['code'=>0,'msg'=>'支付成功']);

    }




}



在paypal返回的地址直接web访问就可以进行测试,测试账号填写沙箱的个人账号就可以支付,支付后登录后台就可以看到是否成功付款。
在这里插入图片描述

在这里插入图片描述

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值