laravel+php+支付功能,详解Laravel接入paypal支付

PayPal

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

下载paypal sdk

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

c8006c64cc8cc9fa8a7d7d92d3b91328.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

创建应用

96b8a47858f18f48678ca2c3b72de30b.png

查看应用配置

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

b0142221714117e43e4a366a73dde767.png

新建测试账号

可设置金额及密码

a5e4db6145273fbae131389837457c16.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 = 'xxxxxxxxx';//应用Client ID

const clientSecret = 'xxxxxxxx';//Secret

const accept_url = 'http://xxx.laravel.com/Api/paypal/Callback'; //支付成功和取消交易的跳转地址

const Currency = 'USD';//货币单位

protected $PayPal;

public function __construct()

{

$this->PayPal = new ApiContext(

new OAuthTokenCredential(

self::clientId,

self::clientSecret

)

);

//如果是沙盒测试环境不设置,请注释掉

// $this->PayPal->setConfig(

// array(

// 'mode' => 'live',

// )

// );

}

/**

* @param

* $product 商品

* $price 价钱

* $shipping 运费

* $description 描述内容

*/

public function pay()

{

$product = '1123';

$price = 1;

$shipping = 0;

$description = '1123123';

$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')->setCancelUrl(self::accept_url . '/?success=false');

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

header("Location: {$approvalUrl}");

}

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

8a56b0c7f6422b4a8be39b719c5db4f2.png

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

同步回调/**

* 回调

*/

public function Callback()

{

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

if ($success == 'false' && !isset($_GET['paymentId']) && !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->PayPal);

$execute = new PaymentExecution();

$execute->setPayerId($PayerID);

try {

$payment->execute($execute, $this->PayPal);

} catch (Exception $e) {

echo ',支付失败,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';die;

}

echo '支付成功,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】';die;

}

异步回调

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

85d7e09ad9a83b08697e2af9dba93558.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['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->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->setCurrency('USD')

->setTotal('99'); // 退款的费用

$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(['message' => $e->getMessage(), 'code' => $e->getCode(), 'state' => $e->getMessage()])); // to object

}

// 退款完成

return $refundedSale;

}

查看相关流水

ff448d5d3aea169e701e7dbdabf5cdfc.png

总结

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

相关教程推荐:《laravel》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值