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