PHP接入PayPal教程

在这里插入图片描述

参考:https://learnku.com/articles/26282
SDK地址: http://paypal.github.io/PayPal-PHP-SDK/

步骤

1.注册账号 认证 直到能正常转账
2.下载SDK
3.撸代码 沙盒测试
4.正式环境测试

1.注册账号

商家控制台:
https://developer.paypal.com
开发者中心:
https://developer.paypal.com/developer/accounts/

注意:看文档可以挂梯子,进控制台不要,不然会打不开。

创建沙盒账号

默认会带两个的,一个商家一个私人。
在这里插入图片描述
改密码:
PHP接入PayPal教程_第1张图片

获取ID和Secret

PHP接入PayPal教程_第2张图片
以上步骤不会的可以多点点,然后翻译下网页,我相信你可以的。

2.下载SDK

首先你要会composer
https://docs.phpcomposer.com/00-intro.html
composer.json加入:

"alibabacloud/sdk": "^1.8",
"paypal/rest-api-sdk-php":

然后

composer update

3. 开始撸代码

PayPal = new ApiContext(
            new OAuthTokenCredential(
                self::clientId,
                self::clientSecret
            )
        );

        //开线上用这里
        $this->PayPal->setConfig([
            'mode' => 'live',
        ]);
    }

    /**
     * @param
     * $product 商品
     * $price 价钱
     * $shipping 运费
     * $description 描述内容
     */
    public function pay($userid, $price,$shipping) {

        $ip    = get_real_ip(); //获取IP
        $order = get_order_no(); //生成随机数

        //业务逻辑:生成订单表

        $product     = '商品1';
        $description = '商品1';
        $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&paymemtRecordID={ 订单表ID }&orderId=$order")
                     ->setCancelUrl(self::accept_url . "/?success=false&paymemtRecordID={ 订单表ID }&orderId=$order");

        $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();
        
        return $approvalUrl;
    }

    /**
     * 回调
     * @param Request $request
     * @return void
     */
    public function Callback() {
        BLog::pay("paypal 收到回调 " . json_encode($_GET));
        //var_dump($_SERVER['HTTP_HOST']);


        $tPaymentRecordId = $_GET['paymemtRecordID'];
        $appOrderNO       = $_GET['orderId'];

        //业务逻辑,查询订单表
     
        if (!$p) {
            BLog::pay("回调:记录没找着:$tPaymentRecordId:$appOrderNO");
            echo "fail";
            return;
        }

        $success = trim($_GET['success']);

        if ($success == 'false' && !isset($_GET['paymentId']) && !isset($_GET['PayerID'])) {
            echo '取消付款';
            BLog::pay("paypal 取消付款");
            return;
        }

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

        if (!isset($success, $paymentId, $PayerID)) {
            BLog::pay("paypal 支付失败");
            echo '支付失败';
            return;
        }

        if ((bool)$_GET['success'] === 'false') {
            $log = '支付失败,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';
            BLog::pay("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 . '】';
            BLog::pay("paypal 支付失败 $log");
            echo $log;
            return;
        }
        $log = '支付成功,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';
        BLog::pay("paypal 支付失败 $log");
        echo $log;

        //业务逻辑,支付成功

        //跳转支付成功后的地址,看业务
        header("Location: **** ");

        exit;

    }
}

4.线上测试

上面代码中的

  $this->PayPal->setConfig([
            'mode' => 'live',
   ]);

你可能感兴趣的:(PHP)