Payment Interface Guide for PHP and Mini Programs
With the popularity of mobile payments, more and more merchants have begun to use mini programs as one of their main sales channels. To implement the payment function of the mini program, it needs to be connected to the corresponding payment interface. This article will introduce how to use PHP language to connect the payment interface of the mini program, and attach code examples for reference.
function createSign($params, $key){ ksort($params); //按照参数名ASCII码从小到大排序 $string = ''; foreach($params as $k => $v){ if($v != '' && $k != 'sign'){ $string .= $k . '=' . $v . '&'; } } $string .= 'key=' . $key; $string = md5($string); //签名加密 return strtoupper($string); //转换成大写 }
function createUnifiedOrder($mchid, $key, $appid, $openid, $out_trade_no, $total_fee){ $params = array( 'appid' => $appid, 'body' => '商品描述', 'mch_id' => $mchid, 'nonce_str' => md5(time()), 'notify_url' => '支付成功回调地址', 'openid' => $openid, 'out_trade_no' => $out_trade_no, 'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], 'total_fee' => $total_fee, 'trade_type' => 'JSAPI' ); //生成签名 $params['sign'] = createSign($params, $key); //将数组转换为XML格式 $xml = '<xml>'; foreach($params as $k => $v){ $xml .= '<' . $k . '>' . $v . '</' . $k . '>'; } $xml .= '</xml>'; //向微信服务器发送请求 $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); $response = curl_exec($ch); curl_close($ch); //解析XML响应 $result = simplexml_load_string($response); $prepay_id = $result->prepay_id; //获取预支付交易会话标识 return $prepay_id; }
function getMiniProgramPayParams($mchid, $key, $appid, $openid, $out_trade_no, $total_fee){ $prepay_id = createUnifiedOrder($mchid, $key, $appid, $openid, $out_trade_no, $total_fee); $params = array( 'appId' => $appid, 'timeStamp' => time(), 'nonceStr' => md5(time()), 'package' => 'prepay_id=' . $prepay_id, 'signType' => 'MD5' ); //生成签名 $params['paySign'] = createSign($params, $key); return $params; }
Conclusion:
Through the above steps, we can use the PHP language to connect to the payment interface of the mini program to realize the mobile payment function. Of course, in the actual application process, corresponding adjustments and expansions need to be made according to specific business needs. I hope the content of this article will be helpful to you and enable you to successfully implement the mini program payment function.
The above is the detailed content of PHP and mini program payment interface docking guide. For more information, please follow other related articles on the PHP Chinese website!