LaravelAlipay Payment

1. Payment function

1.1 Alipay Payment Installation Configuration


Then Alipay Scavenger logs in. Because the personal number is unable to apply for the payment key, we use its sandbox environment.


We can recharge any amount on our side in a sandbox environment.

Similarly, third-party packages can be used for development in laravel to speed up our development and make it very easy to use.

Run the command composer require yansongda/laravel-pay:

Run the command PHP artisan vendor:publish --provider="Yansongda\LaravelPayPayServiceProvider" --tag=laravel-pay profile:

Then follow File. Generate a public key certificate,
Download the installation document to specify the build.
Place the downloaded Certificate in the code folder:

I placed three certificate files in my new folder cert.
Next, modify the configuration:

'alipay' => [
        'default' => [
            // Alipay's app_id sandbox tests are available
            'app_id' => '2021000118617661',
            // Apply private key
            'app_secret_cert' => '', // The certificate key you requested
            // Apply Public Key Certificate Path
            'app_public_cert_path' => '/home/vagrant/code/cert/appCertPublicKey_2021000118617661.crt',
            // Alipay Public Key Certificate Path
            'alipay_public_cert_path' => '/home/vagrant/code/cert/alipayCertPublicKey_RSA2.crt',
            // Payment Baogen Certificate Path  
            'alipay_root_cert_path' => '/home/vagrant/code/cert/alipayRootCert.crt',
            // Synchronize notification address after successful payment
            'return_url' => '',
            // Asynchronous Notification Address
            'notify_url' => 'http://8bee-211-97-129-32.ngrok.io/api/pay/notify/aliyun', //your payment completes callback address handling routing, which uses intranet penetration. Configuration is mentioned in Section 4 of this chapter
            'mode' => Pay::MODE_SANDBOX, // Sandbox environment, since we don't have a business number, sandbox environment configuration is used
            // 'mode'=> Pay:: MODE_NORMAL, //Formal Environment
            
        ],
    ],

1.2 Create a payment controller

Run the command php artisan make:controller Web/PayController

Write the method at the time of payment and the callback method at the time of completion of payment:

<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Yansongda\LaravelPay\Facades\Pay;

class PayController extends Controller
{
    // payment
    public function pay(Request $request, Order $order)
    {
        $request->validate([
            'type' => 'required|in:aliyun,wechat',
        ], [
            'type.required' => 'Payment type cannot be empty',
            'type.in' => 'Payment type can only be Payment by Alipay or WeChat'
        ]);

        // Return directly if order status is not 1
        if ($order->status != 1) {
            return $this->response->errorBadRequest('Order status is abnormal, please re-order!');
        }


        if ($request->input('type') == 'aliyun') {


            $order = [
                'out_trade_no' => $order->order_no,
                'total_amount' => $order->amount/100,
                'subject' => $order->goods()->first()->title.' etc. '.$order->goods()->count() .'Goods',
            ];

            return Pay::alipay()->scan($order);
        }
        if ($request->input('type') == 'wechat') {
        }
    }

    /**
     * Callback after Alipay's successful payment
     */
    public function notifyAliyun(Request $request) {
        $alipay = Pay::alipay();
    
        try{
            $data = $alipay->callback(); // Yes, it's that simple!

            // Please make your own judgment on trade_status and other logic. In Alipay's business notification, Alipay will only be deemed successful if the transaction notification status is TRADE_SUCCESS or TRADE_FINISHED.
            // 1. The merchant needs to verify whether the out_trade_no in the notification data is the order number created in the merchant system;
            // 2. Determine whether total_amount is really the actual amount of the order (that is, the amount at the time the merchant order was created);
            // 3. Check whether the seller_id (or seller_email) in the notification is the corresponding operation of the out_trade_no document (sometimes a merchant may have more than one seller_id/seller_email);
            // 4. Verify that app_id is the merchant itself.
            // 5. Other business logic
             
            // Determine the status of successful payment status
            if ($data->trade_status == 'TRADE_SUCCESS' || $data->trade_status == 'TRADE_FINISHED') {
                // Query orders
                $order = Order::where('order_no', $data->out_trade_no)->first();

                // Update order data (simple write, if complete follow above 5 points)
                $order->update([
                    'status' => 2, // Payment Completed
                    'pay_time' => $data->gmt_payment, // Time of payment
                    'pay_type' => 'Alipay', // Type of payment
                    'trade_no' => $data->trade_no, // Alipay's number is used when writing a refund
                ]);
            }

            // Log::info($data); print log knows what field the callback was given to 
            Log::debug('Alipay notify', $data->all()); // Print log knows what fields callbacks are given 
        } catch (\Exception $e) {
            // $e->getMessage();
        }

        return $alipay->success();
    }
}

We insert data when we pay callbacks, so Order.php needs to add fields that allow batch assignments:

1.3 Create payment routes

        /**
         * payment
         */
        $api->get('orders/{order}/pay', [PayController::class, 'pay']);

1.4 Intranet Penetration

Since we are using the local domain name, the external network is not accessible, and this Alipay callback function cannot be requested, we need to configure intranet penetration here:
Run the command share shopprojectapi.com
(shopprojectapi.com is your own configured domain name)
An error occurs: -bash: /usr/local/bin/ngrok: cannot execute binary file: Exec format error
The reason is simple, but for a few hours, because my computer is m1 arm64 architecture, and ngrok in homestead is not estimated, so we go to the official website to download ngrok's linux

After downloading the unzipped file, replace the ngrok at this path/usr/local/bin/ngrok on the virtual machine with the tool FileZilla.
After replacing it, run the command share shopprojectapi.com and you can see that:

Next, visit the domain name it gives us, and you can see that the external network can already access our intranet projects:

1.5 Create Payment Completion Callback Route

It is important to note that this callback route does not require login, so it is placed outside the login middleware.

    /**
     * Callback
     */ 
    // Callback after Alipay's successful payment
    $api->any('pay/notify/aliyun', [PayController::class, 'notifyAliyun']);

1.6 Test results

Payment interface

Generate links, we will link through The web address Convert to QR code, download Alipay version of sandbox test

Then scan the generated QR code and click Payment. After the payment is successful, we check to see if the order has data inserted:

You can see that our order is status 2 and we also have Alipay's order number. So far our Alipay payment function has been perfected.

On the way to php learning, if you feel this article is helpful to you, please pay attention to three lines of comments. Thank you, you must be another support for my blogging.

Keywords: PHP Laravel Back-end

Added by tcorbeil on Thu, 16 Sep 2021 04:26:18 +0300