接入 paypal PHP-sdk 支付 / 回调 / 退款全流程
记录一下接入paypal 全过程
因项目的原因要用到国外的支付和国外的信用卡,查了一下paypal就内置了信用卡付款方式,所以只需要接入paypal就能基本满足项目海外支付的需求。
查了一下文档发现web端可以接入js的支付和服务端sdk的支付,这里选择了php-sdk支付
一. 下载sdk
在composer.json中加入 "paypal/rest-api-sdk-php" : "1.7.4"
在命令行中运行 composer update
二. 注册开发者帐号、创建应用
地址:https://developer.paypal.com
创建沙盒测试账户(注册时会自动生成一个个人账户和商家账户,如果不能使用就自己创建几个):https://developer.paypal.com/developer/acc...
1. 创建应用
2. 获取应用配置
shndbox为沙盒环境配置,live反之
3. 创建测试帐号
点击create account设置测试帐号金额和密码
三.代码
调起paypal支付
<?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';//ID
const clientSecret = 'xxxxxxxx';//秘钥
const accept_url = 'http://laravel-rbac.cc/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}");
}
同步回调 - 用于确认用户是否付款
/**
* 回调
*/
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,设置后要等一会才会生效
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;
}
查看相关流水
支付成为后到测试帐号里查看流水https://www.sandbox.paypal.com/myaccount/home
结语
Paypal 由于是英文文档查了很多博客结合着文档来做的,下面是
php-sdk文档的地址:
http://paypal.github.io/PayPal-PHP-SDK/
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: