Home PHP Framework Laravel Detailed explanation of Laravel access to paypal payment

Detailed explanation of Laravel access to paypal payment

Jun 15, 2020 pm 12:02 PM
laravel

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
Copy after login

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
Copy after login

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}");
    }
Copy after login

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;
    }
Copy after login

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;
    }
Copy after login

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; 
    }
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Which one is more beginner-friendly, Laravel or CodeIgniter? Which one is more beginner-friendly, Laravel or CodeIgniter? Jun 05, 2024 pm 07:50 PM

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

Laravel vs CodeIgniter: Which framework is better for large projects? Laravel vs CodeIgniter: Which framework is better for large projects? Jun 04, 2024 am 09:09 AM

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

Questions and Answers on PHP Enterprise Application Microservice Architecture Design Questions and Answers on PHP Enterprise Application Microservice Architecture Design May 07, 2024 am 09:36 AM

Microservice architecture uses PHP frameworks (such as Symfony and Laravel) to implement microservices and follows RESTful principles and standard data formats to design APIs. Microservices communicate via message queues, HTTP requests, or gRPC, and use tools such as Prometheus and ELKStack for monitoring and troubleshooting.

Laravel vs CodeIgniter: Which framework is better for small projects? Laravel vs CodeIgniter: Which framework is better for small projects? Jun 04, 2024 pm 05:29 PM

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.

Which is the better template engine, Laravel or CodeIgniter? Which is the better template engine, Laravel or CodeIgniter? Jun 03, 2024 am 11:30 AM

Comparing Laravel's Blade and CodeIgniter's Twig template engine, choose based on project needs and personal preferences: Blade is based on MVC syntax, which encourages good code organization and template inheritance. Twig is a third-party library that provides flexible syntax, powerful filters, extended support, and security sandboxing.

See all articles