<?php
/**
* @author rdisme
* 微信支付 H5支付方式
*/
class Wechat_pay_mweb {
const PAYURL = 'https://api.mch.weixin.qq.com/pay/unifiedorder'; //微信传参地址
private $appid;
private $mchid;
private $key;
private $host;
public function __construct()
{
$this->appid = *******;
$this->mchid = *******;
$this->key = *******;
$this->host = *******; // 网站域名比如:https://www.baidu.com
}
/**
* [pay 微信支付-H5支付方式]
* @param string $out_trade_no [订单编号]
* @param string $body [备注]
* @param integer $total_fee [金额]
* @return [array]
*/
public function pay( $out_trade_no,$body='ceshi',$total_fee=1,$notify_url='',$attach=5 )
{
// 交易类型 H5交易
$trade_type='MWEB';
//随机字符串
$nonce_str = MD5($out_trade_no);
//获得用户设备IP
$spbill_create_ip = $this->get_client_ip();
//场景信息 必要参数
$scene_info ='{"h5_info":{"type":"Wap","wap_url":"'.$this->host.'","wap_name":"支付"}}';
//拼接字符串 注意顺序微信有个测试网址 顺序按照他的来 直接点下面的校正测试 包括下面XML 是否正确
$signA ="appid={$this->appid}&attach=$attach&body=$body&mch_id={$this->mchid}&nonce_str=$nonce_str¬ify_url={$notify_url}&out_trade_no=$out_trade_no&scene_info=$scene_info&spbill_create_ip=$spbill_create_ip&total_fee=$total_fee&trade_type=$trade_type";
// MD5 后转换成大写
$sign = strtoupper(MD5( $signA."&key={$this->key}" ));
//拼接成XML 格式
$post_data = "<xml>
<appid>{$this->appid}</appid>
<attach>$attach</attach>
<body>$body</body>
<mch_id>{$this->mchid}</mch_id>
<nonce_str>$nonce_str</nonce_str>
<notify_url>{$notify_url}</notify_url>
<out_trade_no>$out_trade_no</out_trade_no>
<scene_info>$scene_info</scene_info>
<spbill_create_ip>$spbill_create_ip</spbill_create_ip>
<total_fee>$total_fee</total_fee>
<trade_type>$trade_type</trade_type>
<sign>$sign</sign>
</xml>";
//后台 POST 微信传参地址 同时取得微信返回的参数
$dataxml = $this->postXmlCurl($post_data,self::PAYURL);
//将微信返回的 XML 转换成数组
$objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA);
return array(
'mweb_url' => isset($objectxml['mweb_url']) ? $objectxml['mweb_url'] : ''
);
}
public function postXmlCurl($xml,$url,$second = 30){
$ch = curl_init();
//设置超时
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
//设置 header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//post 提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//运行 curl
$data = curl_exec($ch);
//返回结果
if($data){
curl_close($ch);
return $data;
}else{
$error = curl_errno($ch);
curl_close($ch);
echo "curl 出错,错误码:$error"."";
}
}
public function get_client_ip()
{
$cip = false;
if( $_SERVER['REMOTE_ADDR'] ) {
$cip = $_SERVER['REMOTE_ADDR'];
} elseif( getenv('REMOTE_ADDR') ) {
$cip = getenv('REMOTE_ADDR');
}
return $cip;
}
}
?>
PHP - 微信H5支付
最新推荐文章于 2024-07-11 04:15:10 发布