Home WeChat Applet Mini Program Development How to implement WeChat payment in mini program

How to implement WeChat payment in mini program

Mar 30, 2020 am 11:24 AM
Applets

How to implement WeChat payment in mini program

How to implement WeChat payment in the mini program:

Preliminary preparation:

1. Open WeChat payment and bind the mini program to WeChat payment ;

2. Prepare the appid of the mini program, the merchant number of WeChat payment, and the payment secret key.

The merchant system and the WeChat payment system mainly interact:

1. Call the login interface in the mini program to obtain the user's openid

2. Call the merchant server to pay and place an order uniformly interface to make prepayment

/**
 * 预支付请求接口(POST)
 * @param string $openid 	openid
 * @param string $body 		商品简单描述
 * @param string $order_sn  订单编号
 * @param string $total_fee 金额
 * @return  json的数据
 */
public function prepay(){
	$config = $this->config;
	
	$openid = I('post.openid');
	$body = I('post.body');
	$order_sn = I('post.order_sn');
	$total_fee = I('post.total_fee');
	
	//统一下单参数构造
	$unifiedorder = array(
		'appid'			=> $config['appid'],
		'mch_id'		=> $config['pay_mchid'],
		'nonce_str'		=> self::getNonceStr(),
		'body'			=> $body,
		'out_trade_no'	=> $order_sn,
		'total_fee'		=> $total_fee * 100,
		'spbill_create_ip'	=> get_client_ip(),
		'notify_url'	=> 'https://'.$_SERVER['HTTP_HOST'].'/Api/Wxpay/notify',
		'trade_type'	=> 'JSAPI',
		'openid'		=> $openid
	);
	$unifiedorder['sign'] = self::makeSign($unifiedorder);
	//请求数据
	$xmldata = self::array2xml($unifiedorder);
	$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
	$res = self::curl_post_ssl($url, $xmldata);
	if(!$res){
		self::return_err("Can't connect the server");
	}
	// 这句file_put_contents是用来查看服务器返回的结果 测试完可以删除了
	//file_put_contents(APP_ROOT.'/Statics/log1.txt',$res,FILE_APPEND);
	
	$content = self::xml2array($res);
	if(strval($content['result_code']) == 'FAIL'){
		self::return_err(strval($content['err_code_des']));
	}
	if(strval($content['return_code']) == 'FAIL'){
		self::return_err(strval($content['return_msg']));
	}
	self::return_data(array('data'=>$content));
	//$this->ajaxReturn($content);
}
Copy after login

3. Call the merchant server to sign the interface again and return the payment data

/**
 * 进行支付接口(POST)
 * @param string $prepay_id 预支付ID(调用prepay()方法之后的返回数据中获取)
 * @return  json的数据
 */
public function pay(){
	$config = $this->config;
	$prepay_id = I('post.prepay_id');
	
	$data = array(
		'appId'		=> $config['appid'],
		'timeStamp'	=> time(),
		'nonceStr'	=> self::getNonceStr(),
		'package'	=> 'prepay_id='.$prepay_id,
		'signType'	=> 'MD5'
	);
	
	$data['paySign'] = self::makeSign($data);
	
	$this->ajaxReturn($data);
}
Copy after login

4. Complete the payment in the mini program, and the merchant server receives the payment callback notification

Mini program code:

wx.requestPayment({
   'timeStamp': '',
   'nonceStr': '',
   'package': '',
   'signType': 'MD5',
   'paySign': '',
   'success':function(res){
   },
   'fail':function(res){
   }
})
Copy after login

Server callback notification:

