search
HomePHP FrameworkLaravelDetailed 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:

Detailed explanation of Laravel access to paypal payment

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

Detailed explanation of Laravel access to paypal payment

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

Detailed explanation of Laravel access to paypal payment

Create a new test account

Amount and password can be set

Detailed explanation of Laravel access to paypal payment

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 = &#39;xxxxxxxxx&#39;;//应用Client ID
    const clientSecret = &#39;xxxxxxxx&#39;;//Secret
    const accept_url = &#39;http://xxx.laravel.com/Api/paypal/Callback&#39;; //支付成功和取消交易的跳转地址
    const Currency = &#39;USD&#39;;//货币单位
    protected $PayPal;
    public function __construct()
    {
        $this->PayPal = new ApiContext(
            new OAuthTokenCredential(
                self::clientId,
                self::clientSecret
            )
        );
 //如果是沙盒测试环境不设置,请注释掉
//        $this->PayPal->setConfig(
//            array(
//                &#39;mode&#39; => &#39;live&#39;,
//            )
//        );
    }
    /**
     * @param
     * $product 商品
     * $price 价钱
     * $shipping 运费
     * $description 描述内容
     */
    public function pay()
    {
        $product = &#39;1123&#39;;
        $price = 1;
        $shipping = 0;
        $description = &#39;1123123&#39;;
        $paypal = $this->PayPal;
        $total = $price + $shipping;//总价
        $payer = new Payer();
        $payer->setPaymentMethod(&#39;paypal&#39;);
        $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 . &#39;?success=true&#39;)->setCancelUrl(self::accept_url . &#39;/?success=false&#39;);
        $payment = new Payment();
        $payment->setIntent(&#39;sale&#39;)->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:

Detailed explanation of Laravel access to paypal payment

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[&#39;success&#39;]);
        if ($success == &#39;false&#39; && !isset($_GET[&#39;paymentId&#39;]) && !isset($_GET[&#39;PayerID&#39;])) {
            echo &#39;取消付款&#39;;die;
        }
        $paymentId = trim($_GET[&#39;paymentId&#39;]);
        $PayerID = trim($_GET[&#39;PayerID&#39;]);
        if (!isset($success, $paymentId, $PayerID)) {
            echo &#39;支付失败&#39;;die;
        }
        if ((bool)$_GET[&#39;success&#39;] === &#39;false&#39;) {
            echo  &#39;支付失败,支付ID【&#39; . $paymentId . &#39;】,支付人ID【&#39; . $PayerID . &#39;】&#39;;die;
        }
        $payment = Payment::get($paymentId, $this->PayPal);
        $execute = new PaymentExecution();
        $execute->setPayerId($PayerID);
        try {
            $payment->execute($execute, $this->PayPal);
        } catch (Exception $e) {
            echo &#39;,支付失败,支付ID【&#39; . $paymentId . &#39;】,支付人ID【&#39; . $PayerID . &#39;】&#39;;die;
        }
        echo &#39;支付成功,支付ID【&#39; . $paymentId . &#39;】,支付人ID【&#39; . $PayerID . &#39;】&#39;;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:

Detailed explanation of Laravel access to paypal payment

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[&#39;invoice&#39;] = $json_data[&#39;resource&#39;][&#39;invoice_number&#39;];
          $data[&#39;txn_id&#39;] = $json_data[&#39;resource&#39;][&#39;id&#39;];
          $data[&#39;total&#39;] = $json_data[&#39;resource&#39;][&#39;amount&#39;][&#39;total&#39;];
          $data[&#39;status&#39;] = isset($json_data[&#39;status&#39;])?$json_data[&#39;status&#39;]:&#39;&#39;;
          $data[&#39;state&#39;] = $json_data[&#39;resource&#39;][&#39;state&#39;];
        try {
                 //处理相关业务
        } catch (\Exception $e) {
            //记录错误日志
            Log::error("paypal notify fail:".$e->getMessage());
            return "fail";
        }
        return "success";
    }
    public function get_JsonData(){
        $json = file_get_contents(&#39;php://input&#39;);
        if ($json) {
            $json = str_replace("&#39;", &#39;&#39;, $json);
            $json = json_decode($json,true);
        }
        return $json;
    }

Processing refund

public function returnMoney()
    {
        try {
            $txn_id = "xxxxxxx";  //异步加调中拿到的id
            $amt = new Amount();
            $amt->setCurrency(&#39;USD&#39;)
                ->setTotal(&#39;99&#39;);  // 退款的费用
            $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([&#39;message&#39; => $e->getMessage(), &#39;code&#39; => $e->getCode(), &#39;state&#39; => $e->getMessage()]));  // to object
        }
        // 退款完成
        return $refundedSale; 
    }

View related flow

Detailed explanation of Laravel access to paypal payment

##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: "

laravel"

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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Laravel's Primary Function: Backend DevelopmentLaravel's Primary Function: Backend DevelopmentApr 15, 2025 am 12:14 AM

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's Backend Capabilities: Databases, Logic, and MoreLaravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AM

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.

Laravel's Versatility: From Simple Sites to Complex SystemsLaravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AM

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.

Laravel (PHP) vs. Python: Development Environments and EcosystemsLaravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AM

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.

Laravel and the Backend: Powering Web Application LogicLaravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AM

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.

Why is Laravel so popular?Why is Laravel so popular?Apr 02, 2025 pm 02:16 PM

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.

Which is better, Django or Laravel?Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AM

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.

Which is better PHP or Laravel?Which is better PHP or Laravel?Mar 27, 2025 pm 05:31 PM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor