Home WeChat Applet WeChat Development Use EasyWechat to quickly develop WeChat public account payment

Use EasyWechat to quickly develop WeChat public account payment

Sep 14, 2017 am 09:58 AM
easywechat develop

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

Installation:

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

instance

<?php
use EasyWeChat\Foundation\Application;protected $app=null;public function construct(){   
$options = [   /**
     * Debug 模式,bool 值:true/false
     *
     * 当值为 false 时,所有的日志都不会记录     */
    &#39;debug&#39;  => true,    /**
     * 账号基本信息,请从微信公众平台/开放平台获取     */
    &#39;app_id&#39;  => &#39;your-app-id&#39;,         // AppID
    &#39;secret&#39;  => &#39;your-app-secret&#39;,     // AppSecret
    &#39;token&#39;   => &#39;your-token&#39;,          // Token
    &#39;aes_key&#39; => &#39;&#39;,                    // EncodingAESKey,安全模式下请一定要填写!!!

    /**
     * 日志配置
     *
     * level: 日志级别, 可选为:
     *         debug/info/notice/warning/error/critical/alert/emergency
     * permission:日志文件权限(可选),默认为null(若为null值,monolog会取0644)
     * file:日志文件位置(绝对路径!!!),要求可写权限     */
    &#39;log&#39; => [        &#39;level&#39;      => &#39;debug&#39;,
        &#39;permission&#39; => 0777,
        &#39;file&#39;       => &#39;/tmp/easywechat.log&#39;,
    ],    /**
     * OAuth 配置
     *
     * scopes:公众平台(snsapi_userinfo / snsapi_base),开放平台:snsapi_login
     * callback:OAuth授权完成后的回调页地址     */
    &#39;oauth&#39; => [        
            &#39;scopes&#39;   => [&#39;snsapi_userinfo&#39;],
        &#39;callback&#39; => &#39;/examples/oauth_callback.php&#39;,
    ],    /**
     * 微信支付     */
    &#39;payment&#39; => [        &#39;merchant_id&#39;        => &#39;your-mch-id&#39;,
        &#39;key&#39;                => &#39;key-for-signature&#39;,
        &#39;cert_path&#39;          => &#39;path/to/your/cert.pem&#39;, // XXX: 绝对路径!!!!
        &#39;key_path&#39;           => &#39;path/to/your/key&#39;,      // XXX: 绝对路径!!!!
        &#39;notify_url&#39;         => &#39;默认的订单回调地址&#39;,       // 你也可以在下单时单独设置来想覆盖它
        // &#39;device_info&#39;     => &#39;013467007045764&#39;,
        // &#39;sub_app_id&#39;      => &#39;&#39;,
        // &#39;sub_merchant_id&#39; => &#39;&#39;,
        // ...
    ],];$this->$app = new Application($options);
}
Copy after login
4. Get the payment object payment

$payment =$this->$app->payment;
Copy after login

5. Pass the order object order (order number, amount, openid) as parameters

<?phpuse EasyWeChat\Foundation\Application;use EasyWeChat\Payment\Order; 

$attributes = [ &#39;trade_type&#39; => &#39;JSAPI&#39;, // JSAPI,NATIVE,APP... &#39;body&#39; => &#39;iPad mini 16G 白色&#39;, &#39;detail&#39; => &#39;iPad mini 16G 白色&#39;,
&#39;out_trade_no&#39; => &#39;1217752501201407033233368018&#39;,//订单号 &#39;total_fee&#39; => 5388, // 单位:分 &#39;notify_url&#39; => &#39;http://xxx.com/order-notify&#39;, // 支付结果通知网址,如果不设置则会使用配置里的默认地址 &#39;openid&#39; => &#39;当前用户的 openid&#39;, // trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识, // ... ]; $order = new Order($attributes);
Copy after login

6. Preprocessing, get A preprocessing id, payment->prepare(order);

$result = $payment->prepare($order);
if ($result->return_code == &#39;SUCCESS&#39; && $result->result_code == &#39;SUCCESS&#39;){    
$prepayId = $result->prepay_id;
}
Copy after login

7. Generate payment JS configuration

$json = $payment->configForPayment($prepayId); // 返回 json 字符串,如果想返回数组,传第二个参数 false
Copy after login

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(&#39;done&#39;,[&#39;order&#39;=>$ordersn,&#39;json&#39;=>$json]);
Copy after login
<script>$(&#39;form&#39;).submit (function() {
WeixinJSBridge.invoke(&#39;getBrandWCPayRequest&#39;, {!!$json!!},function(res){if(res.err_msg == "get_brand_wcpay_request:ok" ) {// 使用以上方式判断前端返回,微信团队郑重提示:
// res.err_msg将在用户支付成功后返回
// ok,但并不保证它绝对可靠。          }
      }
);return false;
});</script>
Copy after login

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 &#39;Order not exist.&#39;; // 告诉微信,我已经处理完了,订单没找到,别再通知我了    }    // 如果订单存在
    // 检查订单是否已经更新过支付状态
    if ($order->paid_at) { // 假设订单字段“支付时间”不为空代表已经支付
        return true; // 已经支付成功了就不再更新了    }    // 用户是否支付成功
    if ($successful) {        // 不是已经支付状态则修改为已经支付状态
        $order->paid_at = time(); // 更新支付时间为当前时间
        $order->status = &#39;paid&#39;;
    } else { // 用户支付失败
        $order->status = &#39;paid_fail&#39;;
    }    $order->save(); // 保存订单
    return true; // 返回处理完成});
    return $response;
}
Copy after login

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

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

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

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

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

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 Summary of the five most popular Go language libraries: essential tools for development Feb 22, 2024 pm 02:33 PM

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.

Which Linux distribution is best for Android development? Which Linux distribution is best for Android development? Mar 14, 2024 pm 12:30 PM

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? Understanding VSCode: What is this tool used for? Mar 25, 2024 pm 03:06 PM

&quot;Understanding VSCode: What is this tool used for?&quot; 》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

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

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:

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

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

See all articles