paypal支付接口准备工作
首先去申请一个paypal账号,https://www.paypal.com/。
申请完毕并登录,进入https://developer.paypal.com/developer/accounts/。即可看到你申请账号自动配属的两个测试账号,账号类别分别是:BUSINESS和PERSONAL,PERSONAL的账号里面有$9999,测试费用,表激动。
下面去给两个账号设置密码,点击账号展开,然后点击Profile,会弹出账号信息框,里面可以设置密码等一堆属性。如果点击账号始终无法展开,请吐槽下paypal,然后F5再点。
下面进入https://developer.paypal.com/developer/applications/申请APP,点击REST API apps栏目下面的Create App按钮,写进一个APP名称,然后选择一个测试账户作为此APP绑定的账号,如果你在上一步没有申请新的测试账号,那么这里默认就是选择了BUSINESS账号。
然后打开创建的APP,可以看到APP的clientId和clientSecret。
paypal的测试环境域名为sandbox.paypal.com,正式域名为www.paypal.com。一下测试均为测试环境。
至此准备工作差不多了,开始动代码。
PayPal-PHP-SDK下载:https://packagist.org/packages/paypal/rest-api-sdk-php
通过composer(composer安装教程)下载PayPal-PHP-SDK,具体的composer.json如下:
composer require paypal/rest-api-sdk-php
{ "require" : { "paypal/rest-api-sdk-php" : "1.7.4" }, "repositories": { "packagist": { "type": "composer", "url": "https://packagist.phpcomposer.com" } } }
shndbox 为沙盒环境配置,live 反之
点击 create account 设置测试帐号金额和密码
PayPal Payments的逻辑大致如下:
创建一个支付,发送到paypal服务端
paypal服务端返回一个用户授权地址
转链到用户授权地址,用户授权
用户授权完毕,paypal返回到客户端设置的execute地址,付款实现。
<?php namespace app\pay\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; use cmf\controller\HomeBaseController; class PaypalController extends HomeBaseController { const clientId = '';//ID const clientSecret = '';//秘钥 const accept_url = 'http://test.pay.com/PayPal/Callback';//回调地址 const Currency = 'USD';//币种 const error_log = 'PayPal-error.log';//错误日志 const success_log = 'PayPal-success.log';//成功日志 protected $PayPal; public function __construct() { $this->PayPal = new ApiContext( new OAuthTokenCredential( self::clientId, self::clientSecret ) ); $this->PayPal->setConfig( array( 'mode' => 'live', 'http.ConnectionTimeOut' => 30, ) ); } public function index() { $product = input('product'); if (empty($product)) { return json(['status'=>false,'msg'=>'商品不能为空']); } $price = input('price'); if (empty($price)) { return json(['status'=>false,'msg'=>'价格不能为空']); } $shipping = input('shipping', 0); $description = input('description'); if (empty($description)) { return json(['status'=>false,'msg'=>'描述内容不能为空']); } $this->pay($product, $price, $shipping, $description); } /** * @param * $product 商品 * $price 价钱 * $shipping 运费 * $description 描述内容 */ public function pay($product, $price, $shipping = 0, $description) { $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'])) { pay_logs(self::error_log, '取消付款'); exit(); } $paymentId = trim($_GET['paymentId']); $PayerID = trim($_GET['PayerID']); if (!isset($success, $paymentId, $PayerID)) { pay_logs(self::error_log, '支付失败'); exit(); } if ((bool)$_GET['success'] === 'false') { pay_logs(self::error_log, '支付失败,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】'); exit(); } $payment = Payment::get($paymentId, $this->PayPal); $execute = new PaymentExecution(); $execute->setPayerId($PayerID); try { $payment->execute($execute, $this->PayPal); } catch (Exception $e) { pay_logs(self::error_log, $e . ',支付失败,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】'); exit(); } pay_logs(self::success_log, '支付成功,支付ID【' . $paymentId . '】,支付人ID【' . $PayerID . '】'); } }
/** * 回调 */ 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/