search
HomeBackend DevelopmentPHP TutorialHow to develop WeChat payment in PHP?

How to develop WeChat payment in PHP?

May 12, 2023 am 08:39 AM
phpWeChat Paydevelop

With the popularity of smartphones, mobile payment has become an essential tool in people's lives. As one of the representatives, WeChat Pay has a large user base and market share in the domestic market. Therefore, WeChat payment development has become increasingly important for some developers who want to develop e-commerce or mobile applications.

This article will mainly introduce how to develop WeChat payment in PHP.

  1. Preparation

Before using WeChat Pay, we need to register an account on the WeChat Pay official website and obtain the developer ID, merchant number, API key and other necessary Information. At the same time, it is necessary to ensure that the merchant account has successfully opened the WeChat payment service, submitted relevant review materials, and passed the WeChat payment certification.

  1. Integrated SDK

WeChat Pay provides many SDKs for development in different languages, which we can download directly from the official website and integrate into our projects. Here we take PHP language as an example to introduce how to integrate WeChat Payment SDK.

(1) Download WeChat Payment SDK

We can download the PHP version of SDK on the official website, and after downloading, unzip it to get the "lib" directory. The "lib/WxPay.Api.php" file is the main SDK file.

(2) Create a payment file

In order to facilitate the use of the SDK, we can create a new "pay.php" file ourselves to process the logic related to WeChat payment. In this file, we need to reference and initialize the relevant settings of the above SDK. Before doing this, we need to pay attention to the following points:

——The public account appid can be obtained through the official website of WeChat Pay;
——The merchant number can be obtained through the official website of WeChat Pay;
—— Set the API key, which can be obtained through the official website of WeChat Pay;
—— Set the order transaction number, order transaction amount and other necessary parameters;

Then, we can initialize the SDK through the following code:

<?php
include_once "WxPay.Api.php";
include_once "WxPay.Data.php";

// 初始化SDK信息
WxPayConfig::$APPID = '您的公众账号APPID';
WxPayConfig::$MCHID = '您的商户号';
WxPayConfig::$KEY = '您的API密钥';

// 设置订单交易号、订单交易金额等必要的参数
$out_trade_no = '您的订单交易号';
$total_fee = '您的订单交易金额';

// ...
?>

(3) Generate signature

Before conducting WeChat payment transactions, we need to generate a signature. The code to generate the signature is as follows:

<?php
// 创建订单支付对象
$input = new WxPayUnifiedOrder();
$input->SetBody("test");                                       // 商品描述
$input->SetAttach("test");                                     // 附加数据
$input->SetOut_trade_no($out_trade_no);                        // 商户订单号
$input->SetTotal_fee($total_fee);                              // 标价金额
$input->SetTime_start(date("YmdHis"));                         // 交易起始时间
$input->SetTime_expire(date("YmdHis", time() + 60 * 5));        // 交易结束时间
$input->SetGoods_tag("test");                                  // 订单优惠标记
$input->SetNotify_url("http://localhost/pay/callback.php");    // 通知地址
$input->SetTrade_type("JSAPI");                                 // 交易类型
$input->SetOpenid("用户的openid");                              // 用户标识

// 生成签名
$order = WxPayApi::unifiedOrder($input);
$jsApiParameters = $tools->GetJsApiParameters($order);
?>

(4) JSAPI payment

Finally, we can call the WeChat payment page through JSAPI to implement the WeChat payment task. The code is as follows:

<input type="button" value="微信支付" onclick="callpay()" />
<script type="text/javascript">

// JSAPI调起微信支付
function callpay()
{
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        <?php echo $jsApiParameters; ?>,
        function(res){
            WeixinJSBridge.log(res.err_msg);
            if(res.err_msg == "get_brand_wcpay_request:ok" ){
                alert('支付成功');
            }else{
                alert('支付失败:' + res.err_msg);
            }
        }
    );
}
</script>
  1. Summary

The above is a detailed introduction on how to develop WeChat payment in PHP. Through the above steps, we can quickly implement the WeChat payment function and improve the user experience of the website or mobile application. Of course, depending on the specific situation, related issues such as security during the payment process also need to be considered.

The above is the detailed content of How to develop WeChat payment in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.