Home  >  Article  >  WeChat Applet  >  How to implement WeChat payment in mini program

How to implement WeChat payment in mini program

尚
Original
2020-03-30 11:24:048239browse

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);
}

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);
}

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){
   }
})

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;
}

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) { 
 
							}
						}) 
					}
				})
			}
		})
	})
}

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:
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