OrderController.php 73 KB

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