WxpayH5.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. <?php
  2. /*
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fecshop\services\payment;
  10. //use fecshop\models\mysqldb\IpnMessage;
  11. use fecshop\services\Service;
  12. use yii\base\InvalidConfigException;
  13. use Yii;
  14. use Monolog\Handler\IFTTTHandler;
  15. /**
  16. * Payment wxpay services.
  17. * @author Alex Chang<1692576541@qq.com>
  18. * @since 1.0
  19. */
  20. class WxpayH5 extends Service
  21. {
  22. public $devide;
  23. public $configFile;
  24. public $subjectMaxLength = 30;
  25. public $tradeType;
  26. public $scanCodeBody = '微信H5支付';
  27. public $deviceInfo = 'WEB';
  28. public $expireTime = 600;
  29. protected $_order;
  30. // 允许更改的订单状态,不存在这里面的订单状态不允许修改
  31. protected $_allowChangOrderStatus;
  32. public function init()
  33. {
  34. ini_set('date.timezone', 'Asia/Shanghai');
  35. parent::init();
  36. $wxpayConfigFile = Yii::getAlias($this->configFile);
  37. if (!is_file($wxpayConfigFile)) {
  38. throw new InvalidConfigException('wxpay config file:['.$wxpayConfigFile.'] is not exist');
  39. }
  40. require_once($wxpayConfigFile);
  41. $wxpayApiFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Api.php');
  42. //$wxpayDataFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Data.php');
  43. $wxpayNotifyFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Notify.php');
  44. //$wxpayExceptionFile = Yii::getAlias('@fecshop/lib/wxpay/lib/WxPay.Exception.php');
  45. $wxpayJsApiPayPayFile = Yii::getAlias('@fecshop/lib/wxpay/example/WxPay.JsApiPay.php');
  46. //$wxpayNativePayFile = Yii::getAlias('@fecshop/lib/wxpay/example/WxPay.NativePay.php');
  47. $wxpayLogFile = Yii::getAlias('@fecshop/lib/wxpay/example/log.php');
  48. require_once($wxpayApiFile);
  49. //require_once($wxpayDataFile);
  50. require_once($wxpayNotifyFile);
  51. //require_once($wxpayExceptionFile);
  52. require_once($wxpayJsApiPayPayFile);
  53. require_once($wxpayLogFile);
  54. //交易类型
  55. //JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里
  56. //MICROPAY--刷卡支付,刷卡支付有单独的支付接口,不调用统一下单接口
  57. $this->tradeType = 'MWEB';
  58. $this->_allowChangOrderStatus = [
  59. Yii::$service->order->payment_status_pending,
  60. Yii::$service->order->payment_status_processing,
  61. ];
  62. }
  63. /**
  64. * 接收IPN消息的url,接收微信支付的异步消息,进而更改订单状态。
  65. */
  66. public function ipn()
  67. {
  68. $notifyFile = Yii::getAlias('@fecshop/services/payment/wxpay/notify.php');
  69. require_once($notifyFile);
  70. \Yii::info('begin ipn', 'fecshop_debug');
  71. $notify = new \PayNotifyCallBack();
  72. $notify->Handle(false);
  73. }
  74. /**
  75. * @param $data | Array 数据格式如下:
  76. * array(18) {
  77. * ["appid"]=> string(18) "wx426b3015555a46be"
  78. * ["attach"]=>string(24) "微信支付测试产品"
  79. * ["bank_type"]=>string(3) "CFT"
  80. * ["cash_fee"]=>string(1) "1"
  81. * ["device_info"]=>string(3) "WEB"
  82. * ["fee_type"]=> string(3) "CNY"
  83. * ["is_subscribe"]=>string(1) "N"
  84. * ["mch_id"]=>string(10) "1900009851"
  85. * ["nonce_str"]=> string(32) "e91xn1hwgyw9ox5zecdag1l86vrhi94l"
  86. * ["openid"]=>string(28) "oHZx6uKw5nrwZmEfgIX8poeQIucw"
  87. * ["out_trade_no"]=>string(10) "1100000953"
  88. * ["result_code"]=>string(7) "SUCCESS"
  89. * ["return_code"]=>string(7) "SUCCESS"
  90. * ["sign"]=>string(32) "589AC2046E667584FF1967C3C091259A"
  91. * ["time_end"]=>string(14) "20171106160124"
  92. * ["total_fee"]=>string(1) "1"
  93. * ["trade_type"]=>string(6) "NATIVE"
  94. * ["transaction_id"]=>string(28) "4200000006201711062859872774"
  95. * }
  96. * 在微信sdk验证数据安全性后,会执行该函数,用来验证订单的金额的正确性
  97. * 如果订单数据没有问题,则更改订单状态。
  98. */
  99. public function ipnUpdateOrder($data)
  100. {
  101. \Yii::info('ipn order process', 'fecshop_debug');
  102. $incrementId = $data['out_trade_no'];
  103. $transaction_id = $data['transaction_id'];
  104. $total_fee = $data['total_fee'];
  105. $fee_type = $data['fee_type'];
  106. if ($incrementId && $transaction_id && $total_fee) {
  107. $this->_order = Yii::$service->order->getByIncrementId($incrementId);
  108. Yii::$service->payment->setPaymentMethod($this->_order['payment_method']);
  109. $base_grand_total = $this->_order['base_grand_total'];
  110. $order_total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY');
  111. \Yii::info('check order totla amouont['.($order_total_amount * 100).' == '.$total_fee.']', 'fecshop_debug');
  112. // 微信支付的人民币单位为分
  113. if(bccomp($order_total_amount * 100, $total_fee) !== 0){
  114. return false;
  115. }
  116. \Yii::info('updateOrderInfo', 'fecshop_debug');
  117. // 更改订单状态
  118. if ($this->updateOrderInfo($incrementId, $transaction_id, false)) { //支付成功调用服务执行订单状态改变,清空购物车和发送邮件操作
  119. \Yii::info('updateOrderInfo Success', 'fecshop_debug');
  120. return true;
  121. }
  122. }
  123. }
  124. public function getOpenidUrl($baseUrl)
  125. {
  126. $tools = new \JsApiPay();
  127. return $tools->GetOpenidUrl($baseUrl);
  128. }
  129. function postXmlCurl($xml,$url,$second = 30){
  130. $ch = curl_init();
  131. //设置超时
  132. curl_setopt($ch, CURLOPT_TIMEOUT, $second);
  133. curl_setopt($ch,CURLOPT_URL, $url);
  134. curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
  135. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
  136. //设置 header
  137. curl_setopt($ch, CURLOPT_HEADER, FALSE);
  138. //要求结果为字符串且输出到屏幕上
  139. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  140. //post 提交方式
  141. curl_setopt($ch, CURLOPT_POST, TRUE);
  142. curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  143. //运行 curl
  144. $data = curl_exec($ch);
  145. //返回结果
  146. if($data){
  147. curl_close($ch);
  148. return $data;
  149. }else{
  150. $error = curl_errno($ch);
  151. curl_close($ch);
  152. echo "curl 出错,错误码:$error"."<br>";
  153. }
  154. }
  155. /**
  156. * @param $code | string 传递的微信code
  157. */
  158. public function getScanCodeStart($code = "")
  159. {
  160. // 根据订单得到json格式的微信支付参数。
  161. $trade_info = $this->getStartBizContentAndSetPaymentMethod();
  162. if (!$trade_info) {
  163. Yii::$service->helper->errors->add('generate wxpay bizContent error');
  164. return false;
  165. }
  166. $money= $trade_info['total_amount'] * 100; //微信支付的单位为分,所以要乘以100; //充值金额 微信支付单位为分
  167. $userip = Yii::$service->helper->getCustomerIp();; //获得用户设备 IP
  168. $appid = \WxPayConfig::APPID ; //应用 APPID
  169. $mch_id = \WxPayConfig::MCHID; //微信支付商户号
  170. $key = \WxPayConfig::KEY; //微信商户 API 密钥
  171. $out_trade_no = $trade_info['increment_id'];//平台内部订单号
  172. $nonce_str = Yii::$service->helper->createNoncestr();//随机字符串
  173. $body = $this->scanCodeBody;//内容
  174. $total_fee = $money; //金额
  175. $spbill_create_ip = $userip; //IP
  176. $notify_url = Yii::$service->payment->getStandardIpnUrl(); //回调地址
  177. $trade_type = $this->tradeType;//交易类型 具体看 API 里面有详细介绍
  178. //$scene_info ='{"h5_info":{"type":"Wap","wap_url":"http://qq52o.me","wap_name":"支付"}}';//场景信息 必要参数
  179. //echo $openId;exit;
  180. $wap_url = Yii::$service->url->homeUrl();
  181. $scene_info ='{"h5_info":{"type":"Wap","wap_url":"'.$wap_url.'","wap_name":"'.$this->scanCodeBody.'"}}';//场景信息 必要参数
  182. $signA ="appid=$appid&attach=$out_trade_no&body=$body&mch_id=$mch_id&nonce_str=$nonce_str&notify_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";
  183. $strSignTmp = $signA."&key=$key"; //拼接字符串 注意顺序微信有个测试网址 顺序按照他的来 直接点下面的校正测试 包括下面 XML 是否正确
  184. $sign = strtoupper(MD5($strSignTmp)); // MD5 后转换成大写
  185. $post_data = "<xml>
  186. <appid>$appid</appid>
  187. <mch_id>$mch_id</mch_id>
  188. <body>$body</body>
  189. <out_trade_no>$out_trade_no</out_trade_no>
  190. <total_fee>$total_fee</total_fee>
  191. <spbill_create_ip>$spbill_create_ip</spbill_create_ip>
  192. <notify_url>$notify_url</notify_url>
  193. <trade_type>$trade_type</trade_type>
  194. <scene_info>$scene_info</scene_info>
  195. <attach>$out_trade_no</attach>
  196. <nonce_str>$nonce_str</nonce_str>
  197. <sign>$sign</sign>
  198. </xml>";//拼接成 XML 格式
  199. $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信传参地址
  200. $dataxml = $this->postXmlCurl($post_data,$url); //后台 POST 微信传参地址 同时取得微信返回的参数
  201. $objectxml = (array)simplexml_load_string($dataxml, 'SimpleXMLElement', LIBXML_NOCDATA); //将微信返回的 XML 转换成数组
  202. return $objectxml;
  203. /*
  204. // 根据订单得到json格式的微信支付参数。
  205. $trade_info = $this->getStartBizContentAndSetPaymentMethod();
  206. if (!$trade_info) {
  207. Yii::$service->helper->errors->add('generate wxpay bizContent error');
  208. return false;
  209. }
  210. $client_ip = Yii::$service->helper->getCustomerIp();
  211. //①、获取用户openid
  212. $tools = new \JsApiPay();
  213. if (!$code) {
  214. $openId = $tools->GetOpenid();
  215. } else {
  216. $openId = $tools->GetOpenidByCode($code);
  217. }
  218. //echo $openId;exit;
  219. $wap_url = Yii::$service->url->homeUrl();
  220. $wap_name = '微信H5支付';
  221. $scene_info ='{"h5_info":{"type":"Wap","wap_url":"'.$wap_url.'","wap_name":"'.wap_name.'"}}';//场景信息 必要参数
  222. //②、统一下单
  223. $input = new \WxPayUnifiedOrder();
  224. //$notify_url = Yii::$service->url->getUrl("payment/wxpayjsapi/ipn"); ////获取支付配置中的返回ipn url
  225. $notify_url = Yii::$service->payment->getStandardIpnUrl();
  226. //$notify = new \NativePay();
  227. //$input = new \WxPayUnifiedOrder();
  228. $input->SetBody($this->scanCodeBody);
  229. //$input->SetAttach("商店的额外的自定义数据");
  230. $input->SetAttach($trade_info['subject']);
  231. $input->SetDevice_info($this->deviceInfo); // 设置设备号
  232. if ($trade_info['coupon_code']) {
  233. $input->SetGoods_tag($trade_info['coupon_code']); //设置商品标记,代金券或立减优惠功能的参数
  234. }
  235. $input->SetOut_trade_no($trade_info['increment_id']); // Fecshop 订单号
  236. $orderTotal = $trade_info['total_amount'] * 100; //微信支付的单位为分,所以要乘以100
  237. $input->SetTotal_fee($orderTotal);
  238. $input->SetTime_start(date("YmdHis"));
  239. $input->SetTime_expire($this->getShangHaiExpireTime($this->expireTime));
  240. $input->SetNotify_url($notify_url); //通知地址 改成自己接口通知的接口,要有公网域名,测试时直接行动此接口会产生日志
  241. $input->SetTrade_type($this->tradeType);
  242. $input->SetSpbill_create_ip($client_ip);
  243. $input->SetSceneInfo($scene_info);
  244. $input->SetProduct_id($trade_info['product_ids']); //此为二维码中包含的商品ID
  245. //$input->SetOpenid($openId);
  246. //var_dump($input);
  247. $result = \WxPayApi::wapUnifiedOrder($input);
  248. return $result;
  249. */
  250. }
  251. //打印输出数组信息
  252. function printf_info($data)
  253. {
  254. foreach($data as $key=>$value){
  255. echo "<font color='#00ff55;'>$key</font> : $value <br/>";
  256. }
  257. }
  258. public function getShangHaiExpireTime($expire_time)
  259. {
  260. $timezone_out = date_default_timezone_get();
  261. date_default_timezone_set('Asia/Shanghai');
  262. $r_time = date("YmdHis", time() + $expire_time);
  263. date_default_timezone_set($timezone_out);
  264. return $r_time;
  265. }
  266. public function scanCodeCheckTradeIsSuccess($out_trade_no)
  267. {
  268. $result = Yii::$service->payment->wxpay->queryOrderByOut($out_trade_no);
  269. if (is_array($result) && !empty($result)) {
  270. $trade_state = $result['trade_state']; //最终的交易状态,必须为SUCCESS才是交易成功
  271. $return_code = $result['result_code'];
  272. $trade_type = $result['trade_type']; //获取交易方式,这里使用的是扫码支付native
  273. $out_trade_no = $result['out_trade_no'];
  274. $total_amount = $result['total_fee'];
  275. $seller_id = $result['mch_id'];
  276. $auth_app_id = $result['appid'];
  277. $trade_no = $result['transaction_id'];
  278. $checkOrderStatus = Yii::$service->payment->wxpay->checkOrder($trade_state, $return_code, $trade_type, $out_trade_no, $total_amount, $seller_id, $auth_app_id);
  279. if ($checkOrderStatus) {
  280. return $this->updateOrderInfo($out_trade_no, $trade_no);
  281. }
  282. }
  283. }
  284. /**
  285. * 通过微信接口查询交易信息
  286. * @param unknown $out_trade_no
  287. */
  288. public function queryOrderByOut($out_trade_no)
  289. {
  290. $input = new \WxPayOrderQuery();
  291. $input->SetOut_trade_no($out_trade_no);
  292. $result = \WxPayApi::orderQuery($input);
  293. return $result;
  294. }
  295. /**
  296. * 把返回的支付参数方式改成数组以适应微信的api
  297. * 生成二维码图片会用到这个函数
  298. */
  299. protected function getStartBizContentAndSetPaymentMethod()
  300. {
  301. $currentOrderInfo = Yii::$service->order->getCurrentOrderInfo();
  302. if (isset($currentOrderInfo['products']) && is_array($currentOrderInfo['products'])) {
  303. $subject_arr = [];
  304. foreach ($currentOrderInfo['products'] as $product) {
  305. $subject_arr[] = $product['name'];
  306. }
  307. if (!empty($subject_arr)) {
  308. $subject = implode(',', $subject_arr);
  309. // 字符串太长会出问题,这里将产品的name链接起来,在截图一下
  310. if (strlen($subject) > $this->subjectMaxLength) {
  311. $subject = mb_substr($subject, 0, $this->subjectMaxLength);
  312. }
  313. //echo $subject;
  314. $increment_id = $currentOrderInfo['increment_id'];
  315. $base_grand_total = $currentOrderInfo['base_grand_total'];
  316. $total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY');
  317. Yii::$service->payment->setPaymentMethod($currentOrderInfo['payment_method']);
  318. $products = $currentOrderInfo['products'];
  319. $productIds = '';
  320. if (is_array($products)) {
  321. foreach ($products as $product) {
  322. $productIds = $product['product_id'];
  323. break;
  324. }
  325. }
  326. return [
  327. 'increment_id' => $increment_id,
  328. 'total_amount' => $total_amount,
  329. 'subject' => $subject,
  330. 'coupon_code' => $currentOrderInfo['coupon_code'],
  331. 'product_ids' => $productIds,
  332. ];
  333. }
  334. }
  335. }
  336. /**
  337. * 检查订单是否合法
  338. * 如果每项验证都通过则返回真
  339. */
  340. public function checkOrder($trade_state, $return_code, $trade_type, $out_trade_no, $total_amount, $seller_id, $auth_app_id)
  341. {
  342. if ($trade_state != 'SUCCESS') {
  343. Yii::$service->helper->errors->add('request trade_state is not equle to SUCCESS');
  344. return false;
  345. }
  346. if ($return_code != 'SUCCESS') {
  347. Yii::$service->helper->errors->add('request return_code is not equle to SUCCESS');
  348. return false;
  349. }
  350. if ($trade_type != 'NATIVE') {
  351. Yii::$service->helper->errors->add('request trade_type is not equle to NATIVE');
  352. return false;
  353. }
  354. if (!$this->_order) {
  355. $this->_order = Yii::$service->order->getByIncrementId($out_trade_no);
  356. Yii::$service->payment->setPaymentMethod($this->_order['payment_method']);
  357. }
  358. if (!$this->_order) {
  359. Yii::$service->helper->errors->add('order increment id:{out_trade_no} is not exist.', ['out_trade_no' => $out_trade_no]);
  360. return false;
  361. }
  362. $base_grand_total = $this->_order['base_grand_total'];
  363. $order_total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY');
  364. if ((string)($order_total_amount * 100) != $total_amount) { //由于微信中是以分为单位所以必须乘以100,二维码页面也已经作了处理,单位都是分,$order_total_amount * 100要转为字符串再比较
  365. Yii::$service->helper->errors->add('order increment id:{out_trade_no} , total_amount({total_amount}) is not equal to order_total_amount({order_total_amount})', ['out_trade_no'=>$out_trade_no , 'total_amount'=>$total_amount , 'order_total_amount'=>$order_total_amount ]);
  366. //return ['o' => $order_total_amount * 100, 't' => $total_amount]; //测试时便于观察订单金额和微信实际支付的金额,生产环境要注释掉
  367. return false;
  368. }
  369. return true;
  370. }
  371. /**
  372. * 微信 支付成功后,对订单的状态进行修改
  373. * 如果支付成功,则修改订单状态为支付成功状态。
  374. * @param $out_trade_no | string , fecshop的订单编号 increment_id
  375. * @param $trade_no | 微信支付交易号
  376. * @param isClearCart | boolean 是否清空购物车
  377. *
  378. */
  379. protected function updateOrderInfo($out_trade_no, $trade_no, $isClearCart=true)
  380. {
  381. if (!empty($out_trade_no) && !empty($trade_no)) {
  382. if ($this->paymentSuccess($out_trade_no, $trade_no)) {
  383. // 清空购物车
  384. if ($isClearCart) {
  385. Yii::$service->cart->clearCartProductAndCoupon();
  386. }
  387. return true;
  388. }
  389. } else {
  390. Yii::$service->helper->errors->add('wxpay payment fail,resultCode: {result_code}', ['result_code' => $resultCode]);
  391. return false;
  392. }
  393. }
  394. /**
  395. * @param $increment_id | String 订单号
  396. * @param $sendEmail | boolean 是否发送邮件
  397. * 订单支付成功后,需要更改订单支付状态等一系列的处理。
  398. */
  399. protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true)
  400. {
  401. if (!$this->_order) {
  402. $this->_order = Yii::$service->order->getByIncrementId($increment_id);
  403. Yii::$service->payment->setPaymentMethod($this->_order['payment_method']);
  404. }
  405. // 【优化后的代码 ##】
  406. $orderstatus = Yii::$service->order->payment_status_confirmed;
  407. $updateArr['order_status'] = $orderstatus;
  408. $updateArr['txn_id'] = $trade_no; // 微信的交易号
  409. $updateColumn = $this->_order->updateAll(
  410. $updateArr,
  411. [
  412. 'and',
  413. ['order_id' => $this->_order['order_id']],
  414. ['in','order_status',$this->_allowChangOrderStatus]
  415. ]
  416. );
  417. if (!empty($updateColumn)) {
  418. // 发送邮件,以及其他的一些操作(订单支付成功后的操作)
  419. Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']);
  420. }
  421. // 【优化后的代码 ##】
  422. /* 注释掉的原来代码,上面进行了优化,保证更改只有一次,这样发邮件也就只有一次了
  423. // 如果订单状态已经是processing,那么,不需要更改订单状态了。
  424. if ($this->_order['order_status'] == Yii::$service->order->payment_status_confirmed){
  425. return true;
  426. }
  427. $order = $this->_order;
  428. if (isset($order['increment_id']) && $order['increment_id']) {
  429. // 如果支付成功,则更改订单状态为支付成功
  430. $order->order_status = Yii::$service->order->payment_status_confirmed;
  431. $order->txn_id = $trade_no; // 微信的交易号
  432. // 更新订单信息
  433. $order->save();
  434. Yii::$service->order->orderPaymentCompleteEvent($order['increment_id']);
  435. // 得到当前的订单信息
  436. // $orderInfo = Yii::$service->order->getOrderInfoByIncrementId($order['increment_id']);
  437. // 发送新订单邮件
  438. // Yii::$service->email->order->sendCreateEmail($orderInfo);
  439. return true;
  440. }
  441. */
  442. return true;
  443. }
  444. // 支付宝的 标示
  445. public function getWxpayHandle()
  446. {
  447. return 'wxpay_standard';
  448. }
  449. }