


Use EasyWechat to quickly develop WeChat public account payment
Preliminary 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
*
* 当值为 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:日志文件权限(可选),默认为null(若为null值,monolog会取0644)
* file:日志文件位置(绝对路径!!!),要求可写权限 */
'log' => [ 'level' => 'debug',
'permission' => 0777,
'file' => '/tmp/easywechat.log',
], /**
* OAuth 配置
*
* scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
* callback:OAuth授权完成后的回调页地址 */
'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' => '默认的订单回调地址', // 你也可以在下单时单独设置来想覆盖它
// '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', // 支付结果通知网址,如果不设置则会使用配置里的默认地址 'openid' => '当前用户的 openid', // trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识, // ... ]; $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 字符串,如果想返回数组,传第二个参数 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){ // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单 $order = 查询订单($notify->out_trade_no); if (!$order) { // 如果订单不存在 return 'Order not exist.'; // 告诉微信,我已经处理完了,订单没找到,别再通知我了 } // 如果订单存在 // 检查订单是否已经更新过支付状态 if ($order->paid_at) { // 假设订单字段“支付时间”不为空代表已经支付 return true; // 已经支付成功了就不再更新了 } // 用户是否支付成功 if ($successful) { // 不是已经支付状态则修改为已经支付状态 $order->paid_at = time(); // 更新支付时间为当前时间 $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

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

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

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.

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.

"Understanding VSCode: What is this tool used for?" 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

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
