首页  >  文章  >  php框架  >  详解Laravel接入paypal支付

详解Laravel接入paypal支付

藏色散人
藏色散人转载
2020-06-15 12:02:574785浏览

PayPal

PayPal, 全球众多用户使用的国际贸易支付工具, 能够轻松完成境外收付款! 一个账户全球通用, 成为PayPal商家, 就能在任何地方接受更多付款方式。

下载paypal sdk

在 composer.json 中加入 “paypal/rest-api-sdk-php” : “1.7.4”,如图:

企业微信截图_15921933704194.png

执行composer update

注册开发者账号,创建测试应用,测试账户

地址:

https://developer.paypal.com

创建沙盒测试账户

账号后台(可以看到自己的消费记录):

https://www.sandbox.paypal.com/signin?returnUri=https%3A%2F%2Fwww.sandbox.paypal.com%2Fmyaccount%2Fsummary&state=%2F

创建应用

企业微信截图_15921933785766.png

查看应用配置

点击创建的应用,查看配置Client ID,Secret,后面请求接口需要用到,sandbox为测试环境,live为线上环境

企业微信截图_1592193385678.png

新建测试账号

可设置金额及密码

企业微信截图_15921933924791.png

接入代码

下单逻辑

<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\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 paypalController extends Controller
{
    const clientId = &#39;xxxxxxxxx&#39;;//应用Client ID
    const clientSecret = &#39;xxxxxxxx&#39;;//Secret
    const accept_url = &#39;http://xxx.laravel.com/Api/paypal/Callback&#39;; //支付成功和取消交易的跳转地址
    const Currency = &#39;USD&#39;;//货币单位
    protected $PayPal;
    public function __construct()
    {
        $this->PayPal = new ApiContext(
            new OAuthTokenCredential(
                self::clientId,
                self::clientSecret
            )
        );
 //如果是沙盒测试环境不设置,请注释掉
//        $this->PayPal->setConfig(
//            array(
//                &#39;mode&#39; => &#39;live&#39;,
//            )
//        );
    }
    /**
     * @param
     * $product 商品
     * $price 价钱
     * $shipping 运费
     * $description 描述内容
     */
    public function pay()
    {
        $product = &#39;1123&#39;;
        $price = 1;
        $shipping = 0;
        $description = &#39;1123123&#39;;
        $paypal = $this->PayPal;
        $total = $price + $shipping;//总价
        $payer = new Payer();
        $payer->setPaymentMethod(&#39;paypal&#39;);
        $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 . &#39;?success=true&#39;)->setCancelUrl(self::accept_url . &#39;/?success=false&#39;);
        $payment = new Payment();
        $payment->setIntent(&#39;sale&#39;)->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]);
        try {
            $payment->create($paypal);
        } catch (PayPalConnectionException $e) {
            echo $e->getData();
            die();
        }
        $approvalUrl = $payment->getApprovalLink();
        header("Location: {$approvalUrl}");
    }

走完下单逻辑会跳转到paypal的支付页面,第一次需要输入账号密码,如图:

企业微信截图_1592193400622.png

进入支付页面,选择Paypal余额支付,支付完成或取消交易会自动跳转到你下单时传的跳转地址,并会传两个参数 paymentId(paypal订单号),PayerID(用户id),你可以根据你的业务逻辑写对应逻辑,一般同步回调确认用户是否付款,异步回调处理业务逻辑

同步回调

 /**
     * 回调
     */
    public function Callback()
    {
        $success = trim($_GET[&#39;success&#39;]);
        if ($success == &#39;false&#39; && !isset($_GET[&#39;paymentId&#39;]) && !isset($_GET[&#39;PayerID&#39;])) {
            echo &#39;取消付款&#39;;die;
        }
        $paymentId = trim($_GET[&#39;paymentId&#39;]);
        $PayerID = trim($_GET[&#39;PayerID&#39;]);
        if (!isset($success, $paymentId, $PayerID)) {
            echo &#39;支付失败&#39;;die;
        }
        if ((bool)$_GET[&#39;success&#39;] === &#39;false&#39;) {
            echo  &#39;支付失败,支付ID【&#39; . $paymentId . &#39;】,支付人ID【&#39; . $PayerID . &#39;】&#39;;die;
        }
        $payment = Payment::get($paymentId, $this->PayPal);
        $execute = new PaymentExecution();
        $execute->setPayerId($PayerID);
        try {
            $payment->execute($execute, $this->PayPal);
        } catch (Exception $e) {
            echo &#39;,支付失败,支付ID【&#39; . $paymentId . &#39;】,支付人ID【&#39; . $PayerID . &#39;】&#39;;die;
        }
        echo &#39;支付成功,支付ID【&#39; . $paymentId . &#39;】,支付人ID【&#39; . $PayerID . &#39;】&#39;;die;
    }

异步回调

回调地址配置在后台,地址必须为https开头,设置一般过一段时间才会生效(我是下午申请,第二天上午才生效的,如图:

企业微信截图_15921934125191.png

你可以勾选很多事件发送通知,不过最重要的还是支付完成(Payment sale completed)以及退款(Payment sale refunded)

支付完成

public function notify(){
        //获取回调结果
        $json_data = $this->get_JsonData();
        if(!empty($json_data)){
             Log::debug("paypal notify info:\r\n".json_encode($json_data));
        }else{
            Log::debug("paypal notify fail:参加为空");
        }
          //自己打印$json_data的值看有那些是你业务上用到的
          //比如我用到
          $data[&#39;invoice&#39;] = $json_data[&#39;resource&#39;][&#39;invoice_number&#39;];
          $data[&#39;txn_id&#39;] = $json_data[&#39;resource&#39;][&#39;id&#39;];
          $data[&#39;total&#39;] = $json_data[&#39;resource&#39;][&#39;amount&#39;][&#39;total&#39;];
          $data[&#39;status&#39;] = isset($json_data[&#39;status&#39;])?$json_data[&#39;status&#39;]:&#39;&#39;;
          $data[&#39;state&#39;] = $json_data[&#39;resource&#39;][&#39;state&#39;];
        try {
                 //处理相关业务
        } catch (\Exception $e) {
            //记录错误日志
            Log::error("paypal notify fail:".$e->getMessage());
            return "fail";
        }
        return "success";
    }
    public function get_JsonData(){
        $json = file_get_contents(&#39;php://input&#39;);
        if ($json) {
            $json = str_replace("&#39;", &#39;&#39;, $json);
            $json = json_decode($json,true);
        }
        return $json;
    }

处理退款

public function returnMoney()
    {
        try {
            $txn_id = "xxxxxxx";  //异步加调中拿到的id
            $amt = new Amount();
            $amt->setCurrency(&#39;USD&#39;)
                ->setTotal(&#39;99&#39;);  // 退款的费用
            $refund = new Refund();
            $refund->setAmount($amt);
            $sale = new Sale();
            $sale->setId($txn_id);
            $refundedSale = $sale->refund($refund, $this->PayPal);
        } catch (\Exception $e) {
            // PayPal无效退款
            return json_decode(json_encode([&#39;message&#39; => $e->getMessage(), &#39;code&#39; => $e->getCode(), &#39;state&#39; => $e->getMessage()]));  // to object
        }
        // 退款完成
        return $refundedSale; 
    }

查看相关流水

企业微信截图_15921934192087.png

总结

paypal对于扩展海外支付的业务还是很有帮助的,它支持多种货币,可绑定各种信用卡,银行卡,缺点是接入时不会有paypal技术人员和你对接,反正我是在接入完成之后才联系到paypal对接人的,好在接入难度不大,网上资料比较丰富,希望此文章可以给各位带来帮助,对于海外支付有兴趣的可以和我来讨论。

相关教程推荐:《laravel

以上是详解Laravel接入paypal支付的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:csdn.net。如有侵权,请联系admin@php.cn删除