Home > PHP Framework > Laravel > body text

Detailed explanation of Laravel access to paypal payment

藏色散人
Release: 2020-06-15 12:02:57
forward
4781 people have browsed it

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!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template