微信H5支付,成功样例

<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/6/3
* Time: 12:00
*/
if( !defined("IN_IA") )
{
exit( "Access Denied" );
}
class Pay_Wxh5_EweiShopV2Page extends MobilePage
{

private $url ="https://api.mch.weixin.qq.com/pay/unifiedorder";//微信支付统一下单接口
private $key='saf4ds3f5sd63g8fh7df3s1f53sag4cs';//商户平台设置的密钥key
private $appid='wx635dc8b8b2bbbd27';//微信分配的公众账号ID(企业号corpid即为此appId)
private $mch_id='1533831841';//微信支付分配的商户号
private $device_info='WEB';//终端设备号(门店号或收银设备ID),注意:PC网页或公众号内支付请传"WEB"
// private $nonce_str='MD5';//随机字符串,不长于32位。推荐随机数生成算法
// private $sign='MD5';// 签名,详见签名生成算法
private $sign_type='MD5';// 签名类型,目前支持HMAC-SHA256和MD5,默认为MD5
private $body='爱奇艺充值中心-会员充值';//商品简单描述,该字段须严格按照规范传递,具体请见参数规定
// private $detail='';// 单品优惠字段(暂未上线)
private $attach='测试';//附加数据,在查询API和支付通知中原样返回,该字段主要用于商户携带订单的自定义数据
private $out_trade_no='20150806125357';//商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
private $fee_type='CNY';//符合ISO 4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
private $total_fee='1';//订单总金额,单位为分,详见支付金额
private $spbill_create_ip='';//必须传正确的用户端IP,支持ipv4、ipv6格式,获取方式详见获取用户ip指引
// private $time_start='';//订单生成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
// private $time_expire='';//订单失效时间,格式为yyyyMMddHHmmss,如2009年12月27日9点10分10秒表示为20091227091010。其他详见时间规则注意:最短失效时间间隔必须大于5分钟
private $goods_tag='WXG';//商品标记,代金券或立减优惠功能的参数,说明详见代金券或立减优惠
private $notify_url="http://aiqiyi.yamivip.cn/wx_pay.php";//接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
private $trade_type='MWEB';//H5支付的交易类型为MWEB
private $product_id='';//trade_type=NATIVE,此参数必传。此id为二维码中包含的商品ID,商户自行定义。
private $limit_pay='no_credit';//no_credit--指定不能使用信用卡支付
private $openid='';//trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。openid如何获取,可参考【获取openid】。企业号请使用【企业号OAuth2.0接口】获取企业号内成员userid,再调用【企业号userid转openid接口】进行转换
private $receipt='';//Y,传入Y时,支付成功消息和支付详情页将出现开票入口。需要在微信支付商户平台或微信公众平台开通电子发票功能,传此字段才可生效
private $scene_info=''; //该字段用于上报支付的场景信息,针对H5支付有以下三种场景,请根据对应场景上报
//3,WAP网站应用
//{"h5_info": //h5支付固定传"h5_info"
//{"type": "", //场景类型
//"wap_url": "",//WAP网站URL地址
//"wap_name": "" //WAP 网站名
//}
//}



/**
* 支付接口
*/
public function main(){
global $_GPC;
global $_W;
$openid = $_W["openid"];
$uniacid = $_W["uniacid"];
$orderid = intval($_GPC["id"]);
$order = pdo_fetch("select * from " . tablename("ewei_shop_order") . " where id=:id and uniacid=:uniacid and openid=:openid limit 1", array( ":id" => $orderid, ":uniacid" => $uniacid, ":openid" => $openid ));
$this->out_trade_no = $order['ordersn'];
$this->total_fee = $order['price'] * 100;
$this->attach = json_encode(array(
'id'=>$orderid,
'openid'=>$openid,
'uniacid'=>$uniacid,
));

if( !is_weixin() )
{
$data = $this->data();
$data['sign'] = $this->makeSign($data);
$result = $this->curl_post_ssl($this->url,$this->arrayToXml($data));

load()->func('logging');
logging_run("调试body:".$result);

$url = $this->xmlToArray($result)['mweb_url']."&redirect_url=".urlencode("http://aiqiyi.yamivip.cn/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=order.pay.success&id=".$orderid."&is_login=1&result=true");
header("location: " . $url);
return $result;
}
}



/**
* @return array|bool
* 微信支付回调验证
* 返回数据
*/
public function notify()
{
load()->func('logging');
logging_run(123213123);

global $_GPC;
global $_W;

$xml = file_get_contents('php://input');
$data = $this->xmlToArray($xml);
$data_sign = $data['sign'];
unset($data['sign']);
$sign = $this->makeSign($data);
if ( ($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS') )
{

$result = $data;
logging_run("xml:".json_encode($data));
//更新数据库
$attrch = json_decode($result['attach'],true);
$openid = $attrch['openid'];
$uniacid = $attrch["uniacid"];
$orderid = $attrch["id"];
$ordersn = $result['out_trade_no'];

$order = pdo_fetch("select * from " . tablename("ewei_shop_order") . " where id=:id and uniacid=:uniacid and openid=:openid limit 1", array( ":id" => $orderid, ":uniacid" => $uniacid, ":openid" => $openid ));
$log = pdo_fetch("SELECT * FROM " . tablename("core_paylog") . " WHERE `uniacid`=:uniacid AND `module`=:module AND `tid`=:tid limit 1", array( ":uniacid" => $uniacid, ":module" => "ewei_shopv2", ":tid" => $ordersn ));

logging_run("哈哈1:".$openid);
logging_run("哈哈2:".$uniacid);
logging_run("哈哈3:".$orderid);
logging_run("哈哈4:".json_encode($order));
logging_run("哈哈5:".json_encode($log));

if( $log["status"] != 1 )
{
$record = array( );
$record["status"] = "1";
$record["type"] = "wechat";
pdo_update("core_paylog", $record, array( "plid" => $log["plid"] ));
$ret = array( );
$ret["result"] = "success";
$ret["type"] = "wechat";
$ret["from"] = "return";
$ret["tid"] = $log["tid"];
$ret["user"] = $log["openid"];
$ret["fee"] = $log["fee"];
$ret["weid"] = $log["weid"];
$ret["uniacid"] = $log["uniacid"];
logging_run("呵呵:".json_encode($ret));
m("order")->payResult($ret);
$this->postAiQiYi($order);

}
}else
{
$result = false;
}
// 返回状态给微信服务器
if ( $result )
{
$str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
}else
{
$str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
}
echo $str;
return $result;
}
/*
*随机字符串,不长于32位
*随机数生成算法
*/
private function nonce_str(){
return MD5(rand());
}

/**
* 生成签名
* @return 签名
*/
protected function makeSign($data)
{
//获取微信支付秘钥
$key = $this->key;
//去空
$data = array_filter($data);
//签名步骤一:按字典序排序参数
ksort($data);
$string_a = http_build_query($data);
$string_a = urldecode($string_a);
//签名步骤二:在string后加入KEY
$string_sign_temp = $string_a."&key=".$key;
//签名步骤三:MD5加密
$sign = md5($string_sign_temp);
// 签名步骤四:所有字符转为大写
$result=strtoupper($sign);
return $result;
}

/*
*生成data-XML数据体
*/
public function data(){
$time = time();
return [
'appid'=>$this->appid,
'mch_id'=>$this->mch_id,
'device_info'=>$this->device_info,
'nonce_str'=>$this->nonce_str(),
'sign_type'=>$this->sign_type,
'body'=>$this->body,
'detail'=>$this->detail,
'attach'=>$this->attach,
'out_trade_no'=>$this->out_trade_no,
'fee_type'=>$this->fee_type,
'total_fee'=>$this->total_fee,
'spbill_create_ip'=>$this->spbill_create_ip(),
'time_start'=>date("YmdHis",$time),
'time_expire'=>date("YmdHis",$time + 3600),
'goods_tag'=>$this->goods_tag,
'notify_url'=>$this->notify_url,
'trade_type'=>$this->trade_type,
'product_id'=>$this->product_id,
'limit_pay'=>$this->limit_pay,
'openid'=>$this->openid,
'receipt'=>$this->receipt,
'scene_info'=>"{'h5_info':{'type':'Wap','wap_url':'https://pay.qq.com','wap_name':'腾讯充值'}}",
];
}


/*
*获取用户的真实ip:58.144.154.238 123.139.87.194
*/
public function spbill_create_ip(){
// $cip = "unknown";
// if($_SERVER['REMOTE_ADDR']){
// $cip = $_SERVER['REMOTE_ADDR'];
// }else if(getenv("REMOTE_ADDR")){
// $cip = getenv("REMOTE_ADDR");
// }

if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$ip = getenv('HTTP_CLIENT_IP');
} elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$ip = getenv('REMOTE_ADDR');
} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// return preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
$cip = preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';

// var_dump($cip);
// load()->func('logging');
// logging_run("ip:".$cip);
return $cip;
}


/*
*数组转化为xml
*/
private function arrayToXml($arr)
{
$xml = '<xml>';
foreach ($arr as $key=>$val)
{
if (is_numeric($val)){
$xml.='<'.$key.'>'.$val.'</'.$key.'>';

}else{
$xml.='<'.$key.'><![CDATA['.$val.']]></'.$key.'>';
}
}
$xml.='</xml>';
return $xml;
}

/*
*xml转化为数组
*/
private function xmlToArray($xml)
{
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
}

/**
* 微信支付发起请求
*/
protected function curl_post_ssl($url, $data, $second=30,$aHeader=array())
{
$ch = curl_init();
//超时时间
curl_setopt($ch,CURLOPT_TIMEOUT,$second);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
//这里设置代理,如果有的话
//curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
//curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
if( count($aHeader) >= 1 ){
curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
}
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$data = curl_exec($ch);
if($data){
curl_close($ch);
return $data;
}
else {
$error = curl_errno($ch);
echo "call faild, errorCode:$error\n";
curl_close($ch);
return false;
}
}



/**
* @param $post_data
* @return mixed
* 爱奇艺
*/
public function postAiQiYi($order)
{
load()->func('logging');
logging_run("进来啦!");
$order_goods = pdo_fetch('SELECT total FROM '.tablename('ewei_shop_order_goods').' WHERE orderid=:orderid ORDER BY id DESC LIMIT 1',array('orderid'=>$order['id']));
$_good = pdo_fetch('SELECT goodssn,type FROM '.tablename('ewei_shop_goods').' where id = (SELECT goodsid FROM '.tablename('ewei_shop_order_goods').' WHERE orderid=:orderid ORDER BY id DESC LIMIT 1)',array('orderid'=>$order['id']));

logging_run("测试1:".json_encode($order_goods));
logging_run("测试2:".json_encode($_good));
logging_run("测试3:".json_encode($order));
if($_good['type'] == 2){
logging_run("测试4:".json_encode($_good['type']));
$post_data = [
'partnerNo'=>'SXNNKJ_ZC',//'toB_common_test',//合作方的唯一标识
'orderNo'=>$order['ordersn'],//订单号
'item'=>$_good['goodssn'],//$_good['333测试'],//333测试 产品编码
'amount'=>$order_goods['total'],//数量
'sum'=>$order['price']*100,//金额
'mobile'=>unserialize($order['carrier'])['carrier_mobile']//手机号码
];
}else{
logging_run("支付回调爱奇艺数据传递参数:不是虚拟产品");
return false;
}
$post_data['sign'] = $this->sign($post_data);
logging_run("测试5:".json_encode($post_data));
$curl = curl_init();
//设置抓取的url
curl_setopt($curl, CURLOPT_URL, '');
//设置头文件的信息作为数据流输出
curl_setopt($curl, CURLOPT_HEADER, 0);
//设置获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//设置post方式提交
curl_setopt($curl, CURLOPT_POST, 1);
//设置post数据
curl_setopt($curl, CURLOPT_POSTFIELDS,$post_data);
//执行命令
$data = curl_exec($curl);
//关闭URL请求
curl_close($curl);

logging_run("支付回调爱奇艺数据传递参数:".json_encode($post_data).'返回数据:'.$data,'','aiqiyi');
return json_decode($data);
}


/**
* @param $param
* @return string
* 签名
*/
public function sign($param)
{
// 参数排序
ksort($param);
// 生成待签名字符串
$signStr = '';
foreach ( $param as $key => $value ) {
$signStr = $signStr . $key . "=" . $value . "&";
}
$signStr = substr($signStr, 0, -1);
// 生成签名
$str = $signStr.'be7a16fdabd757f2';//' b0ee3c7f62760330';
$signature = md5($str);
return $signature;
}


}

posted on 2019-06-10 13:52  搞技术的雷先生  阅读(2981)  评论(0编辑  收藏  举报

导航