How to implement WeChat payment in mini program

Release: 2020-03-30 11:24:04
Original
8066 people have browsed it

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='';
	}else{
		$str='';
	}
	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:'',
		total_fee:0,
		order_sn:''
	}
	Object.assign(payInfo, _payInfo);
	if(payInfo.body.length==0){
		wx.showToast({
			title:'支付信息描述错误'
		})
		return false;
	}
	if(payInfo.total_fee==0){
		wx.showToast({
			title:'支付金额不能0'
		})
		return false; 
	}
	if(payInfo.order_sn.length==0){
		wx.showToast({
			title:'订单号不能为空'
		})
		return false; 
	}
	var This = this;
	This.getOpenid(function(openid){
		payInfo.openid=openid;
		This.request({
			url:'api/pay/prepay',
			data:payInfo,
			success:function(res){
				var data = res.data;
				console.log(data);
				if(!data.status){
					wx.showToast({
						title:data['errmsg']
					})
					return false;
				}
				This.request({
					url:'api/pay/pay',
					data:{prepay_id:data.data.data.prepay_id},
					success:function(_payResult){
						var payResult = _payResult.data;
						console.log(payResult);
						wx.requestPayment({
							'timeStamp': payResult.timeStamp.toString(),
							'nonceStr': payResult.nonceStr,
							'package': payResult.package,
							'signType': payResult.signType,
							'paySign': payResult.paySign,
							'success': function (succ) {
								success&&success(succ);
							},
							'fail': function (err) {
								fail&&fail(err);
							},
							'complete': 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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!