Joke Collection Website - Blessing messages - What is WeChat Payment lavel?

What is WeChat Payment lavel?

Laravel WeChat Development Component-WeChat WeChat Payment

I. Introduction

This tutorial is a development example based on LAVER L5.1LTS in LAMP development environment.

Because there are many excellent php developers with open source spirit in China, in order to save time and maintenance cost, WeChat development adopts component development, and we don't need to make wheels repeatedly. This tutorial uses easywechat component of overtrue team to develop and implement the payment function of WeChat.

Because this component has too many functions, this blog mainly introduces the main process and ideas of "code scanning payment".

Second, composer installation.

By default, everyone has installed composer in their own development environment, and they can perform some simple operations and installation commands:

The composition requirement is "overtrue/laravel- WeChat: ~3.0"

* If laravel-debugbar is used, please disable or close it, otherwise this module will not work normally! ! ! * (But composer prompts whether x-debug can be turned off, which will affect the installation, so you can leave it alone. )

Third, configure in laravel.

1. Register the ServiceProvider (find the array with key providers in the config/app.php configuration file and add the service providers to the array):

over true \ LaravelWechat \ service provider::class,

2. (Optional) Add * Appearance * In the alias array of app/config/app.php, add * alias *:

Wechat' => over true \ laravelwechat \ serviceprovider:: class,

3. Create a configuration file (run the artisan command in the project root directory and publish the configuration file to the project):

Php artisan vendor: publishing

At this point, the configuration file wechat.php will be generated in the /config directory. Enter your WeChat merchant information in it. Please pay attention to privacy protection here.

Fourth, WeChat pays for flies.

1. Configure WeChat merchant information. Yes. The ENV file in the laravel root directory supports the following configurations:

Wechat _APPID

Wechat _ Secret

Wechat _ token

Wechat _AES_KEY

Wechat _ Log _ Level

Wechat _ Log _ File

Wechat _ OAUTH _ scope

Wechat _ OAUTH _ callback

Wechat _ Payment _ Merchant _ID

Wechat _ Payment _ Key

Wechat _ Payment _ Certificate _ Path

Wechat _ Payment _ Key _ Path

Wechat _ Payment _ Equipment _ Information

Wechat _ Payment _ Subscription _ Application _ID

Wechat _ Payment _ Subscription _ Merchant _ID

Wechat _ Enable _ Simulate

You can configure related parameters in /config/wechat.php, or you can write them in a. ENV file, and then, the specific reading method of wechat.php is as follows:

Notify _ url' = & gtEnv ('notify _ URL',' /notify _ URL'),//callback address

Env () reading. Env file by default. If the constant is not present. Env, returns the value of the second parameter of env ().

Problems needing attention in 2.wechat.php document

(1). The Log configuration is in the Log array.

(2)' Payment' array is the main configuration array, which mainly configures the information and certificates of merchants.

3. (Press the key) Create an order

(1). Introduce a namespace.

Use easy wechat \ foundation \ application;

Use EasyWeChat \ Payment \ Order

(2). Fill in the order information

$attributes = [

Trade _ type' =>' JSAPI', // JSAPI, local machine, application program ...

Body' = & gtIPad mini 16G white',

Details' = & gtIPad mini 16G white',

out _ trade _ no ' = & gt' 12 1775250 120 14070332333680 18',

total _ fee ' = & gt5388,

Notify _ url' = & gt/order-notify',//Payment result notification URL. If it is not set, the default address in the configuration will be used. There is no match here because it has been configured in. environment

// ...

];

//Create an order

$order = $ attributes;

$ result = $ payment-& gt; To prepare (an order);

if($ result-& gt; Return_code ==' success' & amp& amp$ result-& gt;; result_code == 'SUCCESS ')

{

//Logic after order generation

\Log::info ('Generate order number ...'). $ data-& gt; order _ guid);

//This piece is returned to the page in the form of ajax.

//The user's experience is to click to confirm the payment, and the verification code comes out as a layer page (yes, you need a useful layer js).

$ajax_data=[

html ' = & gtJSON _ encode(\ QR code::size(250)-& gt; Generate ($result['code_url']),

out _ trade _ no ' = & gt$ data-& gt; order_guid

Price' =>$ data-& gt;; price

];

Return $ ajax _ data

} Otherwise {

return back()-& gt; WithErrors ('Error in generating order!' );

}

Verb (short for verb) renders the page.

An order is created here, and a QR code picture needs to be generated. Please refer to this QR code picture component.

Composer setting

First, add the QrCode package to the require in the composer.json file:

Composers need "simplesoftwareio/simple-qrcode"

Add a service provider

Register simplesoftwareio \ qrcode \ qrcodeserviceprovider:: class in the providers array of config/app.php

Add alias

Finally, register' QR code' = & gtsimplesoftwareio \ qrcode \ facades \ qrcode:: class to alias the array of config/app.php 。

