OrderController.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  1. <?php
  2. namespace hd\controllers;
  3. use bizHd\hb\classes\HbClass;
  4. use Yii;
  5. use biz\shop\classes\ShopExtClass;
  6. use biz\sj\services\MerchantExtendService;
  7. use biz\sj\services\MerchantService;
  8. use bizHd\custom\classes\CustomClass;
  9. use bizHd\custom\classes\HdClass;
  10. use bizHd\goods\classes\GoodsClass;
  11. use bizHd\merchant\services\ShopService;
  12. use bizHd\order\classes\OrderClass;
  13. use bizHd\order\classes\OrderForwardClass;
  14. use bizHd\order\classes\OrderItemClass;
  15. use bizHd\order\classes\OrderSendClass;
  16. use hd\models\order\CreateOrderForm;
  17. use bizHd\express\classes\HdDeliveryOrderClass;
  18. use bizHd\order\services\OrderService;
  19. use bizHd\product\classes\ProductClass;
  20. use bizHd\saas\services\RegionService;
  21. use bizHd\shop\classes\ShopClass;
  22. use bizHd\user\services\UserService;
  23. use bizHd\work\classes\WorkClass;
  24. use common\components\dict;
  25. use common\components\dateUtil;
  26. use common\components\noticeUtil;
  27. use common\components\orderSn;
  28. use common\components\payUtil;
  29. use common\services\xhPayToolService;
  30. use common\components\util;
  31. use common\components\stringUtil;
  32. use bizHd\promote\services\CouponService;
  33. use common\components\httpUtil;
  34. use biz\wx\classes\WxMessageClass;
  35. use common\components\lakala\Lakala;
  36. use yii\helpers\ArrayHelper;
  37. class OrderController extends BaseController
  38. {
  39. public $guestAccess = ['order-relate', 'fast-pay', 'create-order', 'list', 'info'];
  40. public function actionDebt()
  41. {
  42. $get = Yii::$app->request->get();
  43. $id = $get['id'] ?? 0;
  44. $info = OrderClass::getById($id, true);
  45. if (empty($info)) {
  46. util::fail('没有找到订单');
  47. }
  48. if ($info->mainId != $this->mainId) {
  49. util::fail('不是你的订单');
  50. }
  51. //4秒内不允许重复提交
  52. util::checkRepeatCommit($id, 4);
  53. if ($info->status != 1) {
  54. util::fail('订单已付款或取消');
  55. }
  56. $payWay = dict::getDict('payWay', 'debtPay');
  57. $connection = Yii::$app->db;
  58. $transaction = $connection->beginTransaction();
  59. try {
  60. $actPrice = $info->actPrice ?? 0;
  61. $info->debtPrice = $actPrice;
  62. $info->remainDebtPrice = $actPrice;
  63. $info->debt = 1;
  64. $info->save();
  65. OrderClass::payAfter($info, $payWay);
  66. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  67. if ($info->getGoods == 1 && $info->sendType == 1 && $info->status == 2) {
  68. $info->status = 4;
  69. $info->save();
  70. }
  71. $transaction->commit();
  72. //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
  73. HdDeliveryOrderClass::payAfter($info);
  74. util::complete('赊账成功');
  75. } catch (\Exception $exception) {
  76. $transaction->rollBack();
  77. Yii::info("赊账失败原因:" . $exception->getMessage());
  78. util::fail('操作失败');
  79. }
  80. }
  81. //取消订单 ssh 20221231
  82. public function actionCancel()
  83. {
  84. //避免重复提交
  85. $adminId = $this->adminId;
  86. util::checkRepeatCommit($adminId, 8);
  87. $get = Yii::$app->request->get();
  88. $id = $get['id'] ?? 0;
  89. $order = OrderClass::getById($id, true);
  90. if ($order->mainId != $this->mainId) {
  91. util::fail('不是你的订单');
  92. }
  93. $staff = $this->shopAdmin;
  94. $connection = Yii::$app->db;
  95. $transaction = $connection->beginTransaction();
  96. try {
  97. OrderClass::setExpire($order, true, $staff);
  98. $transaction->commit();
  99. util::complete();
  100. } catch (\Exception $exception) {
  101. $transaction->rollBack();
  102. Yii::info("取消原因:" . $exception->getMessage());
  103. util::fail('取消失败');
  104. }
  105. }
  106. //修改订单 ssh 20220926
  107. public function actionUpdate()
  108. {
  109. $post = Yii::$app->request->post();
  110. $id = $post['id'] ?? 0;
  111. $order = OrderClass::getById($id, true);
  112. OrderClass::valid($order, $this->mainId);
  113. unset($post['id']);
  114. if ($order->status == 3) {
  115. util::fail('订单已配送');
  116. }
  117. if ($order->status == 4) {
  118. util::fail('订单已完成');
  119. }
  120. if ($order->status == 5) {
  121. util::fail('订单已取消');
  122. }
  123. if ($order->fromType == 4) {
  124. util::fail('请在美团APP上修改');
  125. }
  126. $address = $post['address'] ?? '';
  127. $floor = $post['floor'] ?? '';
  128. $post['fullAddress'] = $address . $floor;
  129. OrderClass::updateById($id, $post);
  130. $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
  131. $remark = $post['remark'] ?? '';
  132. $reachDate = $post['reachDate'] ?? '';
  133. $reachPeriod = $post['reachPeriod'] ?? '';
  134. $cardInfo = $post['cardInfo'] ?? '';
  135. $anonymity = $post['anonymity'] ?? 0;
  136. $bookName = $post['bookName'] ?? '';
  137. if (!empty($workList)) {
  138. foreach ($workList as $work) {
  139. $work->remark = $remark;
  140. $work->reachDate = $reachDate;
  141. $work->reachPeriod = $reachPeriod;
  142. $work->cardInfo = $cardInfo;
  143. $work->anonymity = $anonymity;
  144. $work->bookName = $bookName;
  145. $work->save();
  146. }
  147. }
  148. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  149. ShopExtClass::orderUpdateRemind($shopExt, $order);
  150. util::complete();
  151. }
  152. //客户欠款的订单 ssh 2021.2.4
  153. public function actionDebtList()
  154. {
  155. $get = Yii::$app->request->get();
  156. $id = $get['id'] ?? 0;
  157. $info = CustomClass::getById($id, true);
  158. CustomClass::valid($info, $this->shopId);
  159. $where = ['customId' => $id, 'debt' => 1];
  160. $searchTime = $get['searchTime'] ?? '';
  161. if (!empty($searchTime)) {
  162. $startTime = $get['startTime'] ?? '';
  163. $endTime = $get['endTime'] ?? '';
  164. $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
  165. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  166. }
  167. $allowedPageSizes = [100, 200, 300];
  168. $pageSize = isset($get['pageSize']) && in_array((int)$get['pageSize'], $allowedPageSizes, true)
  169. ? (int)$get['pageSize'] : 100;
  170. $page = max(1, (int)($get['page'] ?? 1));
  171. $fields = ['id', 'orderSn', 'actPrice', 'addTime', 'remainDebtPrice', 'debtPrice'];
  172. Yii::$app->request->setQueryParams(array_merge($get, ['page' => $page, 'pageSize' => $pageSize]));
  173. $result = OrderClass::getList($fields, $where, 'addTime DESC');
  174. if (!empty($result['list'])) {
  175. foreach ($result['list'] as $key => $value) {
  176. $debtPrice = $value['debtPrice'] ?? 0;
  177. $remainDebtPrice = $value['remainDebtPrice'] ?? 0;
  178. $hasPayDebt = 0;
  179. if ($debtPrice > $remainDebtPrice) {
  180. $hasPayDebt = bcsub($debtPrice, $remainDebtPrice, 2);
  181. }
  182. $result['list'][$key]['hasPayDebt'] = floatval($hasPayDebt);
  183. }
  184. }
  185. $result['customInfo'] = $info;
  186. util::success($result);
  187. }
  188. //确认送达 ssh 20250902
  189. public function actionReach()
  190. {
  191. //解决重复提交
  192. util::checkRepeatCommit($this->adminId, 5);
  193. $get = Yii::$app->request->get();
  194. $id = $get['id'] ?? 0;
  195. $order = OrderClass::getById($id, true);
  196. if (empty($order)) {
  197. util::fail('没有找到订单');
  198. }
  199. OrderClass::valid($order, $this->mainId);
  200. if ($order->status == 5) {
  201. util::fail('订单已取消');
  202. }
  203. if ($order->status == 1) {
  204. util::fail('订单待付款');
  205. }
  206. if ($order->status == 2) {
  207. util::fail('订单未发货');
  208. }
  209. if ($order->status == 4) {
  210. util::fail('订单已经送到了');
  211. }
  212. if (!in_array($order->sendStatus, [-1, -4])) {
  213. util::fail('由跑腿送货,无需确认');
  214. }
  215. $order->status = 4;
  216. $order->save();
  217. util::complete('操作成功');
  218. }
  219. //确认取货
  220. public function actionFetch()
  221. {
  222. $get = Yii::$app->request->get();
  223. $id = $get['id'] ?? 0;
  224. //解决重复提交
  225. util::checkRepeatCommit($id . '_' . $this->adminId, 5);
  226. $order = OrderClass::getById($id, true);
  227. if (empty($order)) {
  228. util::fail('没有找到订单');
  229. }
  230. OrderClass::valid($order, $this->mainId);
  231. if ($order->status == 5) {
  232. util::fail('订单已取消');
  233. }
  234. if ($order->status == 1) {
  235. util::fail('订单待付款');
  236. }
  237. if ($order->status == 4) {
  238. util::fail('订单已取过了');
  239. }
  240. if (in_array($order->sendStatus, [-1, 0, 1, 2, 4, 5])) {
  241. util::fail('由跑腿送货,无需确认');
  242. }
  243. $order->status = 4;
  244. $order->save();
  245. util::complete('操作成功');
  246. }
  247. //批量确认取货 待发货的自取订单 每次500个
  248. public function actionBatchFetch()
  249. {
  250. $where = ["status" => 2, "sendType" => 1, "shopId" => $this->shopId];
  251. $orderList = OrderService::getLimitList("id",$where,500,"id desc");
  252. $ids = ArrayHelper::getColumn($orderList,"id");
  253. OrderService::updateByIds($ids, ["status" => 4]);
  254. util::complete($ids);
  255. }
  256. //确认发货
  257. public function actionSend()
  258. {
  259. //解决重复提交
  260. util::checkRepeatCommit($this->adminId, 5);
  261. $get = Yii::$app->request->get();
  262. $id = $get['id'] ?? 0;
  263. $order = OrderClass::getById($id, true);
  264. if (empty($order)) {
  265. util::fail('没有找到订单');
  266. }
  267. OrderClass::valid($order, $this->mainId);
  268. if ($order->status != 2) {
  269. util::fail('订单不是待发货状态');
  270. }
  271. // $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
  272. // if (!empty($workList)) {
  273. // $unComplete = false;
  274. // foreach ($workList as $work) {
  275. // if ($work->status != 1) {
  276. // $unComplete = true;
  277. // }
  278. // }
  279. // if ($unComplete == true) {
  280. // util::fail('还有制作单没有完成');
  281. // }
  282. // }
  283. $order->status = 3;
  284. $order->save();
  285. util::complete('已发货');
  286. }
  287. //打印订单 ssh 20220601
  288. public function actionPrintOrder()
  289. {
  290. $get = Yii::$app->request->get();
  291. $id = isset($get['id']) ? $get['id'] : 0;
  292. $order = OrderClass::getById($id, true);
  293. if (empty($order)) {
  294. util::fail('没有找到订单');
  295. }
  296. if ($order->forward == 1) {
  297. util::fail('红冲订单不能打印');
  298. }
  299. OrderClass::valid($order, $this->mainId);
  300. OrderClass::onlinePrint($order, true);
  301. util::complete();
  302. }
  303. //微信和支付宝付款码支付复查 ssh 20220422
  304. public function actionCodePayCheck()
  305. {
  306. ini_set('date.timezone', 'Asia/Shanghai');
  307. header("Content-type: text/html; charset=utf-8");
  308. $get = Yii::$app->request->get();
  309. $id = isset($get['id']) ? $get['id'] : 0;
  310. util::checkRepeatCommit($id, 3);
  311. $order = OrderClass::getById($id, true);
  312. OrderClass::valid($order, $this->mainId);
  313. $orderSn = $order->orderSn ?? '';
  314. $totalFee = $order->mainPay ?? 0;
  315. if ($order->status == OrderClass::ORDER_STATUS_COMPLETE) {
  316. util::success(['returnStatus' => 'SUCCESS']);
  317. }
  318. if ($order->status == OrderClass::ORDER_STATUS_CANCEL) {
  319. util::complete('订单已取消');
  320. }
  321. if ($order->status != OrderClass::ORDER_STATUS_UN_PAY) {
  322. util::complete('订单不是待付款状态');
  323. }
  324. $connection = Yii::$app->db;
  325. $transaction = $connection->beginTransaction();
  326. try {
  327. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  328. $shop = $this->shop;
  329. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  330. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  331. $params = [
  332. 'appid' => 'OP00002119',
  333. 'serial_no' => '018b08cfddbd',
  334. 'merchant_no' => $shop->lklSjNo,
  335. 'term_no' => $shop->lklScanTermNo,
  336. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  337. 'lklCertificatePath' => $lklCertificatePath,
  338. ];
  339. $laResource = new Lakala($params);
  340. $scanParams = ['orderSn' => $orderSn,];
  341. $response = $laResource->query($scanParams);
  342. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  343. if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
  344. $payWayType = dict::getDict('payWay', 'wxPay');
  345. $account_type = $response['resp_data']['account_type'] ?? '';
  346. if ($account_type == 'WECHAT') {
  347. $payWayType = dict::getDict('payWay', 'wxPay');
  348. }
  349. if ($account_type == 'ALIPAY') {
  350. $payWayType = dict::getDict('payWay', 'alipay');
  351. }
  352. $transactionId = $response['resp_data']['trade_no'] ?? '';
  353. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  354. $order->save();
  355. $attach = '';
  356. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  357. $transaction->commit();
  358. //解决重复通知
  359. $cacheKey = 'hd_shop_order_pay_check_' . $orderSn;
  360. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  361. if (empty($has)) {
  362. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  363. //打印小票和语音播报
  364. $newOrder = OrderClass::getById($id, true);
  365. OrderClass::onlinePrint($newOrder);
  366. ShopExtClass::hdGatheringReport($newOrder);
  367. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  368. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  369. $newOrder->status = 4;
  370. $newOrder->save();
  371. }
  372. HdDeliveryOrderClass::payAfter($newOrder);
  373. $shopId = $newOrder->shopId ?? 0;
  374. $shop = ShopClass::getById($shopId, true);
  375. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  376. }
  377. util::success(['returnStatus' => 'SUCCESS']);
  378. } else {
  379. util::complete('未知状态..');
  380. }
  381. }
  382. util::complete('未知状态..');
  383. } catch (\Exception $e) {
  384. $transaction->rollBack();
  385. util::complete('支付失败');
  386. }
  387. }
  388. //微信和支付宝付款码支付验证(带付款码) ssh 20260716
  389. public function actionCodePayVerify()
  390. {
  391. ini_set('date.timezone', 'Asia/Shanghai');
  392. header("Content-type: text/html; charset=utf-8");
  393. $get = Yii::$app->request->get();
  394. $id = isset($get['id']) ? $get['id'] : 0;
  395. $authCode = isset($get['authCode']) ? $get['authCode'] : '';
  396. util::checkRepeatCommit($id, 3);
  397. $order = OrderClass::getById($id, true);
  398. OrderClass::valid($order, $this->mainId);
  399. $orderSn = $order->orderSn ?? '';
  400. $totalFee = $order->mainPay ?? 0;
  401. if ($order->status == OrderClass::ORDER_STATUS_COMPLETE) {
  402. util::success(['returnStatus' => 'SUCCESS']);
  403. }
  404. if ($order->status == OrderClass::ORDER_STATUS_CANCEL) {
  405. util::complete('订单已取消');
  406. }
  407. if ($order->status != OrderClass::ORDER_STATUS_UN_PAY) {
  408. util::complete('订单不是待付款状态');
  409. }
  410. $connection = Yii::$app->db;
  411. $transaction = $connection->beginTransaction();
  412. try {
  413. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  414. $shop = $this->shop;
  415. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  416. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  417. $params = [
  418. 'appid' => 'OP00002119',
  419. 'serial_no' => '018b08cfddbd',
  420. 'merchant_no' => $shop->lklSjNo,
  421. 'term_no' => $shop->lklScanTermNo,
  422. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  423. 'lklCertificatePath' => $lklCertificatePath,
  424. ];
  425. $laResource = new Lakala($params);
  426. $scanParams = ['orderSn' => $orderSn, 'authCode' => $authCode];
  427. $response = $laResource->query($scanParams);
  428. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  429. if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
  430. $payWayType = dict::getDict('payWay', 'wxPay');
  431. $account_type = $response['resp_data']['account_type'] ?? '';
  432. if ($account_type == 'WECHAT') {
  433. $payWayType = dict::getDict('payWay', 'wxPay');
  434. }
  435. if ($account_type == 'ALIPAY') {
  436. $payWayType = dict::getDict('payWay', 'alipay');
  437. }
  438. $transactionId = $response['resp_data']['trade_no'] ?? '';
  439. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  440. $order->save();
  441. $attach = '';
  442. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  443. $transaction->commit();
  444. //解决重复通知
  445. $cacheKey = 'hd_shop_order_pay_check_' . $orderSn;
  446. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  447. if (empty($has)) {
  448. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  449. //打印小票和语音播报
  450. $newOrder = OrderClass::getById($id, true);
  451. OrderClass::onlinePrint($newOrder);
  452. ShopExtClass::hdGatheringReport($newOrder);
  453. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  454. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  455. $newOrder->status = 4;
  456. $newOrder->save();
  457. }
  458. HdDeliveryOrderClass::payAfter($newOrder);
  459. $shopId = $newOrder->shopId ?? 0;
  460. $shop = ShopClass::getById($shopId, true);
  461. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  462. }
  463. util::success(['returnStatus' => 'SUCCESS']);
  464. } else {
  465. util::complete('未知状态..');
  466. }
  467. }
  468. util::complete('未知状态..');
  469. } catch (\Exception $e) {
  470. $transaction->rollBack();
  471. util::complete('支付失败');
  472. }
  473. }
  474. /**
  475. * 微信和支付宝付款码支付
  476. * 职责:处理商户扫描客户付款码(被扫支付)的请求,调用拉卡拉支付接口并更新本地订单状态(零售端)
  477. * 入参:GET 传参 id (订单ID), authCode (付款码), version (版本号)
  478. * 返回:JSON 格式的支付结果(SUCCESS/FAILURE)
  479. * 副作用:更新订单支付状态、支付方式,记录支付日志,触发云打印、跑腿呼叫及语音播报
  480. * 关键边界:
  481. * 1. 验证订单有效性与待付款状态
  482. * 2. 校验付款码格式(微信/支付宝)
  483. * 3. 优化:将拉卡拉外部网络请求移出数据库事务,避免因网络延迟长时间占用数据库连接和行锁
  484. */
  485. public function actionCodePay()
  486. {
  487. ini_set('date.timezone', 'Asia/Shanghai');
  488. header("Content-type: text/html; charset=utf-8");
  489. $get = Yii::$app->request->get();
  490. $id = isset($get['id']) ? $get['id'] : 0;
  491. util::checkRepeatCommit($id, 3);
  492. $version = $get['version'] ?? 0;
  493. $order = OrderClass::getById($id, true);
  494. OrderClass::valid($order, $this->mainId);
  495. if ($order->status == OrderClass::ORDER_STATUS_CANCEL) {
  496. $msg = '订单已取消';
  497. util::success(['returnStatus' => 'FAILURE'], $msg);
  498. }
  499. if ($order->status != OrderClass::ORDER_STATUS_UN_PAY) {
  500. $msg = '订单不是待付款状态';
  501. util::success(['returnStatus' => 'FAILURE'], $msg);
  502. }
  503. $shop = $this->shop;
  504. $sj = $shop->merchantName;
  505. $shopName = $shop->shopName;
  506. $name = $shopName == '首店' ? $sj : $sj . '-' . $shopName;
  507. $authCode = (string)$get['authCode'] ?? '';
  508. if ($version > 0) {
  509. if (empty($authCode)) {
  510. $msg = '没有扫到付款码';
  511. $remind = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  512. noticeUtil::push($remind . ' 编号005', '15280215347');
  513. util::success(['returnStatus' => 'FAILURE'], $msg);
  514. }
  515. //微信文档说明 https://pay.weixin.qq.com/doc/v2/merchant/4011936234
  516. $wxPattern = '/^(10|11|12|13|14|15)\d{16}$/';
  517. //支付宝文档说明 https://opendocs.alipay.com/open/194/106039/
  518. $aliPattern = '/^(25|26|27|28|29|30)\d{14,22}$/';
  519. if (!preg_match($wxPattern, $authCode) && !preg_match($aliPattern, $authCode)) {
  520. $msg = '付款码错误,请使用微信或支付宝付款码';
  521. $remind = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  522. //noticeUtil::push($remind . ' 编号009', '15280215347');
  523. util::success(['returnStatus' => 'FAILURE'], $msg);
  524. }
  525. } else {
  526. if (empty($authCode)) {
  527. util::fail('没有获取到支付码');
  528. }
  529. }
  530. $orderSn = $order->orderSn ?? '';
  531. $lsCodePayErrorKey = 'ls_code_pay_error_' . $id;
  532. $hasFailPay = Yii::$app->redis->executeCommand('GET', [$lsCodePayErrorKey]);
  533. //前面有付失败过,要重新生成单号
  534. if (!empty($hasFailPay)) {
  535. $oldOrderSn = $order->orderSn;
  536. $orderSn = orderSn::getOrderSn();
  537. $order->orderSn = $orderSn;
  538. $order->save();
  539. OrderItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $orderSn]);
  540. }
  541. $subject = '购买花材 ' . $orderSn;
  542. $totalFee = $order->mainPay ?? 0;
  543. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  544. try {
  545. $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
  546. $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
  547. $params = [
  548. 'appid' => 'OP00002119',
  549. 'serial_no' => '018b08cfddbd',
  550. 'merchant_no' => $shop->lklSjNo,
  551. 'term_no' => $shop->lklScanTermNo,
  552. 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
  553. 'lklCertificatePath' => $lklCertificatePath,
  554. ];
  555. $laResource = new Lakala($params);
  556. $notifyUrl = Yii::$app->params['hdHost'] . "/notice/pay-callback";
  557. $scanParams = [
  558. 'orderSn' => $orderSn,
  559. 'amount' => $totalFee,
  560. 'capitalType' => $capitalType,
  561. 'notifyUrl' => $notifyUrl,
  562. 'subject' => $subject,
  563. 'authCode' => $authCode,
  564. ];
  565. // 复杂分支/关键逻辑:在调用外部支付接口前不开启事务,防止网络延迟卡死数据库连接
  566. $response = $laResource->scanPay($scanParams);
  567. if (isset($response['code']) && $response['code'] == 'BBS00000') {
  568. // 复杂分支/关键逻辑:支付成功后,开启数据库事务,确保本地订单状态更新的原子性
  569. $connection = Yii::$app->db;
  570. $transaction = $connection->beginTransaction();
  571. try {
  572. $account_type = $response['resp_data']['account_type'] ?? '';
  573. $payWayType = dict::getDict('payWay', 'wxPay');
  574. if ($account_type == 'WECHAT') {
  575. $payWayType = dict::getDict('payWay', 'wxPay');
  576. }
  577. if ($account_type == 'ALIPAY') {
  578. $payWayType = dict::getDict('payWay', 'alipay');
  579. }
  580. $order->payWay = $payWayType;
  581. $transactionId = $response['resp_data']['trade_no'] ?? '';
  582. $order->onlinePay = dict::getDict('onlinePay', 'yes');
  583. $order->save();
  584. $attach = '';
  585. payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
  586. $transaction->commit();
  587. } catch (\Exception $e) {
  588. $transaction->rollBack();
  589. throw $e;
  590. }
  591. //解决重复通知
  592. $cacheKey = 'hd_shop_order_pay_' . $orderSn;
  593. $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
  594. if (empty($has)) {
  595. Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
  596. $newOrder = OrderClass::getById($id, true);
  597. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  598. if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
  599. $newOrder->status = 4;
  600. $newOrder->save();
  601. }
  602. //打印小票
  603. OrderClass::onlinePrint($newOrder);
  604. HdDeliveryOrderClass::payAfter($newOrder);
  605. //语音播报
  606. ShopExtClass::hdGatheringReport($newOrder);
  607. $shopId = $newOrder->shopId ?? 0;
  608. $shop = ShopClass::getById($shopId, true);
  609. WxMessageClass::gatheringIncomeInform($shop, $newOrder);
  610. }
  611. util::success(['returnStatus' => 'SUCCESS']);
  612. } else {
  613. //标记有没付成功的次数,原因有可能是余额不足等
  614. Yii::$app->redis->executeCommand('SETEX', [$lsCodePayErrorKey, 1200, 'hasFail']);
  615. $msg = $response['msg'] ?? '';
  616. $retCode = $response['code'] ?? '';
  617. $fullMsg = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
  618. if ($retCode == 'BBS10000' || $retCode == 'BBS11105') {
  619. $shopId = $order->shopId;
  620. ShopExtClass::remindInputPassword($shopId);
  621. }
  622. //noticeUtil::push($fullMsg . ' ' . $retCode . ' 编号008', '15280215347');
  623. util::success(['returnStatus' => 'FAILURE', 'returnCode' => $retCode], $msg);
  624. }
  625. } catch (\Exception $e) {
  626. Yii::error("零售端支付失败原因:" . $e->getMessage());
  627. util::fail('支付失败');
  628. }
  629. }
  630. //开单操作 ssh 20220316
  631. public function actionCreateOrder()
  632. {
  633. $post = Yii::$app->request->post();
  634. $post['sjId'] = $this->sjId;
  635. $post['shopId'] = $this->shopId;
  636. $post['mainId'] = $this->mainId ?? 0;
  637. $shop = $this->shop;
  638. if ($shop->memberLevelSet == 0) {
  639. //util::fail('请先设置会员等级');
  640. }
  641. $now = time();
  642. $orderValidTime = 600;
  643. $expireTime = $now + $orderValidTime;
  644. $post['deadline'] = $expireTime;
  645. $post['staffId'] = $this->shopAdminId ?? 0;
  646. $post['staffName'] = $this->shopAdmin->name ?? '';
  647. $post['flowerNum'] = isset($post['flowerNum']) && $post['flowerNum'] > 0 ? $post['flowerNum'] : 0;
  648. $version = $post['version'] ?? 0; //验证已移至 CreateOrderForm
  649. if ($version < 3) {
  650. util::fail('请升级版本,或用小程序');
  651. }
  652. //默认情况开单员工和收款员工是同个人
  653. $staffId = $this->shopAdminId ?? 0;
  654. $staffName = $this->shopAdmin->name ?? '';
  655. if (empty($post['shopAdminId'])) {
  656. $post['shopAdminId'] = $staffId;
  657. $post['shopAdminName'] = $staffName;
  658. }
  659. if (empty($post['getStaffId'])) {
  660. $post['getStaffId'] = $staffId;
  661. $post['getStaffName'] = $this->shopAdmin->name ?? '';
  662. }
  663. $groupId = !empty($post['groupId']) ? $post['groupId'] : 0;
  664. $post['fromType'] = $post['fromType'] ?? 1;
  665. if ($post['fromType'] == dict::getDict('fromType', 'friend')) {
  666. if (empty($post['bookName'])) {
  667. util::fail('请填写订花人姓名');
  668. }
  669. }
  670. $customId = $post['customId'] ?? 0;
  671. $custom = CustomClass::getById($customId, true);
  672. if (empty($custom)) {
  673. util::fail('没有找到客户哦');
  674. }
  675. $hdId = $custom->hdId ?? 0;
  676. $hd = HdClass::getById($hdId, true);
  677. if (empty($hd)) {
  678. util::fail('客户对应的花店信息缺失,编号869');
  679. }
  680. $hdName = $hd->name ?? '';
  681. $post['hdId'] = $hdId;
  682. $post['hdName'] = $hdName;
  683. $customName = $custom->name ?? '';
  684. $post['customName'] = $customName;
  685. $post['customNamePy'] = stringUtil::py($customName);
  686. if (!empty($post['receiveMobile'])) {
  687. if (!stringUtil::isMobile($post['receiveMobile'])) {
  688. util::fail('请填写正确的收花人手机号');
  689. }
  690. }
  691. if (!empty($post['bookMobile'])) {
  692. if (!stringUtil::isMobile($post['bookMobile'])) {
  693. util::fail('请填写正确的订花人手机号');
  694. }
  695. }
  696. $hasPay = $post['hasPay'] ?? dict::getDict('hasPay', 'unPay');
  697. $post['sendType'] = $post['sendType'] ?? 1;
  698. $forward = $post['forward'] ?? 0;
  699. if ($forward == 1) {
  700. if ($hasPay != 1) {
  701. util::fail('红冲订单只能走线下转账');
  702. }
  703. $historyDate = $post['historyDate'] ?? '';
  704. if (!empty($historyDate)) {
  705. if ($historyDate != date("Y-m-d")) {
  706. util::fail('红冲订单不能修改账单日期,只能今天');
  707. }
  708. }
  709. }
  710. $productJson = $post['product'] ?? '';
  711. $productList = [];
  712. if (!empty($productJson)) {
  713. $productList = json_decode($productJson, true);
  714. }
  715. if (empty($productList) && empty($groupId)) {
  716. //商家手机上开单并生成制作单
  717. if (!empty($post['unitGoodsPrice'])) {
  718. util::fail('此功能停用,有需要请联系管理员');
  719. $unitGoodsPrice = $post['unitGoodsPrice'];
  720. if (!is_numeric($unitGoodsPrice)) {
  721. util::fail('请输入正确的单价');
  722. }
  723. $productList = GoodsClass::orderCreateGoods($post);
  724. }
  725. }
  726. //直接收款
  727. $zjGathering = $post['zjGathering'] ?? 0;
  728. if ($zjGathering == 1) {
  729. $lsGoodsPrice = $post['lsGoodsPrice'] ?? 0;
  730. if (!is_numeric($lsGoodsPrice) || $lsGoodsPrice <= 0) {
  731. util::fail('请填写价格');
  732. }
  733. //直接收款不需要打印小票
  734. $post['needPrint'] = dict::getDict('needPrint', 'noNeed');
  735. $shopId = $this->shopId;
  736. $ext = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  737. $zjGatheringItem = !empty($ext) ? $ext->zjGatheringItem : 0;
  738. if (empty($zjGatheringItem)) {
  739. util::fail('请设置直接收款的商品');
  740. }
  741. $zjGatheringItemInfo = ProductClass::getById($zjGatheringItem, true);
  742. if (empty($zjGatheringItemInfo)) {
  743. util::fail('请设置直接收款的商品哈');
  744. }
  745. $productList = [['productId' => $zjGatheringItem, 'unitType' => 0, 'num' => 1, 'property' => '1', 'unitPrice' => $lsGoodsPrice]];
  746. }
  747. $callErrand = $post['callErrand'] ?? 0;
  748. if ($callErrand == 1) {
  749. $shopId = $this->shopId;
  750. $shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  751. if (!empty($shopExt) && $shopExt->orderFlow == 0) {
  752. util::fail('下单后要变待发货,才能直接发跑腿');
  753. }
  754. }
  755. $connection = Yii::$app->db;
  756. $transaction = $connection->beginTransaction();
  757. try {
  758. $post['product'] = $productList;
  759. $reduceStock = $post['reduceStock'] ?? 0;
  760. if ($reduceStock == 1) {
  761. //如果扣除库,则走另外一条路
  762. $return = OrderClass::reduceMyStock($post, $this->shop, $custom);
  763. $transaction->commit();
  764. util::success($return);
  765. }
  766. //解决开单提交订单时,别人修改价格,造成提交价格不是真实卖价问题!!
  767. $dealPrice = $post['dealPrice'] ?? 0;
  768. //解决重复提交
  769. util::checkRepeatCommit($this->adminId . '_' . $dealPrice, 3);
  770. $totalNum = 0;
  771. if ($dealPrice == 0) {
  772. $productIds = [];
  773. $hsIds = [];
  774. foreach ($productList as $pv) {
  775. $property = $pv['property'] ?? 0;
  776. $puId = $pv['productId'] ?? 0;
  777. if ($property == 0) {
  778. $hsIds[] = $puId;
  779. } else {
  780. $productIds[] = $puId;
  781. }
  782. }
  783. $itemInfo = [];
  784. if (!empty($productIds)) {
  785. $itemInfo = ProductClass::getByIds($productIds, null, 'id');
  786. }
  787. $hsInfo = [];
  788. if (!empty($hsIds)) {
  789. $hsInfo = GoodsClass::getByIds($hsIds, null, 'id');
  790. }
  791. $diff = [];
  792. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  793. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  794. $level = 0;
  795. foreach ($productList as $currentProduct) {
  796. $property = $currentProduct['property'] ?? 0;
  797. $currentPrice = $currentProduct['unitPrice'] ?? 0;
  798. $currentId = $currentProduct['productId'] ?? 0;
  799. if ($property == 1) {
  800. $systemInfo = $itemInfo[$currentId] ?? [];
  801. if (!empty($systemInfo)) {
  802. $name = $systemInfo['name'] ?? '';
  803. $systemPrice = \bizGhs\product\classes\ProductClass::getFinalPrice($systemInfo, $level, $priceMap, $addPriceMap);
  804. if (floatval($currentPrice) != floatval($systemPrice)) {
  805. $diff[] = [
  806. 'name' => $name,
  807. 'price' => $systemPrice,
  808. 'kdPrice' => $currentPrice,
  809. ];
  810. }
  811. }
  812. } else {
  813. $systemInfo = $hsInfo[$currentId] ?? [];
  814. if (!empty($systemInfo)) {
  815. $params = [];
  816. $name = $systemInfo['name'] ?? '';
  817. $hsData = GoodsClass::getFinalPrice($systemInfo, $shop, $custom, $params);
  818. $systemPrice = $hsData['price'] ?? 0;
  819. if ($systemInfo['priceType'] == 1) {
  820. if (floatval($currentPrice) != floatval($systemPrice)) {
  821. $diff[] = [
  822. 'name' => $name,
  823. 'price' => $systemPrice,
  824. 'kdPrice' => $currentPrice,
  825. ];
  826. }
  827. }
  828. }
  829. }
  830. $num = $currentProduct['num'];
  831. $totalNum = bcadd($totalNum, $num);
  832. }
  833. if (!empty($diff)) {
  834. util::success(['diff' => $diff, 'respondType' => 'priceError']);
  835. }
  836. }
  837. //红包使用,多有处,关键词 use_hb_action
  838. $hbId = $post['hbId'] ?? 0;
  839. $hb = null;
  840. if ($hbId > 0) { // 不使用 $hbId =! 0,因为要用负数来表示红包已取消
  841. $hb = HbClass::getById($hbId, true);
  842. if (!empty($hb)) {
  843. if ($hb->customId != $customId) {
  844. util::fail('不是这个客户的红包');
  845. }
  846. if ($hb->amount != $post['hbAmount']) {
  847. util::fail('红包错误'); //红包数据可能被串改
  848. }
  849. if ($hb->status == 1) {
  850. util::fail('红包已使用');
  851. }
  852. if ($hb->status == -1) {
  853. util::fail('红包已作废');
  854. }
  855. if ($hb->endTime < time()) {
  856. $hb->status = -1;
  857. $hb->save();
  858. util::fail('红包已失效');
  859. }
  860. if ($hb->beginTime > time()) {
  861. util::fail('红包可使用期未到');
  862. }
  863. if ($this->shop->rechargeWeal == 3) {
  864. // 判断支付方式是否是余额支付
  865. if ($hasPay != dict::getDict('hasPay', 'balance')) {
  866. util::fail('用红包要用余额支付');
  867. } else {
  868. if($custom->balance < $post['modifyPrice']) {
  869. util::fail('用红包要用余额支付(您的余额不足)');
  870. }
  871. }
  872. }
  873. } else {
  874. Yii::error('没有找到红包,hbId: ', $hbId . ' ' . __METHOD__);
  875. util::fail('红包无效');
  876. }
  877. }
  878. $post['bigNum'] = $totalNum;
  879. //多处调用这个方法,注意同步修改,搜索关键词 createHdNewOrder
  880. $return = OrderService::createHdOrder($post, $custom, $hasPay);
  881. if (!empty($hb)) {
  882. $hb->status = 1;
  883. $hb->orderId = $return->id;
  884. $hb->save();
  885. }
  886. $staff = $this->shopAdmin;
  887. //售后开付款单,库存要变化,关系要建立,多处需要同步修改 sh_pay_change ssh
  888. OrderClass::shPayChange($return, $shop, $staff);
  889. //打印小票和语音播报等使用
  890. $id = $return->id ?? 0;
  891. $order = OrderClass::getById($id, true);
  892. //如果需要生成制作单
  893. $needWork = $post['needWork'] ?? 0;
  894. if ($needWork == 1) {
  895. $main = $this->main;
  896. WorkClass::needWork($order, $main);
  897. $has = WorkClass::getByCondition(['orderId' => $id], true);
  898. if (!empty($has)) {
  899. $return->hasWork = 1;
  900. $return->save();
  901. }
  902. }
  903. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  904. if ($order->getGoods == 1 && $order->sendType == 1 && $order->status == 2) {
  905. $order->status = 4;
  906. $order->save();
  907. }
  908. $transaction->commit();
  909. if ($order->fromType == 3 || $order->fromType == 4) {
  910. //除了客服号下单和美团下单,其它情况允许打小票
  911. } else {
  912. //前台打小票
  913. OrderClass::onlinePrint($order);
  914. }
  915. //订单发跑腿流程
  916. HdDeliveryOrderClass::prepareAskData($post, $order);
  917. //前台提示收款多少钱
  918. ShopExtClass::hdGatheringReport($order);
  919. //前台提醒出示付款码
  920. if (isset($order->status) && $order->status == 1) {
  921. if (isset($post['isCashier']) && $post['isCashier'] == 1) {
  922. ShopExtClass::pleasePayReport($order);
  923. }
  924. }
  925. $shopId = $order->shopId ?? 0;
  926. $shop = ShopClass::getById($shopId, true);
  927. WxMessageClass::gatheringIncomeInform($shop, $order);
  928. if ($needWork == 1) {
  929. //新制作单提示
  930. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  931. ShopExtClass::newWorkRemind($shopExt, $order);
  932. }
  933. util::success($return);
  934. } catch (\Exception $e) {
  935. $transaction->rollBack();
  936. Yii::error("下单失败原因:" . $e->getMessage());
  937. util::fail('下单失败');
  938. }
  939. }
  940. //下单要用到的相关信息 ssh 2019.12.6
  941. public function actionOrderRelate()
  942. {
  943. $regionTree = RegionService::tree();
  944. $shop = $this->shop->attributes;
  945. $freight = MerchantExtendService::getFreight($this->sjExtend);
  946. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  947. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'thirdMapKey' => $mapKey, 'merchant' => $shop];
  948. util::success($out);
  949. }
  950. //余额支付 ssh 2019.12.6
  951. public function actionBalancePay()
  952. {
  953. $post = Yii::$app->request->post();
  954. $orderSn = $post['orderSn'] ?? 0;
  955. $payPassword = $post['payPassword'] ?? 0;
  956. $couponId = $post['couponId'] ?? 0;
  957. $order = OrderService::getByOrderSn($orderSn);
  958. $userId = $this->adminId;
  959. $user = UserService::getUserInfo($userId);
  960. //验证支付密码是否正确
  961. UserService::validPayPassword($payPassword, $user);
  962. //支付前验证订单有效性
  963. OrderService::checkBeforePay($order);
  964. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  965. $totalFee = $order['prePrice'];
  966. $sourceType = 0;
  967. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  968. $actPrice = $discountData['price'];
  969. $callbackParams = [];
  970. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  971. $balance = $respond['balance'] ?? 0;
  972. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  973. }
  974. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  975. public function actionWxPay()
  976. {
  977. ini_set('date.timezone', 'Asia/Shanghai');
  978. $post = Yii::$app->request->post();
  979. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  980. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  981. $order = OrderService::getByOrderSn($orderSn);
  982. $orderId = $order['id'];
  983. //验证优惠券是否还有效
  984. if (!empty($couponId)) {
  985. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  986. }
  987. //支付前验证订单有效性
  988. OrderService::checkBeforePay($order);
  989. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
  990. $totalFee = $order['realPrice'];
  991. //小程序使用miniOpenId
  992. if (httpUtil::isMiniProgram()) {
  993. $openId = $this->user['miniOpenId'];
  994. } else {
  995. $openId = $this->user['openId'];
  996. }
  997. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  998. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  999. $wxPayType = 0;
  1000. if (httpUtil::isMiniProgram()) {
  1001. $wxPayType = 1;
  1002. }
  1003. $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType . '&wxPayType=' . $wxPayType;
  1004. //订单30分钟后过期
  1005. $now = time();
  1006. $expireTime = $now + 1800;
  1007. $wx = Yii::getAlias("@vendor/weixin");
  1008. require_once($wx . '/lib/WxPay.Api.php');
  1009. require_once($wx . '/example/WxPay.JsApiPay.php');
  1010. $input = new \WxPayUnifiedOrder();
  1011. $input->SetBody($name);
  1012. $input->SetOut_trade_no($orderSn);
  1013. $input->SetTotal_fee($totalFee * 100);
  1014. $input->SetTime_start(date("YmdHis", $now));
  1015. $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
  1016. $input->SetTime_expire(date("YmdHis", $expireTime));
  1017. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  1018. $input->SetTrade_type("JSAPI");
  1019. //花卉宝代为申请的微信支付
  1020. $merchantExtend = $this->sjExtend->attributes;
  1021. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  1022. $input->SetSub_openid($openId);
  1023. } else {
  1024. $input->SetOpenid($openId);
  1025. }
  1026. //小程序使用miniAppId
  1027. if (httpUtil::isMiniProgram()) {
  1028. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  1029. }
  1030. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  1031. $tools = new \JsApiPay();
  1032. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  1033. $newParams = json_decode($jsApiParameters, true);
  1034. //已请求微信不能修改价格
  1035. $updateData = [];
  1036. $updateData['modPrice'] = 0;
  1037. if (empty($order['deadline'])) {
  1038. $updateData['deadline'] = $expireTime;
  1039. }
  1040. OrderService::updateById($orderId, $updateData);
  1041. util::success($newParams);
  1042. }
  1043. //快捷付款订单
  1044. public function actionFastPay()
  1045. {
  1046. ini_set('date.timezone', 'Asia/Shanghai');
  1047. $post = Yii::$app->request->post();
  1048. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  1049. $shopId = !empty($this->shopId) ? $this->shopId : ShopService::getDefaultShopId($this->sj);
  1050. //验证门店是否有效
  1051. $shopInfo = ShopService::getById($shopId);
  1052. ShopService::valid($shopInfo, $this->sjId);
  1053. $post['shopId'] = $shopId;
  1054. //默认门店订单
  1055. $store = isset($post['store']) ? $post['store'] : 1;
  1056. $post['store'] = $store;
  1057. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  1058. $sourceType = $this->isWx ? 0 : 1;
  1059. if (httpUtil::isMiniProgram()) {
  1060. $sourceType = 2;
  1061. }
  1062. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  1063. //兼容旧系统sourceType=3表示朋友圈来源
  1064. $fromType = $sourceType == 3 ? 2 : 0;
  1065. $fromType = isset($post['fromType']) && !empty($post['fromType']) ? $post['fromType'] : $fromType;
  1066. $post['userId'] = $this->adminId;
  1067. $custom = $this->custom;
  1068. $post['bookName'] = $custom['userName'] ?? '';
  1069. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  1070. $bookMobile = empty($bookMobile) && isset($custom['mobile']) && !empty($custom['mobile']) ? $custom['mobile'] : $bookMobile;
  1071. $post['bookMobile'] = $bookMobile;
  1072. $prePrice = round($post['prePrice'], 2);
  1073. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1074. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  1075. $actPrice = $discountData['price'];
  1076. $post['discountType'] = $discountData['discountType'];
  1077. $post['discountAmount'] = $discountData['discountAmount'];
  1078. $post['actPrice'] = $actPrice;
  1079. $post['realPrice'] = $actPrice;
  1080. $post['payStyle'] = 0;
  1081. $post['sjId'] = $this->sjId;
  1082. $now = time();
  1083. $expireTime = $now + 300;//订单5分钟后过期
  1084. $post['createTime'] = date("Y-m-d H:i:s", $now);
  1085. $post['deadline'] = $expireTime;
  1086. if ($actPrice <= 0) {
  1087. util::fail('请填写正确的金额');
  1088. }
  1089. //微信支付订单提交不能修改价格
  1090. $post['modPrice'] = $this->isWx ? 0 : 1;
  1091. $post['sourceType'] = $sourceType;
  1092. $post['goodsNum'] = 1;
  1093. $post['fromType'] = $fromType;
  1094. $order = OrderService::addOrder($post);
  1095. $orderId = $order['id'];
  1096. $orderSn = $order['orderSn'];
  1097. $sjId = $this->sjId;
  1098. if ($payWay == 0) {
  1099. $orderId = $order['id'];
  1100. $name = '购买商品';
  1101. $totalFee = $actPrice;
  1102. $user = UserService::getById($this->adminId);
  1103. $openId = isset($user['openId']) ? $user['openId'] : 0;
  1104. if (httpUtil::isMiniProgram()) {
  1105. //小程序使用miniOpenId
  1106. $openId = $user['miniOpenId'];
  1107. }
  1108. if (empty($openId)) {
  1109. util::fail('没有找到客户的openId');
  1110. }
  1111. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1112. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  1113. $wxPayType = 0;
  1114. if (httpUtil::isMiniProgram()) {
  1115. $wxPayType = 1;
  1116. }
  1117. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  1118. $wx = Yii::getAlias("@vendor/weixin");
  1119. require_once($wx . '/lib/WxPay.Api.php');
  1120. require_once($wx . '/example/WxPay.JsApiPay.php');
  1121. $input = new \WxPayUnifiedOrder();
  1122. $input->SetBody($name);
  1123. $input->SetOut_trade_no($orderSn);
  1124. $input->SetTotal_fee($totalFee * 100);
  1125. $input->SetTime_start(date("YmdHis", $now));
  1126. $input->SetAttach($attach);
  1127. //设置订单有效期5分钟
  1128. $input->SetTime_expire(date("YmdHis", $expireTime));
  1129. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  1130. $input->SetTrade_type("JSAPI");
  1131. //花卉宝代为申请的微信支付
  1132. $merchantExtend = $this->sjExtend->attributes;
  1133. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  1134. $input->SetSub_openid($openId);
  1135. } else {
  1136. $input->SetOpenid($openId);
  1137. }
  1138. //小程序使用miniAppId
  1139. if (httpUtil::isMiniProgram()) {
  1140. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  1141. }
  1142. Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
  1143. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  1144. $tools = new \JsApiPay();
  1145. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  1146. $newParams = json_decode($jsApiParameters, true);
  1147. $newParams['orderId'] = $orderId;
  1148. util::success($newParams);
  1149. } elseif ($payWay == 1) {
  1150. $extend = MerchantExtendService::getBySjId($sjId);
  1151. if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
  1152. util::fail('支付宝付款即将开通...');
  1153. }
  1154. $config = [
  1155. //应用ID,您的APPID。
  1156. 'app_id' => $extend['alipayPId'],
  1157. //商户私钥,您的原始格式RSA私钥
  1158. 'merchant_private_key' => $extend['alipayKey'],
  1159. //异步通知地址
  1160. 'notify_url' => Yii::$app->params['hdHost'] . "/notice/ali-callback",
  1161. //同步跳转
  1162. 'return_url' => "",
  1163. //编码格式
  1164. 'charset' => "UTF-8",
  1165. //签名方式
  1166. 'sign_type' => "RSA2",
  1167. //支付宝网关
  1168. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  1169. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  1170. 'alipay_public_key' => $extend['alipayPublicKey'],
  1171. ];
  1172. Yii::info(json_encode($config) . ' aplipay config');
  1173. $alipayWap = Yii::getAlias("@vendor/alipayWap");
  1174. require_once($alipayWap . '/wappay/service/AlipayTradeService.php');
  1175. require_once($alipayWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  1176. $totalFee = $order['realPrice'];
  1177. $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  1178. $subject = '购买商品';//订单名称,必填
  1179. $total_amount = $totalFee;//付款金额,必填
  1180. $body = '';//商品描述,可空
  1181. $timeout_express = "1m";//超时时间
  1182. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1183. $passBackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&sjId=' . $sjId;//将流水类型、优惠卷传过去
  1184. $passBackParams = urlencode($passBackParams);
  1185. $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
  1186. $payRequestBuilder->setBody($body);
  1187. $payRequestBuilder->setSubject($subject);
  1188. $payRequestBuilder->setOutTradeNo($out_trade_no);
  1189. $payRequestBuilder->setTotalAmount($total_amount);
  1190. $payRequestBuilder->setTimeExpress($timeout_express);
  1191. //在异步通知时将该参数原样返回
  1192. $payRequestBuilder->setPassbackParams($passBackParams);
  1193. //同步通知
  1194. $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$sjId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  1195. //异步通知
  1196. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/ali-callback";
  1197. $payResponse = new \AlipayTradeService($config);
  1198. $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
  1199. //直接将支付宝的html返回给前端
  1200. echo $result;
  1201. } elseif ($payWay == 2) {
  1202. //余额支付
  1203. util::fail('暂不支持');
  1204. } else {
  1205. util::fail('无效的支付方式');
  1206. }
  1207. }
  1208. //订单评价
  1209. public function actionComment()
  1210. {
  1211. $post = Yii::$app->request->post();
  1212. $id = $post['id'];
  1213. $order = OrderService::getById($id);
  1214. OrderService::valid($order, $this->mainId);
  1215. if ($order['grade'] > 0) {
  1216. util::fail('您已经评过了');
  1217. }
  1218. OrderService::comment($post);
  1219. util::complete('提交成功');
  1220. }
  1221. //订单详情,不需要登陆可以查看,要有盐,给跑腿上查看订单信息用的
  1222. public function actionInfo()
  1223. {
  1224. $get = Yii::$app->request->get();
  1225. $id = $get['id'] ?? 0;
  1226. $salt = $get['salt'] ?? '';
  1227. $detail = OrderClass::getFullInfo($id);
  1228. if (empty($detail)) {
  1229. util::fail('没有找到订单');
  1230. }
  1231. if (empty($detail['salt'])) {
  1232. util::fail('没有找到订单信息');
  1233. }
  1234. if (empty($salt)) {
  1235. util::fail('请求参数错误呢');
  1236. }
  1237. if ($detail['salt'] != $salt) {
  1238. util::fail('不是你的订单');
  1239. }
  1240. util::success($detail);
  1241. }
  1242. //订单详情
  1243. public function actionDetail()
  1244. {
  1245. $id = Yii::$app->request->get('id', 0);
  1246. $detail = OrderClass::getFullInfo($id);
  1247. OrderService::valid($detail, $this->mainId);
  1248. $forwardMap = [];
  1249. if ($detail['forward'] == 1) {
  1250. //当前单如果已经是红冲订单,则取出其对应的原单
  1251. $map = OrderForwardClass::getByCondition(['shOrderId' => $id], true);
  1252. if (!empty($map)) {
  1253. $originOrderId = $map->orderId ?? 0;
  1254. $forwardMap['orderId'] = $originOrderId;
  1255. }
  1256. }
  1257. $detail['forwardMap'] = $forwardMap;
  1258. $shOrderMap = [];
  1259. if ($detail['hasForward'] == 1) {
  1260. $shOrderMap = OrderForwardClass::getAllByCondition(['orderId' => $id], null, '*');
  1261. }
  1262. $detail['shOrderMap'] = $shOrderMap;
  1263. $main = $this->main;
  1264. //是否走红冲订单模式判断 ssh
  1265. $ret = OrderClass::ifShPay($detail, $main, 0);
  1266. $shAddPay = $ret['shAddPay'];
  1267. $shAddPayReason = $ret['shAddPayReason'];
  1268. $detail['shAddPay'] = $shAddPay;
  1269. $detail['shAddPayReason'] = $shAddPayReason;
  1270. util::success($detail);
  1271. }
  1272. public function actionList()
  1273. {
  1274. $get = Yii::$app->request->get();
  1275. $searchText = $get['searchText'] ?? '';
  1276. $shopId = $this->shopId ?? 0;
  1277. if (empty($shopId)) {
  1278. //没有登录不显示数据
  1279. util::success(['list' => [], 'moreData' => 0, 'shop' => [], 'totalNum' => 0, 'totalPage' => 0]);
  1280. }
  1281. $where = [];
  1282. $where['shopId'] = $shopId;
  1283. if (!empty($get['customId'])) {
  1284. $where['customId'] = $get['customId'];
  1285. }
  1286. if (!empty($get['ids'])) {
  1287. $stringIds = $get['ids'];
  1288. $newIds = explode(',', $stringIds);
  1289. $where['id'] = ['in', $newIds];
  1290. }
  1291. $status = $get['status'] ?? 0;
  1292. if (!empty($status)) {
  1293. $where['status'] = $get['status'];
  1294. }
  1295. $debt = $get['debt'] ?? -1;
  1296. if ($debt > -1) {
  1297. $where['debt'] = $debt;
  1298. }
  1299. if (!empty($get['shopAdminId'])) {
  1300. $where['shopAdminId'] = $get['shopAdminId'];
  1301. }
  1302. // 按搜索词自动识别:纯数字查货号,否则查姓名
  1303. if (!empty($searchText)) {
  1304. $this->appendOrderListSearchWhere($where, $searchText);
  1305. }
  1306. if (isset($get['repeat']) && $get['repeat'] > -1) {
  1307. $where['repeat'] = $get['repeat'];
  1308. }
  1309. if (!empty($get['searchTime'])) {
  1310. $startTime = $get['startTime'] ?? '';
  1311. $endTime = $get['endTime'] ?? '';
  1312. $period = dateUtil::formatTime($get['searchTime'], $startTime, $endTime);
  1313. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1314. }
  1315. $list = OrderService::getOrderList($where);
  1316. $list['shop'] = $this->shop->attributes ?? [];
  1317. util::success($list);
  1318. }
  1319. //订单归类 ssh 2019.12.17
  1320. public function actionClassify()
  1321. {
  1322. $post = Yii::$app->request->post();
  1323. $id = $post['id'] ?? 0;
  1324. $order = OrderService::getById($id);
  1325. OrderService::valid($order, $this->mainId);
  1326. $categoryId = $post['categoryId'];
  1327. $usageId = $post['usageId'];
  1328. OrderService::classify($id, $categoryId, $usageId);
  1329. util::complete();
  1330. }
  1331. //更新配送单 ssh 2019.12.17
  1332. public function actionUpdateSheet()
  1333. {
  1334. $post = Yii::$app->request->post();
  1335. $id = $post['id'] ?? 0;
  1336. unset($post['id']);
  1337. $order = OrderService::getById($id);
  1338. OrderService::valid($order, $this->mainId);
  1339. OrderService::updateSheet($order, $post);
  1340. util::complete('提交成功');
  1341. }
  1342. //商家收款与发货 ssh 2019.12.18
  1343. public function actionGathering()
  1344. {
  1345. $post = Yii::$app->request->post();
  1346. $price = isset($post['price']) && is_numeric($post['price']) ? $post['price'] : 0;
  1347. $payWay = isset($post['payWay']) && is_numeric($post['payWay']) ? $post['payWay'] : 0;
  1348. $userId = $post['userId'] ?? 0;
  1349. $userInfo = UserService::getById($userId);
  1350. if (empty($userInfo) || $userInfo['sjId'] != $this->sjId) {
  1351. util::fail('您选择的客户无效');
  1352. }
  1353. if ($price <= 0) {
  1354. util::fail('请输入金额');
  1355. }
  1356. $post['prePrice'] = $price;
  1357. $post['actPrice'] = $price;
  1358. $post['payWay'] = $payWay;
  1359. $post['sourceType'] = 1;
  1360. $post['userId'] = $userId;
  1361. $post['goodsNum'] = 1;
  1362. $post['orderName'] = '商品';
  1363. $shopId = MerchantService::getDefaultShopId($this->sj);
  1364. $post['shopId'] = $shopId;
  1365. $order = OrderService::addOrder($post);
  1366. $id = $order['id'];
  1367. $orderSn = $order['orderSn'];
  1368. //流水类型列表
  1369. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1370. $callbackParams = [];
  1371. switch ($payWay) {
  1372. case 0:
  1373. xhPayToolService::wxPay($callbackParams, $orderSn, $price, $capitalType, 0);
  1374. break;
  1375. case 1:
  1376. xhPayToolService::alipay($callbackParams, $orderSn, $price, $capitalType, 0, []);
  1377. break;
  1378. case 2:
  1379. xhPayToolService::balancePay($callbackParams, $orderSn, $price, $capitalType, 0);
  1380. break;
  1381. default:
  1382. util::fail('无效支付方式');
  1383. }
  1384. util::success($order);
  1385. }
  1386. //免发货管理 ssh 2020.1.6
  1387. public function actionWithoutSend()
  1388. {
  1389. $id = Yii::$app->request->get('id');
  1390. $order = OrderService::getById($id);
  1391. OrderService::valid($order, $this->mainId);
  1392. //配送流程变更
  1393. $currentFlow = OrderSendClass::withoutSend($order);
  1394. util::success(['currentFlow' => $currentFlow]);
  1395. }
  1396. //修改价格 ssh 2020.1.6
  1397. public function actionUpdatePrice()
  1398. {
  1399. $id = Yii::$app->request->get('id');
  1400. $price = Yii::$app->request->get('price', 1);
  1401. $order = OrderService::getById($id);
  1402. OrderService::valid($order, $this->mainId);
  1403. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  1404. util::fail('已发起支付,不能修改价格');
  1405. }
  1406. OrderService::updateById($id, ['actPrice' => $price]);
  1407. util::complete('修改成功');
  1408. }
  1409. //配送单 ssh 2020.2.29
  1410. public function actionGetDeliverDetail()
  1411. {
  1412. $id = Yii::$app->request->get('id', 0);
  1413. $order = OrderService::getById($id);
  1414. OrderService::valid($order, $this->mainId);
  1415. $reachDate = isset($order['reachDate']) && !empty($order['reachDate']) ? $order['reachDate'] : '';
  1416. $reachPeriodId = $order['reachPeriod'];
  1417. $reachPeriodArr = [0 => '上午', 1 => '下午', 2 => '晚上'];
  1418. $reachPeriod = isset($reachPeriodArr[$reachPeriodId]) ? $reachPeriodArr[$reachPeriodId] : '';
  1419. $bookName = isset($order['bookName']) ? $order['bookName'] : '';
  1420. $bookMobile = isset($order['bookMobile']) ? $order['bookMobile'] : '';
  1421. if (isset($order['anonymity']) && $order['anonymity'] == 1) {
  1422. $bookName = '--';
  1423. $bookMobile = '--';
  1424. }
  1425. $data = [
  1426. 'reachDate' => $reachDate . ' ' . $reachPeriod,
  1427. 'orderSn' => $order['orderSn'],
  1428. 'receiveUserName' => $order['receiveUserName'],
  1429. 'receiveMobile' => $order['receiveMobile'],
  1430. 'fullAddress' => $order['fullAddress'] . "(" . $order['showAddress'] . ")",
  1431. 'cardInfo' => $order['cardInfo'],
  1432. 'bookMobile' => $bookMobile,
  1433. 'bookName' => $bookName,
  1434. 'remark' => $order['remark'],
  1435. 'sendNum' => $order['sendNum'],
  1436. 'telephone' => 18030142050,
  1437. 'printTime' => '',
  1438. 'img' => '',
  1439. ];
  1440. util::success($data);
  1441. }
  1442. //运费计算 lqh 2021.4.12 暂反回固定
  1443. public function actionFreight()
  1444. {
  1445. util::success(['sedCost' => 10]);
  1446. }
  1447. /**
  1448. * 订单列表搜索条件:纯数字按货号精确匹配,否则按客户姓名模糊匹配
  1449. * @param array $where 查询条件(引用传递)
  1450. * @param string $searchText 搜索关键词
  1451. */
  1452. private function appendOrderListSearchWhere(&$where, $searchText)
  1453. {
  1454. $searchText = trim((string)$searchText);
  1455. if ($searchText === '') {
  1456. return;
  1457. }
  1458. if (preg_match('/^\d+$/', $searchText)) {
  1459. $where['sendNum'] = $searchText;
  1460. return;
  1461. }
  1462. $where['customName'] = ['like', $searchText];
  1463. }
  1464. }