//微信支付回调验证
public function notify(){
	$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
	
	// 这句file_put_contents是用来查看服务器返回的XML数据 测试完可以删除了
	//file_put_contents(APP_ROOT.'/Statics/log2.txt',$res,FILE_APPEND);
	
	//将服务器返回的XML数据转化为数组
	$data = self::xml2array($xml);
	// 保存微信服务器返回的签名sign
	$data_sign = $data['sign'];
	// sign不参与签名算法
	unset($data['sign']);
	$sign = self::makeSign($data);
	
	// 判断签名是否正确  判断支付状态
	if ( ($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') ) {
		$result = $data;
		//获取服务器返回的数据
		$order_sn = $data['out_trade_no'];			//订单单号
		$openid = $data['openid'];					//付款人openID
		$total_fee = $data['total_fee'];			//付款金额
		$transaction_id = $data['transaction_id']; 	//微信支付流水号
		
		//更新数据库
		$this->updateDB($order_sn,$openid,$total_fee,$transaction_id);
		
	}else{
		$result = false;
	}
	// 返回状态给微信服务器
	if ($result) {
		$str=&#39;<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>&#39;;
	}else{
		$str=&#39;<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>&#39;;
	}
	echo $str;
	return $result;
}
Copy after login

The complete code of the mini program is as follows:

/**
 * 支付函数
 * @param  {[type]} _payInfo [description]
 * @return {[type]}          [description]
 */
pay:function(_payInfo,success,fail){
	var payInfo = {
		body:&#39;&#39;,
		total_fee:0,
		order_sn:&#39;&#39;
	}
	Object.assign(payInfo, _payInfo);
	if(payInfo.body.length==0){
		wx.showToast({
			title:&#39;支付信息描述错误&#39;
		})
		return false;
	}
	if(payInfo.total_fee==0){
		wx.showToast({
			title:&#39;支付金额不能0&#39;
		})
		return false; 
	}
	if(payInfo.order_sn.length==0){
		wx.showToast({
			title:&#39;订单号不能为空&#39;
		})
		return false; 
	}
	var This = this;
	This.getOpenid(function(openid){
		payInfo.openid=openid;
		This.request({
			url:&#39;api/pay/prepay&#39;,
			data:payInfo,
			success:function(res){
				var data = res.data;
				console.log(data);
				if(!data.status){
					wx.showToast({
						title:data[&#39;errmsg&#39;]
					})
					return false;
				}
				This.request({
					url:&#39;api/pay/pay&#39;,
					data:{prepay_id:data.data.data.prepay_id},
					success:function(_payResult){
						var payResult = _payResult.data;
						console.log(payResult);
						wx.requestPayment({
							&#39;timeStamp&#39;: payResult.timeStamp.toString(),
							&#39;nonceStr&#39;: payResult.nonceStr,
							&#39;package&#39;: payResult.package,
							&#39;signType&#39;: payResult.signType,
							&#39;paySign&#39;: payResult.paySign,
							&#39;success&#39;: function (succ) {
								success&&success(succ);
							},
							&#39;fail&#39;: function (err) {
								fail&&fail(err);
							},
							&#39;complete&#39;: function (comp) { 
 
							}
						}) 
					}
				})
			}
		})
	})
}
Copy after login

Recommendation: " Mini Program Development Tutorial

The above is the detailed content of How to implement WeChat payment in mini program. 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
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

Develop WeChat applet using Python Develop WeChat applet using Python Jun 17, 2023 pm 06:34 PM

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

Can small programs use react? Can small programs use react? Dec 29, 2022 am 11:06 AM

Mini programs can use react. How to use it: 1. Implement a renderer based on "react-reconciler" and generate a DSL; 2. Create a mini program component to parse and render DSL; 3. Install npm and execute the developer Build npm in the tool; 4. Introduce the package into your own page, and then use the API to complete the development.

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: &lt;!--index.wxml--&gt;&l

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How uniapp achieves rapid conversion between mini programs and H5 How uniapp achieves rapid conversion between mini programs and H5 Oct 20, 2023 pm 02:12 PM

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Tutorial on writing a simple chat program in Python Tutorial on writing a simple chat program in Python May 08, 2023 pm 06:37 PM

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

How to operate mini program registration How to operate mini program registration Sep 13, 2023 pm 04:36 PM

Mini program registration operation steps: 1. Prepare copies of personal ID cards, corporate business licenses, legal person ID cards and other filing materials; 2. Log in to the mini program management background; 3. Enter the mini program settings page; 4. Select " "Basic Settings"; 5. Fill in the filing information; 6. Upload the filing materials; 7. Submit the filing application; 8. Wait for the review results. If the filing is not passed, make modifications based on the reasons and resubmit the filing application; 9. The follow-up operations for the filing are Can.

How to get membership in WeChat mini program How to get membership in WeChat mini program May 07, 2024 am 10:24 AM

1. Open the WeChat mini program and enter the corresponding mini program page. 2. Find the member-related entrance on the mini program page. Usually the member entrance is in the bottom navigation bar or personal center. 3. Click the membership portal to enter the membership application page. 4. On the membership application page, fill in relevant information, such as mobile phone number, name, etc. After completing the information, submit the application. 5. The mini program will review the membership application. After passing the review, the user can become a member of the WeChat mini program. 6. As a member, users will enjoy more membership rights, such as points, coupons, member-exclusive activities, etc.

See all articles