WxPay.Api.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. <?php
  2. require_once "WxPay.Exception.php";
  3. require_once "WxPay.Config.php";
  4. require_once "WxPay.Data.php";
  5. /**
  6. *
  7. * 接口访问类,包含所有微信支付API列表的封装,类中方法为static方法,
  8. * 每个接口有默认超时时间(除提交被扫支付为10s,上报超时时间为1s外,其他均为6s)
  9. * @author widyhu
  10. *
  11. */
  12. class WxPayApi
  13. {
  14. /**
  15. *
  16. * 统一下单,WxPayUnifiedOrder中out_trade_no、body、total_fee、trade_type必填
  17. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  18. * @param WxPayUnifiedOrder $inputObj
  19. * @param int $timeOut
  20. * @throws WxPayException
  21. * @return 成功时返回,其他抛异常
  22. */
  23. public static function unifiedOrder($inputObj, $timeOut = 6)
  24. {
  25. $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
  26. //检测必填参数
  27. if(!$inputObj->IsOut_trade_noSet()) {
  28. throw new WxPayException("缺少统一支付接口必填参数out_trade_no!");
  29. }else if(!$inputObj->IsBodySet()){
  30. throw new WxPayException("缺少统一支付接口必填参数body!");
  31. }else if(!$inputObj->IsTotal_feeSet()) {
  32. throw new WxPayException("缺少统一支付接口必填参数total_fee!");
  33. }else if(!$inputObj->IsTrade_typeSet()) {
  34. throw new WxPayException("缺少统一支付接口必填参数trade_type!");
  35. }
  36. //关联参数
  37. if($inputObj->GetTrade_type() == "JSAPI" && !$inputObj->IsOpenidSet()){
  38. throw new WxPayException("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!");
  39. }
  40. if($inputObj->GetTrade_type() == "NATIVE" && !$inputObj->IsProduct_idSet()){
  41. throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!");
  42. }
  43. //异步通知url未设置,则使用配置文件中的url
  44. if(!$inputObj->IsNotify_urlSet()){
  45. $inputObj->SetNotify_url(WxPayConfig::NOTIFY_URL);//异步通知url
  46. }
  47. $inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
  48. $inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
  49. $inputObj->SetSpbill_create_ip($_SERVER['REMOTE_ADDR']);//终端ip
  50. //$inputObj->SetSpbill_create_ip("1.1.1.1");
  51. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  52. //签名
  53. $inputObj->SetSign();
  54. $xml = $inputObj->ToXml();
  55. $startTimeStamp = self::getMillisecond();//请求开始时间
  56. $response = self::postXmlCurl($xml, $url, false, $timeOut);
  57. $result = WxPayResults::Init($response);
  58. self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
  59. return $result;
  60. }
  61. /**
  62. *
  63. * 查询订单,WxPayOrderQuery中out_trade_no、transaction_id至少填一个
  64. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  65. * @param WxPayOrderQuery $inputObj
  66. * @param int $timeOut
  67. * @throws WxPayException
  68. * @return 成功时返回,其他抛异常
  69. */
  70. public static function orderQuery($inputObj, $timeOut = 6)
  71. {
  72. $wepro_appid = D('Home/Front')->get_config_by_name('wepro_appid');
  73. $wepro_partnerid = D('Home/Front')->get_config_by_name('wepro_partnerid');
  74. $url = "https://api.mch.weixin.qq.com/pay/orderquery";
  75. //检测必填参数
  76. if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
  77. throw new WxPayException("订单查询接口中,out_trade_no、transaction_id至少填一个!");
  78. }
  79. $inputObj->SetAppid($wepro_appid);//公众账号ID
  80. $inputObj->SetMch_id($wepro_partnerid);//商户号
  81. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  82. $inputObj->SetSign();//签名
  83. $xml = $inputObj->ToXml();
  84. $startTimeStamp = self::getMillisecond();//请求开始时间
  85. $response = self::postXmlCurl($xml, $url, false, $timeOut);
  86. $result = WxPayResults::Init($response);
  87. self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
  88. return $result;
  89. }
  90. /**
  91. *
  92. * 关闭订单,WxPayCloseOrder中out_trade_no必填
  93. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  94. * @param WxPayCloseOrder $inputObj
  95. * @param int $timeOut
  96. * @throws WxPayException
  97. * @return 成功时返回,其他抛异常
  98. */
  99. public static function closeOrder($inputObj, $timeOut = 6)
  100. {
  101. $url = "https://api.mch.weixin.qq.com/pay/closeorder";
  102. //检测必填参数
  103. if(!$inputObj->IsOut_trade_noSet()) {
  104. throw new WxPayException("订单查询接口中,out_trade_no必填!");
  105. }
  106. $inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
  107. $inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
  108. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  109. $inputObj->SetSign();//签名
  110. $xml = $inputObj->ToXml();
  111. $startTimeStamp = self::getMillisecond();//请求开始时间
  112. $response = self::postXmlCurl($xml, $url, false, $timeOut);
  113. $result = WxPayResults::Init($response);
  114. self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
  115. return $result;
  116. }
  117. /**
  118. 发送红包接口
  119. **/
  120. public static function bonuspay($inputObj, $timeOut = 6)
  121. {
  122. $url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
  123. $param = array();
  124. $param['mch_billno'] = $inputObj['mch_billno'];
  125. $param['mch_id'] = WxPayConfig::MCHID;
  126. $param['wxappid'] = WxPayConfig::APPID;
  127. $param['nick_name'] = $inputObj['nick_name'];// urlencode($inputObj['nick_name']);//$inputObj['nick_name'];
  128. $param['send_name'] = $inputObj['nick_name'];//urlencode($inputObj['nick_name']);//$inputObj['send_name'];
  129. $param['re_openid'] = $inputObj['openid'];
  130. $param['total_amount'] = $inputObj['total_amount'];
  131. $param['min_value'] = $inputObj['total_amount'];
  132. $param['max_value'] = $inputObj['total_amount'];
  133. $param['total_num'] = 1;
  134. $param['wishing'] = '恭喜发财';//urlencode('恭喜发财');//'恭喜发财';
  135. $param['client_ip'] = $_SERVER['REMOTE_ADDR'];
  136. $param['act_name'] = '组团成功';//urlencode('组团成功');//'组团成功';
  137. //$param['act_id'] = '';
  138. $param['remark'] = '团长红包';//urlencode('团长红包');//'团长红包';
  139. $param['nonce_str'] = self::getNonceStr();
  140. $param['sign'] = self::MakeSignfh($param);
  141. $xml = self::arrdatetoxml($param);
  142. //$xml = iconv("UTF-8", "ISO8859-1", $xml);
  143. $startTimeStamp = self::getMillisecond();//请求开始时间
  144. //var_dump($startTimeStamp);die(); ISO8859-1
  145. $response = self::postXmlCurl($xml, $url, true, $timeOut);
  146. libxml_disable_entity_loader(true);
  147. $result = json_decode(json_encode(simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  148. $res_data = array();
  149. if($result['return_code']=='SUCCESS')
  150. {
  151. $res_data['ret'] = 1;
  152. $res_data['mes'] = $result['return_msg'];
  153. } else {
  154. $res_data['ret'] = 0;
  155. $res_data['mes'] = $result['return_msg'];
  156. }
  157. return $res_data;
  158. }
  159. public static function arrdatetoxml($values)
  160. {
  161. $xml = "<xml>";
  162. foreach ($values as $key=>$val)
  163. {
  164. if (is_numeric($val)){
  165. $xml.="<".$key.">".$val."</".$key.">";
  166. }else{
  167. $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
  168. }
  169. }
  170. $xml.="</xml>";
  171. return $xml;
  172. }
  173. /**
  174. * 生成签名
  175. * @return 签名,本函数不覆盖sign成员变量,如要设置签名需要调用SetSign方法赋值
  176. */
  177. public static function MakeSignfh($values)
  178. {
  179. $pay_key = D('Home/Front')->get_config_by_name('wepro_key');
  180. //签名步骤一:按字典序排序参数
  181. ksort($values);
  182. $string = self::ToUrlParamsfh($values);
  183. //var_dump($string);die();
  184. //签名步骤二:在string后加入KEY
  185. $string = $string . "&key=".$pay_key;
  186. //签名步骤三:MD5加密
  187. $string = md5($string);
  188. //签名步骤四:所有字符转为大写
  189. $result = strtoupper($string);
  190. return $result;
  191. }
  192. /**
  193. * 格式化参数格式化成url参数
  194. */
  195. public static function ToUrlParamsfh($values)
  196. {
  197. $buff = "";
  198. foreach ($values as $k => $v)
  199. {
  200. if($k != "sign" && $v != "" && !is_array($v)){
  201. $buff .= $k . "=" . $v . "&";
  202. }
  203. }
  204. $buff = trim($buff, "&");
  205. return $buff;
  206. }
  207. public static function payToUser($openid,$amount,$username,$desc,$partner_trade_no,$uniacid=0)
  208. {
  209. $is_open_yinpay = D('Home/Front')->get_config_by_name('is_open_yinpay');
  210. if( isset($is_open_yinpay) && $is_open_yinpay == 3 )
  211. {
  212. //特约商户
  213. //小程序appid
  214. $wepro_appid = D('Home/Front')->get_config_by_name('wepro_appid');
  215. //特约商户商户id
  216. $mchid = D('Home/Front')->get_config_by_name('wepro_sub_mch_id');
  217. //特约商户秘钥
  218. $wepro_key = D('Home/Front')->get_config_by_name('sup_wepro_key');
  219. }else{
  220. $wepro_appid = D('Home/Front')->get_config_by_name('wepro_appid');
  221. $mchid = D('Home/Front')->get_config_by_name('wepro_partnerid');
  222. $wepro_key = D('Home/Front')->get_config_by_name('wepro_key');
  223. }
  224. $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
  225. $params = array();
  226. $params['amount'] = $amount;
  227. $params['desc'] = $desc;
  228. $params['mch_appid'] = $wepro_appid;
  229. $params['mchid'] = $mchid;
  230. $params['nonce_str'] = self::getNonceStr();
  231. $params['partner_trade_no'] = $partner_trade_no;
  232. $params['openid'] = $openid;
  233. $params['check_name'] = 'FORCE_CHECK';
  234. $params['re_user_name'] = $username;
  235. $params['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'];
  236. $strs = "";
  237. if(!empty($params)){
  238. $p = ksort($params);
  239. if($p){
  240. $str = '';
  241. foreach ($params as $k=>$val){
  242. $str .= $k .'=' . $val . '&';
  243. }
  244. $strs = rtrim($str, '&');
  245. }
  246. }
  247. //$str = 'amount='.$params["amount"].'&check_name='.$params["check_name"].'&desc='.$params["desc"].'&mch_appid='.$params["mch_appid"].'&mchid='.$params["mchid"].'&nonce_str='.$params["nonce_str"].'&openid='.$params["openid"].'&partner_trade_no='.$params["partner_trade_no"].'&spbill_create_ip='.$params['spbill_create_ip'].'&key='.$wepro_key;
  248. $str = $strs.'&key='.$wepro_key;
  249. $sign = strtoupper(md5($str));
  250. $params['sign'] = $sign;
  251. $xml = self::arrdatetoxml($params);
  252. $is_open_yinpay = D('Home/Front')->get_config_by_name('is_open_yinpay');
  253. $response = self::postXmlCurl($xml, $url, true ,6 );
  254. libxml_disable_entity_loader(true);
  255. $result = json_decode(json_encode(simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  256. return $result;
  257. }
  258. /**
  259. *
  260. * 申请退款,WxPayRefund中out_trade_no、transaction_id至少填一个且
  261. * out_refund_no、total_fee、refund_fee、op_user_id为必填参数
  262. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  263. * @param WxPayRefund $inputObj
  264. * @param int $timeOut
  265. * @throws WxPayException
  266. * @return 成功时返回,其他抛异常
  267. */
  268. public static function refund($inputObj, $timeOut = 6,$from_type='weixin',$uniacid = 0)
  269. {
  270. $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
  271. //https://api.mch.weixin.qq.com/secapi/pay/refund
  272. $is_pro = false;
  273. //检测必填参数
  274. if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
  275. die("退款申请接口中,out_trade_no、transaction_id至少填一个!");
  276. throw new WxPayException("退款申请接口中,out_trade_no、transaction_id至少填一个!");
  277. }else if(!$inputObj->IsOut_refund_noSet()){
  278. die("退款申请接口中,缺少必填参数out_refund_no!");
  279. throw new WxPayException("退款申请接口中,缺少必填参数out_refund_no!");
  280. }else if(!$inputObj->IsTotal_feeSet()){
  281. die("退款申请接口中,缺少必填参数total_fee!");
  282. throw new WxPayException("退款申请接口中,缺少必填参数total_fee!");
  283. }else if(!$inputObj->IsRefund_feeSet()){
  284. die("退款申请接口中,缺少必填参数refund_fee!");
  285. throw new WxPayException("退款申请接口中,缺少必填参数refund_fee!");
  286. }else if(!$inputObj->IsOp_user_idSet()){
  287. die("退款申请接口中,缺少必填参数op_user_id!");
  288. throw new WxPayException("退款申请接口中,缺少必填参数op_user_id!");
  289. }
  290. //$inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
  291. if($from_type =='wepro')
  292. {
  293. $wepro_appid = D('Home/Front')->get_config_by_name('wepro_appid');
  294. $inputObj->SetAppid($wepro_appid);//公众账号ID
  295. }
  296. else if( $from_type == 'teweixin' )
  297. {
  298. //begin
  299. $wepro_appid = D('Home/Front')->get_config_by_name('wepro_fuwu_appid');
  300. $inputObj->SetAppid($wepro_appid);
  301. //end
  302. }
  303. else{
  304. $wepro_appid = D('Home/Front')->get_config_by_name('wepro_appid');
  305. $inputObj->SetAppid($wepro_appid);//公众账号ID
  306. }
  307. $mchid = D('Home/Front')->get_config_by_name('wepro_partnerid');
  308. if( $from_type == 'teweixin' )
  309. {
  310. //begin
  311. $mchid = D('Home/Front')->get_config_by_name('wepro_fuwu_partnerid');
  312. //end
  313. }
  314. $inputObj->SetMch_id($mchid);//商户号
  315. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  316. if( $from_type == 'teweixin' )
  317. {
  318. $sub_appid = D('Home/Front')->get_config_by_name('wepro_appid');
  319. $sub_mch_id = D('Home/Front')->get_config_by_name('wepro_sub_mch_id');
  320. //begin
  321. $inputObj->SetSub_appid($sub_appid);//商户号
  322. $inputObj->SetSub_mch_id($sub_mch_id);//商户号
  323. $is_pro = true;
  324. //end
  325. }
  326. $inputObj->SetSign();//签名
  327. $xml = $inputObj->ToXml();
  328. $startTimeStamp = self::getMillisecond();//请求开始时间
  329. //var_dump($startTimeStamp);die();
  330. // $response = self::postXmlCurl($xml, $url, true, $timeOut);
  331. $response = self::postXmlCurl($xml, $url, true, $timeOut,$uniacid,$is_pro);//
  332. //var_dump($response);die();
  333. $result = WxPayResults::Init($response);
  334. self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
  335. return $result;
  336. }
  337. /**
  338. *
  339. * 查询退款
  340. * 提交退款申请后,通过调用该接口查询退款状态。退款有一定延时,
  341. * 用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。
  342. * WxPayRefundQuery中out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个
  343. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  344. * @param WxPayRefundQuery $inputObj
  345. * @param int $timeOut
  346. * @throws WxPayException
  347. * @return 成功时返回,其他抛异常
  348. */
  349. public static function refundQuery($inputObj, $timeOut = 6)
  350. {
  351. $url = "https://api.mch.weixin.qq.com/pay/refundquery";
  352. //检测必填参数
  353. if(!$inputObj->IsOut_refund_noSet() &&
  354. !$inputObj->IsOut_trade_noSet() &&
  355. !$inputObj->IsTransaction_idSet() &&
  356. !$inputObj->IsRefund_idSet()) {
  357. throw new WxPayException("退款查询接口中,out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个!");
  358. }
  359. $inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
  360. $inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
  361. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  362. $inputObj->SetSign();//签名
  363. $xml = $inputObj->ToXml();
  364. $startTimeStamp = self::getMillisecond();//请求开始时间
  365. $response = self::postXmlCurl($xml, $url, false, $timeOut);
  366. $result = WxPayResults::Init($response);
  367. self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
  368. return $result;
  369. }
  370. /**
  371. * 下载对账单,WxPayDownloadBill中bill_date为必填参数
  372. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  373. * @param WxPayDownloadBill $inputObj
  374. * @param int $timeOut
  375. * @throws WxPayException
  376. * @return 成功时返回,其他抛异常
  377. */
  378. public static function downloadBill($inputObj, $timeOut = 6)
  379. {
  380. $url = "https://api.mch.weixin.qq.com/pay/downloadbill";
  381. //检测必填参数
  382. if(!$inputObj->IsBill_dateSet()) {
  383. throw new WxPayException("对账单接口中,缺少必填参数bill_date!");
  384. }
  385. $inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
  386. $inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
  387. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  388. $inputObj->SetSign();//签名
  389. $xml = $inputObj->ToXml();
  390. $response = self::postXmlCurl($xml, $url, false, $timeOut);
  391. if(substr($response, 0 , 5) == "<xml>"){
  392. return "";
  393. }
  394. return $response;
  395. }
  396. /**
  397. * 提交被扫支付API
  398. * 收银员使用扫码设备读取微信用户刷卡授权码以后,二维码或条码信息传送至商户收银台,
  399. * 由商户收银台或者商户后台调用该接口发起支付。
  400. * WxPayWxPayMicroPay中body、out_trade_no、total_fee、auth_code参数必填
  401. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  402. * @param WxPayWxPayMicroPay $inputObj
  403. * @param int $timeOut
  404. */
  405. public static function micropay($inputObj, $timeOut = 10)
  406. {
  407. $url = "https://api.mch.weixin.qq.com/pay/micropay";
  408. //检测必填参数
  409. if(!$inputObj->IsBodySet()) {
  410. throw new WxPayException("提交被扫支付API接口中,缺少必填参数body!");
  411. } else if(!$inputObj->IsOut_trade_noSet()) {
  412. throw new WxPayException("提交被扫支付API接口中,缺少必填参数out_trade_no!");
  413. } else if(!$inputObj->IsTotal_feeSet()) {
  414. throw new WxPayException("提交被扫支付API接口中,缺少必填参数total_fee!");
  415. } else if(!$inputObj->IsAuth_codeSet()) {
  416. throw new WxPayException("提交被扫支付API接口中,缺少必填参数auth_code!");
  417. }
  418. $inputObj->SetSpbill_create_ip($_SERVER['REMOTE_ADDR']);//终端ip
  419. $inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
  420. $inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
  421. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  422. $inputObj->SetSign();//签名
  423. $xml = $inputObj->ToXml();
  424. $startTimeStamp = self::getMillisecond();//请求开始时间
  425. $response = self::postXmlCurl($xml, $url, false, $timeOut);
  426. $result = WxPayResults::Init($response);
  427. self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
  428. return $result;
  429. }
  430. /**
  431. *
  432. * 撤销订单API接口,WxPayReverse中参数out_trade_no和transaction_id必须填写一个
  433. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  434. * @param WxPayReverse $inputObj
  435. * @param int $timeOut
  436. * @throws WxPayException
  437. */
  438. public static function reverse($inputObj, $timeOut = 6)
  439. {
  440. $url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";
  441. //检测必填参数
  442. if(!$inputObj->IsOut_trade_noSet() && !$inputObj->IsTransaction_idSet()) {
  443. throw new WxPayException("撤销订单API接口中,参数out_trade_no和transaction_id必须填写一个!");
  444. }
  445. $inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
  446. $inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
  447. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  448. $inputObj->SetSign();//签名
  449. $xml = $inputObj->ToXml();
  450. $startTimeStamp = self::getMillisecond();//请求开始时间
  451. $response = self::postXmlCurl($xml, $url, true, $timeOut);
  452. $result = WxPayResults::Init($response);
  453. self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
  454. return $result;
  455. }
  456. /**
  457. *
  458. * 测速上报,该方法内部封装在report中,使用时请注意异常流程
  459. * WxPayReport中interface_url、return_code、result_code、user_ip、execute_time_必填
  460. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  461. * @param WxPayReport $inputObj
  462. * @param int $timeOut
  463. * @throws WxPayException
  464. * @return 成功时返回,其他抛异常
  465. */
  466. public static function report($inputObj, $timeOut = 1)
  467. {
  468. $url = "https://api.mch.weixin.qq.com/payitil/report";
  469. //检测必填参数
  470. if(!$inputObj->IsInterface_urlSet()) {
  471. throw new WxPayException("接口URL,缺少必填参数interface_url!");
  472. } if(!$inputObj->IsReturn_codeSet()) {
  473. throw new WxPayException("返回状态码,缺少必填参数return_code!");
  474. } if(!$inputObj->IsResult_codeSet()) {
  475. throw new WxPayException("业务结果,缺少必填参数result_code!");
  476. } if(!$inputObj->IsUser_ipSet()) {
  477. throw new WxPayException("访问接口IP,缺少必填参数user_ip!");
  478. } if(!$inputObj->IsExecute_time_Set()) {
  479. throw new WxPayException("接口耗时,缺少必填参数execute_time_!");
  480. }
  481. $inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
  482. $inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
  483. $inputObj->SetUser_ip($_SERVER['REMOTE_ADDR']);//终端ip
  484. $inputObj->SetTime(date("YmdHis"));//商户上报时间
  485. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  486. $inputObj->SetSign();//签名
  487. $xml = $inputObj->ToXml();
  488. $startTimeStamp = self::getMillisecond();//请求开始时间
  489. $response = self::postXmlCurl($xml, $url, false, $timeOut);
  490. return $response;
  491. }
  492. /**
  493. *
  494. * 生成二维码规则,模式一生成支付二维码
  495. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  496. * @param WxPayBizPayUrl $inputObj
  497. * @param int $timeOut
  498. * @throws WxPayException
  499. * @return 成功时返回,其他抛异常
  500. */
  501. public static function bizpayurl($inputObj, $timeOut = 6)
  502. {
  503. if(!$inputObj->IsProduct_idSet()){
  504. throw new WxPayException("生成二维码,缺少必填参数product_id!");
  505. }
  506. $inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
  507. $inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
  508. $inputObj->SetTime_stamp(time());//时间戳
  509. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  510. $inputObj->SetSign();//签名
  511. return $inputObj->GetValues();
  512. }
  513. /**
  514. *
  515. * 转换短链接
  516. * 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX),
  517. * 减小二维码数据量,提升扫描速度和精确度。
  518. * appid、mchid、spbill_create_ip、nonce_str不需要填入
  519. * @param WxPayShortUrl $inputObj
  520. * @param int $timeOut
  521. * @throws WxPayException
  522. * @return 成功时返回,其他抛异常
  523. */
  524. public static function shorturl($inputObj, $timeOut = 6)
  525. {
  526. $url = "https://api.mch.weixin.qq.com/tools/shorturl";
  527. //检测必填参数
  528. if(!$inputObj->IsLong_urlSet()) {
  529. throw new WxPayException("需要转换的URL,签名用原串,传输需URL encode!");
  530. }
  531. $inputObj->SetAppid(WxPayConfig::APPID);//公众账号ID
  532. $inputObj->SetMch_id(WxPayConfig::MCHID);//商户号
  533. $inputObj->SetNonce_str(self::getNonceStr());//随机字符串
  534. $inputObj->SetSign();//签名
  535. $xml = $inputObj->ToXml();
  536. $startTimeStamp = self::getMillisecond();//请求开始时间
  537. $response = self::postXmlCurl($xml, $url, false, $timeOut);
  538. $result = WxPayResults::Init($response);
  539. self::reportCostTime($url, $startTimeStamp, $result);//上报请求花费时间
  540. return $result;
  541. }
  542. /**
  543. *
  544. * 支付结果通用通知
  545. * @param function $callback
  546. * 直接回调函数使用方法: notify(you_function);
  547. * 回调类成员函数方法:notify(array($this, you_function));
  548. * $callback 原型为:function function_name($data){}
  549. */
  550. public static function notify($callback, &$msg)
  551. {
  552. //获取通知的数据
  553. if( !isset($GLOBALS['HTTP_RAW_POST_DATA']) )
  554. {
  555. $xml = file_get_contents('php://input');
  556. }else{
  557. $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
  558. }
  559. //如果返回成功则验证签名
  560. try {
  561. $result = WxPayResults::Init($xml);
  562. } catch (WxPayException $e){
  563. $msg = $e->errorMessage();
  564. return false;
  565. }
  566. return call_user_func($callback, $result);
  567. }
  568. /**
  569. *
  570. * 产生随机字符串,不长于32位
  571. * @param int $length
  572. * @return 产生的随机字符串
  573. */
  574. public static function getNonceStr($length = 32)
  575. {
  576. $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
  577. $str ="";
  578. for ( $i = 0; $i < $length; $i++ ) {
  579. $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
  580. }
  581. return $str;
  582. }
  583. /**
  584. * 直接输出xml
  585. * @param string $xml
  586. */
  587. public static function replyNotify($xml)
  588. {
  589. echo $xml;
  590. }
  591. /**
  592. *
  593. * 上报数据, 上报的时候将屏蔽所有异常流程
  594. * @param string $usrl
  595. * @param int $startTimeStamp
  596. * @param array $data
  597. */
  598. private static function reportCostTime($url, $startTimeStamp, $data)
  599. {
  600. //如果不需要上报数据
  601. if(WxPayConfig::REPORT_LEVENL == 0){
  602. return;
  603. }
  604. //如果仅失败上报
  605. if(WxPayConfig::REPORT_LEVENL == 1 &&
  606. array_key_exists("return_code", $data) &&
  607. $data["return_code"] == "SUCCESS" &&
  608. array_key_exists("result_code", $data) &&
  609. $data["result_code"] == "SUCCESS")
  610. {
  611. return;
  612. }
  613. //上报逻辑
  614. $endTimeStamp = self::getMillisecond();
  615. $objInput = new WxPayReport();
  616. $objInput->SetInterface_url($url);
  617. $objInput->SetExecute_time_($endTimeStamp - $startTimeStamp);
  618. //返回状态码
  619. if(array_key_exists("return_code", $data)){
  620. $objInput->SetReturn_code($data["return_code"]);
  621. }
  622. //返回信息
  623. if(array_key_exists("return_msg", $data)){
  624. $objInput->SetReturn_msg($data["return_msg"]);
  625. }
  626. //业务结果
  627. if(array_key_exists("result_code", $data)){
  628. $objInput->SetResult_code($data["result_code"]);
  629. }
  630. //错误代码
  631. if(array_key_exists("err_code", $data)){
  632. $objInput->SetErr_code($data["err_code"]);
  633. }
  634. //错误代码描述
  635. if(array_key_exists("err_code_des", $data)){
  636. $objInput->SetErr_code_des($data["err_code_des"]);
  637. }
  638. //商户订单号
  639. if(array_key_exists("out_trade_no", $data)){
  640. $objInput->SetOut_trade_no($data["out_trade_no"]);
  641. }
  642. //设备号
  643. if(array_key_exists("device_info", $data)){
  644. $objInput->SetDevice_info($data["device_info"]);
  645. }
  646. try{
  647. self::report($objInput);
  648. } catch (WxPayException $e){
  649. //不做任何处理
  650. }
  651. }
  652. /**
  653. * 以post方式提交xml到对应的接口url
  654. *
  655. * @param string $xml 需要post的xml数据
  656. * @param string $url url
  657. * @param bool $useCert 是否需要证书,默认不需要
  658. * @param int $second url执行超时时间,默认30s
  659. * @throws WxPayException
  660. */
  661. private static function postXmlCurl($xml, $url, $useCert = false, $second = 30, $uniacid=0,$is_pro = false)
  662. {
  663. $ch = curl_init();
  664. //设置超时
  665. curl_setopt($ch, CURLOPT_TIMEOUT, $second);
  666. //如果有配置代理这里就设置代理
  667. /**
  668. if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
  669. && WxPayConfig::CURL_PROXY_PORT != 0){
  670. curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
  671. curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
  672. }
  673. **/
  674. curl_setopt($ch,CURLOPT_URL, $url);
  675. curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
  676. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//严格校验
  677. //设置header
  678. curl_setopt($ch, CURLOPT_HEADER, FALSE);
  679. //要求结果为字符串且输出到屏幕上
  680. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  681. if($useCert == true){
  682. $path = ROOT_PATH.'/Data/wxpaylogs/';
  683. // $wechat_apiclient_cert_pem = D('Home/Front')->get_config_by_name('wechat_apiclient_cert_pem');
  684. // $wechat_apiclient_key_pem = D('Home/Front')->get_config_by_name('wechat_apiclient_key_pem');
  685. if($is_pro){
  686. $wechat_apiclient_cert_pem = D('Home/Front')->get_config_by_name('sup_wechat_apiclient_cert_pem');
  687. $wechat_apiclient_key_pem = D('Home/Front')->get_config_by_name('sup_wechat_apiclient_key_pem');
  688. // dump($wechat_apiclient_key_pem);die;
  689. }else{
  690. $wechat_apiclient_cert_pem = D('Home/Front')->get_config_by_name('wechat_apiclient_cert_pem');
  691. $wechat_apiclient_key_pem = D('Home/Front')->get_config_by_name('wechat_apiclient_key_pem');
  692. }
  693. $file_cert_name = mt_rand(1,99).'_cert.pem';
  694. $file_key_name = mt_rand(100,999).'_key.pem';
  695. file_put_contents($path.$file_cert_name,$wechat_apiclient_cert_pem);
  696. file_put_contents($path.$file_key_name,$wechat_apiclient_key_pem);
  697. //设置证书
  698. //使用证书:cert 与 key 分别属于两个.pem文件
  699. curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  700. curl_setopt($ch,CURLOPT_SSLCERT, $path.$file_cert_name );
  701. curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
  702. curl_setopt($ch,CURLOPT_SSLKEY, $path.$file_key_name );
  703. }
  704. //post提交方式
  705. curl_setopt($ch, CURLOPT_POST, TRUE);
  706. curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  707. //运行curl
  708. $data = curl_exec($ch);
  709. //var_dump( $data);die();
  710. //返回结果
  711. if($data){
  712. if($useCert == true)
  713. {
  714. unlink($path.$file_cert_name);
  715. unlink($path.$file_key_name);
  716. }
  717. curl_close($ch);
  718. return $data;
  719. } else {
  720. $error = curl_errno($ch);
  721. curl_close($ch);
  722. throw new WxPayException("curl出错,错误码:$error");
  723. }
  724. }
  725. //特约商户提现
  726. private static function sup_postXmlCurl($xml, $url, $useCert = false, $second = 30, $uniacid=0)
  727. {
  728. $ch = curl_init();
  729. //设置超时
  730. curl_setopt($ch, CURLOPT_TIMEOUT, $second);
  731. //如果有配置代理这里就设置代理
  732. /**
  733. if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
  734. && WxPayConfig::CURL_PROXY_PORT != 0){
  735. curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
  736. curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
  737. }
  738. **/
  739. curl_setopt($ch,CURLOPT_URL, $url);
  740. curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
  741. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);//严格校验
  742. //设置header
  743. curl_setopt($ch, CURLOPT_HEADER, FALSE);
  744. //要求结果为字符串且输出到屏幕上
  745. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  746. if($useCert == true){
  747. $path = ROOT_PATH.'/Data/wxpaylogs/';
  748. $wechat_apiclient_cert_pem = D('Home/Front')->get_config_by_name('sup_wechat_apiclient_cert_pem');
  749. $wechat_apiclient_key_pem = D('Home/Front')->get_config_by_name('sup_wechat_apiclient_key_pem');
  750. $file_cert_name = mt_rand(1,99).'_cert.pem';
  751. $file_key_name = mt_rand(100,999).'_key.pem';
  752. file_put_contents($path.$file_cert_name,$wechat_apiclient_cert_pem);
  753. file_put_contents($path.$file_key_name,$wechat_apiclient_key_pem);
  754. //设置证书
  755. //使用证书:cert 与 key 分别属于两个.pem文件
  756. curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  757. curl_setopt($ch,CURLOPT_SSLCERT, $path.$file_cert_name );
  758. curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
  759. curl_setopt($ch,CURLOPT_SSLKEY, $path.$file_key_name );
  760. }
  761. //post提交方式
  762. curl_setopt($ch, CURLOPT_POST, TRUE);
  763. curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  764. //运行curl
  765. $data = curl_exec($ch);
  766. //var_dump( $data);die();
  767. //返回结果
  768. $error = curl_errno($ch);
  769. if($data){
  770. if($useCert == true)
  771. {
  772. unlink($path.$file_cert_name);
  773. unlink($path.$file_key_name);
  774. }
  775. curl_close($ch);
  776. return $data;
  777. } else {
  778. $error = curl_errno($ch);
  779. curl_close($ch);
  780. throw new WxPayException("curl出错,错误码:$error");
  781. }
  782. }
  783. /**
  784. * 获取毫秒级别的时间戳
  785. */
  786. private static function getMillisecond()
  787. {
  788. //获取毫秒的时间戳
  789. $time = explode ( " ", microtime () );
  790. $time = $time[1] . ($time[0] * 1000);
  791. $time2 = explode( ".", $time );
  792. $time = $time2[0];
  793. return $time;
  794. }
  795. }