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!

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor