


Use EasyWechat to quickly develop WeChat public account payment
Sep 14, 2017 am 09:58 AMPreliminary preparation:
After applying for WeChat payment, you will receive 2 parameters, merchant id, and merchant key.
Note , these two parameters should not be confused with WeChat parameters.
WeChat parameters: appid, appkey, token
Payment parameters: merchant_id (merchant number), key( Payment key)
How to get the payment key?
Go to https://pay.weixin.qq.com -->Account Center--> API security-->Set API key
Set a 32-bit key by yourself
WeChat payment process:
1. Composer installs the EasyWechat package
Environment requirements:
##PHP >= 5.5. 9
- ##PHP cURL extension
- PHP OpenSSL extension
composer require overtrue/wechat:~3.1 -vvv
2. Public Number configuration
2.1, Configure payment directory and authorized domain name ##2.2. Configure web page authorization
## 3. Initialize the SDK and create an EasyWeChat\Foundation\Application
<?php
use EasyWeChat\Foundation\Application;protected $app=null;public function construct(){
$options = [ /**
* Debug 模式,bool 值:true/false
*
* 當(dāng)值為 false 時,所有的日志都不會記錄 */
'debug' => true, /**
* 賬號基本信息,請從微信公眾平臺/開放平臺獲取 */
'app_id' => 'your-app-id', // AppID
'secret' => 'your-app-secret', // AppSecret
'token' => 'your-token', // Token
'aes_key' => '', // EncodingAESKey,安全模式下請一定要填寫!??!
/**
* 日志配置
*
* level: 日志級別, 可選為:
* debug/info/notice/warning/error/critical/alert/emergency
* permission:日志文件權(quán)限(可選),默認為null(若為null值,monolog會取0644)
* file:日志文件位置(絕對路徑!!!),要求可寫權(quán)限 */
'log' => [ 'level' => 'debug',
'permission' => 0777,
'file' => '/tmp/easywechat.log',
], /**
* OAuth 配置
*
* scopes:公眾平臺(snsapi_userinfo / snsapi_base),開放平臺:snsapi_login
* callback:OAuth授權(quán)完成后的回調(diào)頁地址 */
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => '/examples/oauth_callback.php',
], /**
* 微信支付 */
'payment' => [ 'merchant_id' => 'your-mch-id',
'key' => 'key-for-signature',
'cert_path' => 'path/to/your/cert.pem', // XXX: 絕對路徑?。。?!
'key_path' => 'path/to/your/key', // XXX: 絕對路徑!?。?!
'notify_url' => '默認的訂單回調(diào)地址', // 你也可以在下單時單獨設(shè)置來想覆蓋它
// 'device_info' => '013467007045764',
// 'sub_app_id' => '',
// 'sub_merchant_id' => '',
// ...
],];$this->$app = new Application($options);
}
4. Get the payment object payment
$payment =$this->$app->payment;
5. Pass the order object order (order number, amount, openid) as parameters
<?phpuse EasyWeChat\Foundation\Application;use EasyWeChat\Payment\Order; $attributes = [ 'trade_type' => 'JSAPI', // JSAPI,NATIVE,APP... 'body' => 'iPad mini 16G 白色', 'detail' => 'iPad mini 16G 白色', 'out_trade_no' => '1217752501201407033233368018',//訂單號 'total_fee' => 5388, // 單位:分 'notify_url' => 'http://xxx.com/order-notify', // 支付結(jié)果通知網(wǎng)址,如果不設(shè)置則會使用配置里的默認地址 'openid' => '當(dāng)前用戶的 openid', // trade_type=JSAPI,此參數(shù)必傳,用戶在商戶appid下的唯一標(biāo)識, // ... ]; $order = new Order($attributes);
6. Preprocessing, get A preprocessing id, payment->prepare(order);
$result = $payment->prepare($order); if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){ $prepayId = $result->prepay_id; }
7. Generate payment JS configuration
$json = $payment->configForPayment($prepayId); // 返回 json 字符串,如果想返回數(shù)組,傳第二個參數(shù) false
8. Will Write the order number and json into the user's payment confirmation template, trigger the js, and call up the payment
return view('done',['order'=>$ordersn,'json'=>$json]);
<script>$('form').submit (function() { WeixinJSBridge.invoke('getBrandWCPayRequest', {!!$json!!},function(res){if(res.err_msg == "get_brand_wcpay_request:ok" ) {// 使用以上方式判斷前端返回,微信團隊鄭重提示: // res.err_msg將在用戶支付成功后返回 // ok,但并不保證它絕對可靠。 } } );return false; });</script>
9. Successful callback
in the user After successful payment, the WeChat server will initiate a POST request to the callback URL set in the order, and the content of the request is an XML.
First configure the paid method in the middleware VerifyCsrfToken without going through CSRF verification
public function paid(){$response =$this->$app->payment->handleNotify(function($notify, $successful){ // 使用通知里的 "微信支付訂單號" 或者 "商戶訂單號" 去自己的數(shù)據(jù)庫找到訂單 $order = 查詢訂單($notify->out_trade_no); if (!$order) { // 如果訂單不存在 return 'Order not exist.'; // 告訴微信,我已經(jīng)處理完了,訂單沒找到,別再通知我了 } // 如果訂單存在 // 檢查訂單是否已經(jīng)更新過支付狀態(tài) if ($order->paid_at) { // 假設(shè)訂單字段“支付時間”不為空代表已經(jīng)支付 return true; // 已經(jīng)支付成功了就不再更新了 } // 用戶是否支付成功 if ($successful) { // 不是已經(jīng)支付狀態(tài)則修改為已經(jīng)支付狀態(tài) $order->paid_at = time(); // 更新支付時間為當(dāng)前時間 $order->status = 'paid'; } else { // 用戶支付失敗 $order->status = 'paid_fail'; } $order->save(); // 保存訂單 return true; // 返回處理完成}); return $response; }
The above is the detailed content of Use EasyWechat to quickly develop WeChat public account payment. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Summary of the five most popular Go language libraries: essential tools for development, requiring specific code examples. Since its birth, the Go language has received widespread attention and application. As an emerging efficient and concise programming language, Go's rapid development is inseparable from the support of rich open source libraries. This article will introduce the five most popular Go language libraries. These libraries play a vital role in Go development and provide developers with powerful functions and a convenient development experience. At the same time, in order to better understand the uses and functions of these libraries, we will explain them with specific code examples.

VSCode is a powerful, flexible, and easy-to-extend open source code editor that is widely favored by developers. It supports many programming languages ??and frameworks to meet different project needs. However, the advantages of VSCode may be different for different frameworks. This article will discuss the applicability of VSCode in the development of different frameworks and provide specific code examples. 1.ReactReact is a popular JavaScript library used for building user interfaces. When developing projects using React,

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.

Essentials for Java development: Detailed explanation of Java virtual machine installation steps, specific code examples required. With the development of computer science and technology, the Java language has become one of the most widely used programming languages. It has the advantages of cross-platform and object-oriented, and has gradually become the preferred language for developers. Before using Java for development, you first need to install the Java Virtual Machine (JavaVirtualMachine, JVM). This article will explain in detail the installation steps of the Java virtual machine and provide specific code examples.
