OrderController.php 72 KB

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