laravel 框架怎样调用支付宝的支付接口

发布网友 发布时间:2022-04-23 18:06

我来回答

2个回答

懂视网 时间:2022-04-28 15:39

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 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 = '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的支付页面,第一次需要输入账号密码,如图:

企业微信截图_1592193400622.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开头,设置一般过一段时间才会生效(我是下午申请,第二天上午才生效的,如图:

企业微信截图_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:
".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; 
 }

查看相关流水

企业微信截图_15921934192087.png

总结

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

相关教程推荐:《laravel》

热心网友 时间:2022-04-28 12:47

移动支付接口为手机app等平台和用户、消费者之间架起一座桥梁,使资金能够准确无误的划拨。现在支付宝、微信支付、银联支付等都支持手机支付。平台企业涉及移动支付业务可以使用维金云钱包,通过简单的接口调用就能连接支付宝、银行卡等。

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com