Pay.blade.php content

& ltscript type = " text/JavaScript " src = " { { asset(' vendor/jquery . js ')} } " & gt; & lt/script & gt;

& ltscript type = " text/JavaScript " src = " { { asset(' layer/layer . js ')} } " & gt; & lt/script & gt;

& ltInput class = "wechat _ BTN" type = "button" value =" payment confirmation "/>

{! -This page needs some js code to make the payment function more beautiful and bug-free, such as ajax polling, btn failure after clicking on payment, and closing the bomb layer when giving up payment. -}

Js content

$ ('.wechat _ BTN'). Click (function () {

$ ('.My order guid'). val(“”);

$('#code ')。 val(“”);

//ajax generates QR code

Data = {

_token':$("。 Token "). val(),// token

Money': $ (". Money "). Val (),//Commodity price

}

sendAjax(data,"/order ",function (data) {

//Send a QR code (here use a beautiful layer library)

layer.open({

Type: 1,

Title:' WeChat Pay',

Skin:' layui-layer-rim',//with border.

Area: ['270px',' 340px'],//width and height.

Content: "& ltpstyle =' color: red;' Text alignment: centered; & gt payment amount: "+data ['price'].

+"Yuan

+"'/>& ltdiv id = ' code ' style = ' text-align:center; & gt"+JSON.parse(data['html'])+

“& lt/div & gt; & ltp style = ' text-align:center;' & gt Please use WeChat scan code to pay.

//Here I put a small js about the bomb layer library into the content.

});

getInfo();

//Write a poll here, which can asynchronously query whether the order has been paid, so as to carry out logical processing (such as polling the payment status and successfully jumping to the page). Just mention my idea, and the polling code doesn't need to be found and posted.

});

});

Sixth, the callback function

Put the main code first:

Public function notifyUrl (request $request)

{

$app = new application (config ('WeChat'));

$ response = $ app-& gt; Payment-> HandleNotify (function $notify, $ successful) (

If ($ succeeds) {

$order_arr=json_decode($notify,true);

$ order _ guid = $ order _ arr[' out _ trade _ no ']; //Order number

//Logic of successful callback

}

});

}

pay attention to

(1). Wechat sends a callback by email. Once defined in the route, token verification needs to be excluded from the laravel project. I suggest that VerifyCsrfToken.php exclude this route from the middleware.

Protected $except = [

//

/pay_success_notify ',

/Recipient Rule Excludes Routes'

];

(2).* Focus! Focus! Focus! * Callback processing can be said to be the most important here. If there is a problem here, it may lead to the failure of WeChat callback after the user pays successfully, and the logic of background callback is not realized, resulting in the user spending money and buying nothing (that is, your server does not modify the payment status and other database operations for paying users). Another consequence is that if the parameters returned by WeChat are incorrect, WeChat will send a callback message to remind you that the payment was successful many times, which will cause your server to accept the callback function many times. At this time, you are just as usual. You didn't judge the user's payment status in the logic of successful payment, which caused the logical user to charge the money once, but repeated several related database operations in the database. The former cheated paying users, while the latter cheated your company. If you don't pay attention here, the consequences will only be very serious. Be careful where money is involved.

(2) In the method pointed by the callback route, if your logic of successful payment runs successfully, you need to return true;; If the database operation is unsuccessful, you need to return false;; Or not, WeChat will send another callback message (post mode).

Seven, some easywechat official suggestions:

Here are a few points to note:

1.handleNotify receives only one callable parameter, usually with an anonymous function.

2. The anonymous function receives two parameters, which are:

$notify is an EasyWeChat\Support\Collection object, which encapsulates the notification information, so I will not repeat it here. You can read the notification content as an object or an array, for example, $ notify->; Totalfee or $notify['totalfee'].

The parameter $successful is actually to judge whether the user has paid successfully (result _ code = =' success').

3. The return value of this function is to tell WeChat whether I have finished processing. If you return false or specific error information, WeChat will continue to inform you again later until you explicitly tell it "I have finished processing" and return true in the function; Indicates that processing is complete.

4.handleNotify return value $Response is a response object. If you want to output directly, use $ response->; Send (), which is not output but returns: return $response in some frames.

5. Note: Please separate "whether the payment is successful" from "whether the processing is completed". They are not necessarily connected.

For example, WeChat informs you that the payment is completed, but the payment fails (result_code is' fail'). You should update your order for payment failure, but tell WeChat that the processing is complete.

postscript

1. In the development of WeChat, laravel's own log error detection method is widely used. When var_dump (), echo (), dd () and other methods can't check the error information, log error checking can be solved. How to use laravel's log service will be discussed later.

2. The development of this project can be said to be component development, with fast development speed, high code quality and low maintenance cost. The development of WeChat in this situation is a microcosm.

[Original Address] (/)