OrderController.php 72 KB

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