Wxpay.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 Wxpay extends Service
  21. {
  22. public $devide;
  23. public $configFile;
  24. public $subjectMaxLength = 30;
  25. public $tradeType;
  26. public $scanCodeBody = '微信支付';
  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. $wxpayNativePayFile = Yii::getAlias('@fecshop/lib/wxpay/example/WxPay.NativePay.php');
  46. $wxpayLogFile = Yii::getAlias('@fecshop/lib/wxpay/example/log.php');
  47. require_once($wxpayApiFile);
  48. //require_once($wxpayDataFile);
  49. require_once($wxpayNotifyFile);
  50. //require_once($wxpayExceptionFile);
  51. require_once($wxpayNativePayFile);
  52. require_once($wxpayLogFile);
  53. //交易类型
  54. //JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里
  55. //MICROPAY--刷卡支付,刷卡支付有单独的支付接口,不调用统一下单接口
  56. if (!$this->tradeType) {
  57. if ($this->devide == 'wap') {
  58. $this->tradeType = 'MWEB';
  59. } elseif ($this->devide == 'pc') {
  60. $this->tradeType = "NATIVE";
  61. } else {
  62. throw new InvalidConfigException('you must config param [devide] in payment wxpay service');
  63. return ;
  64. }
  65. }
  66. $this->_allowChangOrderStatus = [
  67. Yii::$service->order->payment_status_pending,
  68. Yii::$service->order->payment_status_processing,
  69. ];
  70. }
  71. /**
  72. * 接收IPN消息的url,接收微信支付的异步消息,进而更改订单状态。
  73. */
  74. public function ipn()
  75. {
  76. $notifyFile = Yii::getAlias('@fecshop/services/payment/wxpay/notify.php');
  77. require_once($notifyFile);
  78. \Yii::info('begin ipn', 'fecshop_debug');
  79. $notify = new \PayNotifyCallBack();
  80. $notify->Handle(false);
  81. }
  82. /**
  83. * @param $data | Array 数据格式如下:
  84. * array(18) {
  85. * ["appid"]=> string(18) "wx426b3015555a46be"
  86. * ["attach"]=>string(24) "微信支付测试产品"
  87. * ["bank_type"]=>string(3) "CFT"
  88. * ["cash_fee"]=>string(1) "1"
  89. * ["device_info"]=>string(3) "WEB"
  90. * ["fee_type"]=> string(3) "CNY"
  91. * ["is_subscribe"]=>string(1) "N"
  92. * ["mch_id"]=>string(10) "1900009851"
  93. * ["nonce_str"]=> string(32) "e91xn1hwgyw9ox5zecdag1l86vrhi94l"
  94. * ["openid"]=>string(28) "oHZx6uKw5nrwZmEfgIX8poeQIucw"
  95. * ["out_trade_no"]=>string(10) "1100000953"
  96. * ["result_code"]=>string(7) "SUCCESS"
  97. * ["return_code"]=>string(7) "SUCCESS"
  98. * ["sign"]=>string(32) "589AC2046E667584FF1967C3C091259A"
  99. * ["time_end"]=>string(14) "20171106160124"
  100. * ["total_fee"]=>string(1) "1"
  101. * ["trade_type"]=>string(6) "NATIVE"
  102. * ["transaction_id"]=>string(28) "4200000006201711062859872774"
  103. * }
  104. * 在微信sdk验证数据安全性后,会执行该函数,用来验证订单的金额的正确性
  105. * 如果订单数据没有问题,则更改订单状态。
  106. */
  107. public function ipnUpdateOrder($data)
  108. {
  109. \Yii::info('ipn order process', 'fecshop_debug');
  110. $incrementId = $data['out_trade_no'];
  111. $transaction_id = $data['transaction_id'];
  112. $total_fee = $data['total_fee'];
  113. $fee_type = $data['fee_type'];
  114. if ($incrementId && $transaction_id && $total_fee) {
  115. $this->_order = Yii::$service->order->getByIncrementId($incrementId);
  116. Yii::$service->payment->setPaymentMethod($this->_order['payment_method']);
  117. $base_grand_total = $this->_order['base_grand_total'];
  118. $order_total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY');
  119. \Yii::info('check order totla amouont['.($order_total_amount * 100).' == '.$total_fee.']', 'fecshop_debug');
  120. // 微信支付的人民币单位为分
  121. if(bccomp($order_total_amount * 100, $total_fee) !== 0){
  122. return false;
  123. }
  124. \Yii::info('updateOrderInfo', 'fecshop_debug');
  125. // 更改订单状态
  126. if ($this->updateOrderInfo($incrementId, $transaction_id, false)) { //支付成功调用服务执行订单状态改变,清空购物车和发送邮件操作
  127. \Yii::info('updateOrderInfo Success', 'fecshop_debug');
  128. return true;
  129. }
  130. }
  131. }
  132. /**
  133. * PC端微信支付的信息获取
  134. * 在下单页面点击place order按钮,跳转到微信的时候,执行该函数。
  135. * @return Array 相应的订单和支付方面的信息,详细参看下面的注释
  136. */
  137. public function getScanCodeStart()
  138. {
  139. // 根据订单得到json格式的微信支付参数。
  140. $trade_info = $this->getStartBizContentAndSetPaymentMethod();
  141. if (!$trade_info) {
  142. Yii::$service->helper->errors->add('generate wxpay bizContent error');
  143. return false;
  144. }
  145. $notify_url = Yii::$service->payment->getStandardIpnUrl(); ////获取支付配置中的返回ipn url
  146. //$notify_url = Yii::$service->url->getUrl("payment/wxpay/standard/ipn"); ////获取支付配置中的返回ipn url
  147. $notify = new \NativePay();
  148. $input = new \WxPayUnifiedOrder();
  149. $input->SetBody($this->scanCodeBody);
  150. //$input->SetAttach("商店的额外的自定义数据");
  151. $input->SetAttach($trade_info['subject']);
  152. $input->SetDevice_info($this->deviceInfo); // 设置设备号
  153. if ($trade_info['coupon_code']) {
  154. $input->SetGoods_tag($trade_info['coupon_code']); //设置商品标记,代金券或立减优惠功能的参数
  155. }
  156. $input->SetOut_trade_no($trade_info['increment_id']); // Fecshop 订单号
  157. $orderTotal = $trade_info['total_amount'] * 100; //微信支付的单位为分,所以要乘以100
  158. $input->SetTotal_fee($orderTotal);
  159. $input->SetTime_start(date("YmdHis"));
  160. $input->SetTime_expire($this->getShangHaiExpireTime($this->expireTime));
  161. $input->SetNotify_url($notify_url); //通知地址 改成自己接口通知的接口,要有公网域名,测试时直接行动此接口会产生日志
  162. $input->SetTrade_type($this->tradeType);
  163. $input->SetProduct_id($trade_info['product_ids']); //此为二维码中包含的商品ID
  164. $result = $notify->GetPayUrl($input);
  165. //var_dump($result);exit;
  166. /**
  167. * var_dump($result);
  168. * array(11) {
  169. * ["appid"]=> string(18) "wx426b3015555a46be"
  170. * ["code_url"]=> string(35) "weixin://wxpay/bizpayurl?pr=Pnu1DAZ"
  171. * ["device_info"]=> string(3) "WEB"
  172. * ["mch_id"]=> string(10) "1900009851"
  173. * ["nonce_str"]=> string(16) "4L2t8gFjJ5qjXE0L"
  174. * ["prepay_id"]=> string(36) "wx201711070845443ca4736bb20972889642"
  175. * ["result_code"]=> string(7) "SUCCESS"
  176. * ["return_code"]=> string(7) "SUCCESS"
  177. * ["return_msg"]=> string(2) "OK"
  178. * ["sign"]=> string(32) "07BCF5B7B1D06DBF8E676EEBA6512082"
  179. * ["trade_type"]=> string(6) "NATIVE"
  180. * }
  181. **/
  182. //商户根据实际情况处理流程
  183. //var_dump($result);exit;
  184. if ($result['return_code'] == "FAIL") {
  185. Yii::$service->helper->errors->add('Api error: {return_msg}', ['return_msg' => $result['return_msg']]);
  186. return false;
  187. } elseif (!$result['code_url']) {
  188. Yii::$service->helper->errors->add('code_url is empty');
  189. return false;
  190. }
  191. $scanCodeImgUrl =Yii::$service->url->getUrl('payment/wxpay/standard/qrcode', ['data' => urlencode($result['code_url'])]);
  192. return [
  193. // 二维码图片的url
  194. 'scan_code_img_url' => $scanCodeImgUrl,
  195. // 订单号
  196. 'increment_id' => $trade_info['increment_id'],
  197. // 订单金额(RMB)
  198. 'total_amount' => $trade_info['total_amount'],
  199. // 订单标题
  200. 'subject' => $trade_info['subject'],
  201. // 订单优惠券
  202. 'coupon_code' => $trade_info['coupon_code'],
  203. // 字符串拼接的订单产品id(逗号隔开)
  204. 'product_ids' => $trade_info['product_ids'],
  205. ];
  206. }
  207. public function getShangHaiExpireTime($expire_time)
  208. {
  209. $timezone_out = date_default_timezone_get();
  210. date_default_timezone_set('Asia/Shanghai');
  211. $r_time = date("YmdHis", time() + $expire_time);
  212. date_default_timezone_set($timezone_out);
  213. return $r_time;
  214. }
  215. public function scanCodeCheckTradeIsSuccess($out_trade_no)
  216. {
  217. $result = Yii::$service->payment->wxpay->queryOrderByOut($out_trade_no);
  218. if (is_array($result) && !empty($result)) {
  219. $trade_state = $result['trade_state']; //最终的交易状态,必须为SUCCESS才是交易成功
  220. $return_code = $result['result_code'];
  221. $trade_type = $result['trade_type']; //获取交易方式,这里使用的是扫码支付native
  222. $out_trade_no = $result['out_trade_no'];
  223. $total_amount = $result['total_fee'];
  224. $seller_id = $result['mch_id'];
  225. $auth_app_id = $result['appid'];
  226. $trade_no = $result['transaction_id'];
  227. $checkOrderStatus = Yii::$service->payment->wxpay->checkOrder($trade_state, $return_code, $trade_type, $out_trade_no, $total_amount, $seller_id, $auth_app_id);
  228. if ($checkOrderStatus) {
  229. return $this->updateOrderInfo($out_trade_no, $trade_no);
  230. }
  231. }
  232. }
  233. /**
  234. * 通过微信接口查询交易信息
  235. * @param unknown $out_trade_no
  236. */
  237. public function queryOrderByOut($out_trade_no)
  238. {
  239. $input = new \WxPayOrderQuery();
  240. $input->SetOut_trade_no($out_trade_no);
  241. $result = \WxPayApi::orderQuery($input);
  242. return $result;
  243. }
  244. /**
  245. * 把返回的支付参数方式改成数组以适应微信的api
  246. * 生成二维码图片会用到这个函数
  247. */
  248. protected function getStartBizContentAndSetPaymentMethod()
  249. {
  250. $currentOrderInfo = Yii::$service->order->getCurrentOrderInfo();
  251. if (isset($currentOrderInfo['products']) && is_array($currentOrderInfo['products'])) {
  252. $subject_arr = [];
  253. foreach ($currentOrderInfo['products'] as $product) {
  254. $subject_arr[] = $product['name'];
  255. }
  256. if (!empty($subject_arr)) {
  257. $subject = implode(',', $subject_arr);
  258. // 字符串太长会出问题,这里将产品的name链接起来,在截图一下
  259. if (strlen($subject) > $this->subjectMaxLength) {
  260. $subject = mb_substr($subject, 0, $this->subjectMaxLength);
  261. }
  262. //echo $subject;
  263. $increment_id = $currentOrderInfo['increment_id'];
  264. $base_grand_total = $currentOrderInfo['base_grand_total'];
  265. $total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY');
  266. Yii::$service->payment->setPaymentMethod($currentOrderInfo['payment_method']);
  267. $products = $currentOrderInfo['products'];
  268. $productIds = '';
  269. if (is_array($products)) {
  270. foreach ($products as $product) {
  271. $productIds = $product['product_id'];
  272. break;
  273. }
  274. }
  275. return [
  276. 'increment_id' => $increment_id,
  277. 'total_amount' => $total_amount,
  278. 'subject' => $subject,
  279. 'coupon_code' => $currentOrderInfo['coupon_code'],
  280. 'product_ids' => $productIds,
  281. ];
  282. }
  283. }
  284. }
  285. /**
  286. * 检查订单是否合法
  287. * 如果每项验证都通过则返回真
  288. */
  289. public function checkOrder($trade_state, $return_code, $trade_type, $out_trade_no, $total_amount, $seller_id, $auth_app_id)
  290. {
  291. if ($trade_state != 'SUCCESS') {
  292. Yii::$service->helper->errors->add('request trade_state is not equle to SUCCESS');
  293. return false;
  294. }
  295. if ($return_code != 'SUCCESS') {
  296. Yii::$service->helper->errors->add('request return_code is not equle to SUCCESS');
  297. return false;
  298. }
  299. //if ($trade_type != 'NATIVE') {
  300. // Yii::$service->helper->errors->add('request trade_type is not equle to NATIVE');
  301. // return false;
  302. //}
  303. if (!$this->_order) {
  304. $this->_order = Yii::$service->order->getByIncrementId($out_trade_no);
  305. Yii::$service->payment->setPaymentMethod($this->_order['payment_method']);
  306. }
  307. if (!$this->_order) {
  308. Yii::$service->helper->errors->add('order increment id:{out_trade_no} is not exist.', ['out_trade_no' => $out_trade_no]);
  309. return false;
  310. }
  311. $base_grand_total = $this->_order['base_grand_total'];
  312. $order_total_amount = Yii::$service->page->currency->getCurrencyPrice($base_grand_total, 'CNY');
  313. if ((string)($order_total_amount * 100) != $total_amount) { //由于微信中是以分为单位所以必须乘以100,二维码页面也已经作了处理,单位都是分,$order_total_amount * 100要转为字符串再比较
  314. 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 ]);
  315. //return ['o' => $order_total_amount * 100, 't' => $total_amount]; //测试时便于观察订单金额和微信实际支付的金额,生产环境要注释掉
  316. return false;
  317. }
  318. return true;
  319. }
  320. /**
  321. * 微信 支付成功后,对订单的状态进行修改
  322. * 如果支付成功,则修改订单状态为支付成功状态。
  323. * @param $out_trade_no | string , fecshop的订单编号 increment_id
  324. * @param $trade_no | 微信支付交易号
  325. * @param isClearCart | boolean 是否清空购物车
  326. *
  327. */
  328. protected function updateOrderInfo($out_trade_no, $trade_no, $isClearCart=true)
  329. {
  330. if (!empty($out_trade_no) && !empty($trade_no)) {
  331. if ($this->paymentSuccess($out_trade_no, $trade_no)) {
  332. // 清空购物车
  333. if ($isClearCart) {
  334. Yii::$service->cart->clearCartProductAndCoupon();
  335. }
  336. return true;
  337. }
  338. } else {
  339. Yii::$service->helper->errors->add('wxpay payment fail,resultCode: {result_code}', ['result_code' => $resultCode]);
  340. return false;
  341. }
  342. }
  343. /**
  344. * @param $increment_id | String 订单号
  345. * @param $sendEmail | boolean 是否发送邮件
  346. * 订单支付成功后,需要更改订单支付状态等一系列的处理。
  347. */
  348. protected function paymentSuccess($increment_id, $trade_no, $sendEmail = true)
  349. {
  350. if (!$this->_order) {
  351. $this->_order = Yii::$service->order->getByIncrementId($increment_id);
  352. Yii::$service->payment->setPaymentMethod($this->_order['payment_method']);
  353. }
  354. // 【优化后的代码 ##】
  355. $orderstatus = Yii::$service->order->payment_status_confirmed;
  356. $updateArr['order_status'] = $orderstatus;
  357. $updateArr['txn_id'] = $trade_no; // 微信的交易号
  358. $updateColumn = $this->_order->updateAll(
  359. $updateArr,
  360. [
  361. 'and',
  362. ['order_id' => $this->_order['order_id']],
  363. ['in','order_status',$this->_allowChangOrderStatus]
  364. ]
  365. );
  366. if (!empty($updateColumn)) {
  367. // 发送邮件,以及其他的一些操作(订单支付成功后的操作)
  368. Yii::$service->order->orderPaymentCompleteEvent($this->_order['increment_id']);
  369. }
  370. // 【优化后的代码 ##】
  371. /* 注释掉的原来代码,上面进行了优化,保证更改只有一次,这样发邮件也就只有一次了
  372. // 如果订单状态已经是processing,那么,不需要更改订单状态了。
  373. if ($this->_order['order_status'] == Yii::$service->order->payment_status_confirmed){
  374. return true;
  375. }
  376. $order = $this->_order;
  377. if (isset($order['increment_id']) && $order['increment_id']) {
  378. // 如果支付成功,则更改订单状态为支付成功
  379. $order->order_status = Yii::$service->order->payment_status_confirmed;
  380. $order->txn_id = $trade_no; // 微信的交易号
  381. // 更新订单信息
  382. $order->save();
  383. Yii::$service->order->orderPaymentCompleteEvent($order['increment_id']);
  384. // 得到当前的订单信息
  385. // $orderInfo = Yii::$service->order->getOrderInfoByIncrementId($order['increment_id']);
  386. // 发送新订单邮件
  387. // Yii::$service->email->order->sendCreateEmail($orderInfo);
  388. return true;
  389. }
  390. */
  391. return true;
  392. }
  393. // 支付宝的 标示
  394. public function getWxpayHandle()
  395. {
  396. return 'wxpay_standard';
  397. }
  398. }