OrderController.php 71 KB

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