Home >PHP Framework >Laravel >Detailed explanation of Laravel access to paypal payment
PayPal
PayPal, an international trade payment tool used by many users around the world, can easily complete overseas collection and payment! One account is universal, and by becoming a PayPal merchant, you can accept more payment methods anywhere.
Download paypal sdk
Add "paypal/rest-api-sdk-php": "1.7.4" to composer.json, as shown in the figure:
Execute composer update
Register a developer account, create a test application, test account
Address:
https://developer.paypal.com
Create a sandbox test account
Account background (you can see your own consumption records):
https://www.sandbox.paypal.com/signin?returnUri=https%3A%2F%2Fwww.sandbox.paypal.com%2Fmyaccount%2Fsummary&state=%2F
Create application
View application configuration
Click on the created application to view the configuration Client ID, Secret, which will be used for subsequent request interfaces, and the sandbox is for testing Environment, live is an online environment
Create a new test account
Amount and password can be set
Access code
Order logic
<?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}"); }
After completing the order logic, it will jump to Paypal payment page, you need to enter your account password for the first time, as shown in the picture:
Enter the payment page, select Paypal balance payment, the payment is completed or the transaction is canceled, it will automatically jump to you to place an order When passing the jump address, two parameters paymentId (paypal order number) and PayerID (user id) will be passed. You can write corresponding logic according to your business logic. Generally, synchronous callback confirms whether the user pays, and asynchronous callback handles the business logic.
Synchronous callback
/** * 回调 */ 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; }
Asynchronous callback
The callback address is configured in the background. The address must start with https. The setting is generally done. It will take some time to take effect (I applied in the afternoon and it took effect the next morning, as shown in the picture:
You can check many events to send notifications, but the most important thing is Or payment sale completed and payment sale refunded
Payment completed
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; }
Processing refund
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; }
View related flow
##Summary
Paypal is still very useful for expanding overseas payment business Helpful, it supports multiple currencies and can be bound to various credit cards and bank cards. The disadvantage is that there will be no Paypal technicians to connect with you when connecting. Anyway, I only contacted the Paypal connection person after the connection was completed. Fortunately, it is not difficult to access, and the online information is relatively rich. I hope this article can help you. If you are interested in overseas payment, you can discuss it with me. Related tutorial recommendations: "The above is the detailed content of Detailed explanation of Laravel access to paypal payment. For more information, please follow other related articles on the PHP Chinese website!