详解Laravel接入paypal支付

paypal

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

下载paypal sdk

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

详解Laravel接入paypal支付

执行composer update

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

地址:

https://developer.paypal.com

创建沙盒测试账户

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

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

创建应用

详解Laravel接入paypal支付

查看应用配置

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

详解Laravel接入paypal支付

新建测试账号

可设置金额及密码

详解Laravel接入paypal支付

接入代码

下单逻辑

<?php namespace AppHttpControllersApi; use IlluminateHttpRequest; use AppHttpControllersController; use PayPalApiPayer; use PayPalApiItem; use PayPalApiItemList; use PayPalApiDetails; use PayPalApiAmount; use PayPalApiTransaction; use PayPalApiRedirectUrls; use PayPalApiPayment; use PayPalAuthOAuthTokenCredential; use PayPalExceptionPayPalConnectionException; use PayPalRestApiContext; use PayPalApiPaymentExecution; 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-&gt;PayPal-&gt;setConfig( //            array( //                'mode' =&gt; 'live', //            ) //        );     }     /**      * @param      * $product 商品      * $price 价钱      * $shipping 运费      * $description 描述内容      */     public function pay()     {         $product = '1123';         $price = 1;         $shipping = 0;         $description = '1123123';         $paypal = $this-&gt;PayPal;         $total = $price + $shipping;//总价         $payer = new Payer();         $payer-&gt;setPaymentMethod('paypal');         $item = new Item();         $item-&gt;setName($product)-&gt;setCurrency(self::Currency)-&gt;setQuantity(1)-&gt;setPrice($price);          $itemList = new ItemList();         $itemList-&gt;setItems([$item]);         $details = new Details();         $details-&gt;setShipping($shipping)-&gt;setSubtotal($price);         $amount = new Amount();         $amount-&gt;setCurrency(self::Currency)-&gt;setTotal($total)-&gt;setDetails($details);         $transaction = new Transaction();         $transaction-&gt;setAmount($amount)-&gt;setItemList($itemList)-&gt;setDescription($description)-&gt;setInvoiceNumber(uniqid());         $redirectUrls = new RedirectUrls();         $redirectUrls-&gt;setReturnUrl(self::accept_url . '?success=true')-&gt;setCancelUrl(self::accept_url . '/?success=false');         $payment = new Payment();         $payment-&gt;setIntent('sale')-&gt;setPayer($payer)-&gt;setRedirectUrls($redirectUrls)-&gt;setTransactions([$transaction]);         try {             $payment-&gt;create($paypal);         } catch (PayPalConnectionException $e) {             echo $e-&gt;getData();             die();         }         $approvalUrl = $payment-&gt;getApprovalLink();         header("Location: {$approvalUrl}");     }

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

详解Laravel接入paypal支付

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

同步回调

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

异步回调

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

详解Laravel接入paypal支付

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

支付完成

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

处理退款

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

查看相关流水

详解Laravel接入paypal支付

总结

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

相关教程推荐:《laravel

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享