OrderController.php 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776
  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. /**
  680. * 开单操作
  681. * 若前端已将会员折扣/门店满减写入 modifyPrice,可传 skipMemberDiscount、skipShopMeetCut,避免二次扣减。
  682. */
  683. public function actionCreateOrder()
  684. {
  685. $post = Yii::$app->request->post();
  686. $post['sjId'] = $this->sjId;
  687. $post['shopId'] = $this->shopId;
  688. $post['mainId'] = $this->mainId ?? 0;
  689. $shop = $this->shop;
  690. if ($shop->memberLevelSet == 0) {
  691. //util::fail('请先设置会员等级');
  692. }
  693. $now = time();
  694. $orderValidTime = 600;
  695. $expireTime = $now + $orderValidTime;
  696. $post['deadline'] = $expireTime;
  697. $post['staffId'] = $this->shopAdminId ?? 0;
  698. $post['staffName'] = $this->shopAdmin->name ?? '';
  699. $post['flowerNum'] = isset($post['flowerNum']) && $post['flowerNum'] > 0 ? $post['flowerNum'] : 0;
  700. $version = $post['version'] ?? 0; //验证已移至 CreateOrderForm
  701. if ($version < 3) {
  702. util::fail('请升级版本,或用小程序');
  703. }
  704. // 不再支持红冲负单字段
  705. $post['forward'] = 0;
  706. //默认情况开单员工和收款员工是同个人
  707. $staffId = $this->shopAdminId ?? 0;
  708. $staffName = $this->shopAdmin->name ?? '';
  709. if (empty($post['shopAdminId'])) {
  710. $post['shopAdminId'] = $staffId;
  711. $post['shopAdminName'] = $staffName;
  712. }
  713. if (empty($post['getStaffId'])) {
  714. $post['getStaffId'] = $staffId;
  715. $post['getStaffName'] = $this->shopAdmin->name ?? '';
  716. }
  717. $groupId = !empty($post['groupId']) ? $post['groupId'] : 0;
  718. $post['fromType'] = $post['fromType'] ?? 1;
  719. if ($post['fromType'] == dict::getDict('fromType', 'friend')) {
  720. if (empty($post['bookName'])) {
  721. util::fail('请填写订花人姓名');
  722. }
  723. }
  724. $customId = $post['customId'] ?? 0;
  725. $custom = CustomClass::getById($customId, true);
  726. if (empty($custom)) {
  727. util::fail('没有找到客户哦');
  728. }
  729. $hdId = $custom->hdId ?? 0;
  730. $hd = HdClass::getById($hdId, true);
  731. if (empty($hd)) {
  732. util::fail('客户对应的花店信息缺失,编号869');
  733. }
  734. $hdName = $hd->name ?? '';
  735. $post['hdId'] = $hdId;
  736. $post['hdName'] = $hdName;
  737. $customName = $custom->name ?? '';
  738. $post['customName'] = $customName;
  739. $post['customNamePy'] = stringUtil::py($customName);
  740. if (!empty($post['receiveMobile'])) {
  741. if (!stringUtil::isMobile($post['receiveMobile'])) {
  742. util::fail('请填写正确的收花人手机号');
  743. }
  744. }
  745. if (!empty($post['bookMobile'])) {
  746. if (!stringUtil::isMobile($post['bookMobile'])) {
  747. util::fail('请填写正确的订花人手机号');
  748. }
  749. }
  750. $hasPay = $post['hasPay'] ?? dict::getDict('hasPay', 'unPay');
  751. $post['sendType'] = $post['sendType'] ?? 1;
  752. $productJson = $post['product'] ?? '';
  753. $productList = [];
  754. if (!empty($productJson)) {
  755. $productList = json_decode($productJson, true);
  756. }
  757. if (empty($productList) && empty($groupId)) {
  758. //商家手机上开单并生成制作单
  759. if (!empty($post['unitGoodsPrice'])) {
  760. util::fail('此功能停用,有需要请联系管理员');
  761. $unitGoodsPrice = $post['unitGoodsPrice'];
  762. if (!is_numeric($unitGoodsPrice)) {
  763. util::fail('请输入正确的单价');
  764. }
  765. $productList = GoodsClass::orderCreateGoods($post);
  766. }
  767. }
  768. //直接收款
  769. $zjGathering = $post['zjGathering'] ?? 0;
  770. if ($zjGathering == 1) {
  771. $lsGoodsPrice = $post['lsGoodsPrice'] ?? 0;
  772. if (!is_numeric($lsGoodsPrice) || $lsGoodsPrice <= 0) {
  773. util::fail('请填写价格');
  774. }
  775. //直接收款不需要打印小票
  776. $post['needPrint'] = dict::getDict('needPrint', 'noNeed');
  777. $shopId = $this->shopId;
  778. $ext = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  779. $zjGatheringItem = !empty($ext) ? $ext->zjGatheringItem : 0;
  780. if (empty($zjGatheringItem)) {
  781. util::fail('请设置直接收款的商品');
  782. }
  783. $zjGatheringItemInfo = ProductClass::getById($zjGatheringItem, true);
  784. if (empty($zjGatheringItemInfo)) {
  785. util::fail('请设置直接收款的商品哈');
  786. }
  787. $productList = [['productId' => $zjGatheringItem, 'unitType' => 0, 'num' => 1, 'property' => '1', 'unitPrice' => $lsGoodsPrice]];
  788. }
  789. $callErrand = $post['callErrand'] ?? 0;
  790. if ($callErrand == 1) {
  791. $shopId = $this->shopId;
  792. $shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], true);
  793. if (!empty($shopExt) && $shopExt->orderFlow == 0) {
  794. util::fail('下单后要变待发货,才能直接发跑腿');
  795. }
  796. }
  797. $connection = Yii::$app->db;
  798. $transaction = $connection->beginTransaction();
  799. try {
  800. $post['product'] = $productList;
  801. $reduceStock = $post['reduceStock'] ?? 0;
  802. if ($reduceStock == 1) {
  803. //如果扣除库,则走另外一条路
  804. $return = OrderClass::reduceMyStock($post, $this->shop, $custom);
  805. $transaction->commit();
  806. util::success($return);
  807. }
  808. //解决开单提交订单时,别人修改价格,造成提交价格不是真实卖价问题!!
  809. $dealPrice = $post['dealPrice'] ?? 0;
  810. //解决重复提交
  811. util::checkRepeatCommit($this->adminId . '_' . $dealPrice, 3);
  812. $totalNum = 0;
  813. if ($dealPrice == 0) {
  814. $productIds = [];
  815. $hsIds = [];
  816. foreach ($productList as $pv) {
  817. $property = $pv['property'] ?? 0;
  818. $puId = $pv['productId'] ?? 0;
  819. if ($property == 0) {
  820. $hsIds[] = $puId;
  821. } else {
  822. $productIds[] = $puId;
  823. }
  824. }
  825. $itemInfo = [];
  826. if (!empty($productIds)) {
  827. $itemInfo = ProductClass::getByIds($productIds, null, 'id');
  828. }
  829. $hsInfo = [];
  830. if (!empty($hsIds)) {
  831. $hsInfo = GoodsClass::getByIds($hsIds, null, 'id');
  832. }
  833. $diff = [];
  834. $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
  835. $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
  836. $level = 0;
  837. foreach ($productList as $currentProduct) {
  838. $property = $currentProduct['property'] ?? 0;
  839. $currentPrice = $currentProduct['unitPrice'] ?? 0;
  840. $currentId = $currentProduct['productId'] ?? 0;
  841. if ($property == 1) {
  842. $systemInfo = $itemInfo[$currentId] ?? [];
  843. if (!empty($systemInfo)) {
  844. $name = $systemInfo['name'] ?? '';
  845. $systemPrice = \bizGhs\product\classes\ProductClass::getFinalPrice($systemInfo, $level, $priceMap, $addPriceMap);
  846. if (floatval($currentPrice) != floatval($systemPrice)) {
  847. $diff[] = [
  848. 'name' => $name,
  849. 'price' => $systemPrice,
  850. 'kdPrice' => $currentPrice,
  851. ];
  852. }
  853. }
  854. } else {
  855. $systemInfo = $hsInfo[$currentId] ?? [];
  856. if (!empty($systemInfo)) {
  857. $params = [];
  858. $name = $systemInfo['name'] ?? '';
  859. $hsData = GoodsClass::getFinalPrice($systemInfo, $shop, $custom, $params);
  860. $systemPrice = $hsData['price'] ?? 0;
  861. if ($systemInfo['priceType'] == 1) {
  862. if (floatval($currentPrice) != floatval($systemPrice)) {
  863. $diff[] = [
  864. 'name' => $name,
  865. 'price' => $systemPrice,
  866. 'kdPrice' => $currentPrice,
  867. ];
  868. }
  869. }
  870. }
  871. }
  872. $num = $currentProduct['num'];
  873. $totalNum = bcadd($totalNum, $num);
  874. }
  875. if (!empty($diff)) {
  876. util::success(['diff' => $diff, 'respondType' => 'priceError']);
  877. }
  878. }
  879. //红包使用,多有处,关键词 use_hb_action
  880. $hbId = $post['hbId'] ?? 0;
  881. $hb = null;
  882. if ($hbId > 0) { // 不使用 $hbId =! 0,因为要用负数来表示红包已取消
  883. $hb = HbClass::getById($hbId, true);
  884. if (!empty($hb)) {
  885. if ($hb->customId != $customId) {
  886. util::fail('不是这个客户的红包');
  887. }
  888. if ($hb->amount != $post['hbAmount']) {
  889. util::fail('红包错误'); //红包数据可能被串改
  890. }
  891. if ($hb->status == 1) {
  892. util::fail('红包已使用');
  893. }
  894. if ($hb->status == -1) {
  895. util::fail('红包已作废');
  896. }
  897. if ($hb->endTime < time()) {
  898. $hb->status = -1;
  899. $hb->save();
  900. util::fail('红包已失效');
  901. }
  902. if ($hb->beginTime > time()) {
  903. util::fail('红包可使用期未到');
  904. }
  905. // 按适用范围校验最低消费
  906. HbScopeClass::assertMinConsume($hb, $post['product'] ?? [], $post['modifyPrice'] ?? 0);
  907. if ($this->shop->rechargeWeal == 3) {
  908. // 判断支付方式是否是余额支付
  909. if ($hasPay != dict::getDict('hasPay', 'balance')) {
  910. util::fail('用红包要用余额支付');
  911. } else {
  912. if ($custom->balance < $post['modifyPrice']) {
  913. util::fail('用红包要用余额支付(您的余额不足)');
  914. }
  915. }
  916. }
  917. } else {
  918. Yii::error('没有找到红包,hbId: ', $hbId . ' ' . __METHOD__);
  919. util::fail('红包无效');
  920. }
  921. }
  922. $post['bigNum'] = $totalNum;
  923. // 开单页已把会员折扣/门店满减写入 modifyPrice 时会传 skip*,避免 createHdOrder/addOrder 二次扣减
  924. if (!empty($post['skipMemberDiscount'])) {
  925. $post['skipMemberDiscount'] = 1;
  926. }
  927. if (!empty($post['skipShopMeetCut'])) {
  928. $post['skipShopMeetCut'] = 1;
  929. }
  930. //多处调用这个方法,注意同步修改,搜索关键词 createHdNewOrder
  931. $return = OrderService::createHdOrder($post, $custom, $hasPay);
  932. if (!empty($hb)) {
  933. $hb->status = 1;
  934. $hb->orderId = $return->id;
  935. $hb->save();
  936. }
  937. //打印小票和语音播报等使用
  938. $id = $return->id ?? 0;
  939. $order = OrderClass::getById($id, true);
  940. //如果需要生成制作单
  941. $needWork = $post['needWork'] ?? 0;
  942. if ($needWork == 1) {
  943. $main = $this->main;
  944. WorkClass::needWork($order, $main);
  945. $has = WorkClass::getByCondition(['orderId' => $id], true);
  946. if (!empty($has)) {
  947. $return->hasWork = 1;
  948. $return->save();
  949. }
  950. }
  951. //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
  952. if ($order->getGoods == 1 && $order->sendType == 1 && $order->status == 2) {
  953. $order->status = 4;
  954. $order->save();
  955. DistributionCommissionClass::onRetailOrderCompleted((int)$order->id);
  956. }
  957. $transaction->commit();
  958. if ($order->fromType == 3 || $order->fromType == 4) {
  959. //除了客服号下单和美团下单,其它情况允许打小票
  960. } else {
  961. //前台打小票
  962. OrderClass::onlinePrint($order);
  963. }
  964. //订单发跑腿流程
  965. HdDeliveryOrderClass::prepareAskData($post, $order);
  966. //前台提示收款多少钱
  967. ShopExtClass::hdGatheringReport($order);
  968. //前台提醒出示付款码
  969. if (isset($order->status) && $order->status == 1) {
  970. if (isset($post['isCashier']) && $post['isCashier'] == 1) {
  971. ShopExtClass::pleasePayReport($order);
  972. }
  973. }
  974. $shopId = $order->shopId ?? 0;
  975. $shop = ShopClass::getById($shopId, true);
  976. WxMessageClass::gatheringIncomeInform($shop, $order);
  977. if ($needWork == 1) {
  978. //新制作单提示
  979. $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
  980. ShopExtClass::newWorkRemind($shopExt, $order);
  981. }
  982. util::success($return);
  983. } catch (\Exception $e) {
  984. $transaction->rollBack();
  985. Yii::error("下单失败原因:" . $e->getMessage());
  986. util::fail('下单失败');
  987. }
  988. }
  989. //下单要用到的相关信息 ssh 2019.12.6
  990. public function actionOrderRelate()
  991. {
  992. $regionTree = RegionService::tree();
  993. $shop = $this->shop->attributes;
  994. $freight = MerchantExtendService::getFreight($this->sjExtend);
  995. $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
  996. $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'thirdMapKey' => $mapKey, 'merchant' => $shop];
  997. util::success($out);
  998. }
  999. //余额支付 ssh 2019.12.6
  1000. public function actionBalancePay()
  1001. {
  1002. $post = Yii::$app->request->post();
  1003. $orderSn = $post['orderSn'] ?? 0;
  1004. $payPassword = $post['payPassword'] ?? 0;
  1005. $couponId = $post['couponId'] ?? 0;
  1006. $order = OrderService::getByOrderSn($orderSn);
  1007. $userId = $this->adminId;
  1008. $user = UserService::getUserInfo($userId);
  1009. //验证支付密码是否正确
  1010. UserService::validPayPassword($payPassword, $user);
  1011. //支付前验证订单有效性
  1012. OrderService::checkBeforePay($order);
  1013. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1014. $totalFee = $order['prePrice'];
  1015. $sourceType = 0;
  1016. $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  1017. $actPrice = $discountData['price'];
  1018. $callbackParams = [];
  1019. $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
  1020. $balance = $respond['balance'] ?? 0;
  1021. util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
  1022. }
  1023. //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
  1024. public function actionWxPay()
  1025. {
  1026. ini_set('date.timezone', 'Asia/Shanghai');
  1027. $post = Yii::$app->request->post();
  1028. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1029. $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
  1030. $order = OrderService::getByOrderSn($orderSn);
  1031. $orderId = $order['id'];
  1032. //验证优惠券是否还有效
  1033. if (!empty($couponId)) {
  1034. CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
  1035. }
  1036. //支付前验证订单有效性
  1037. OrderService::checkBeforePay($order);
  1038. $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
  1039. $totalFee = $order['realPrice'];
  1040. //小程序使用miniOpenId
  1041. if (httpUtil::isMiniProgram()) {
  1042. $openId = $this->user['miniOpenId'];
  1043. } else {
  1044. $openId = $this->user['openId'];
  1045. }
  1046. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1047. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  1048. $wxPayType = 0;
  1049. if (httpUtil::isMiniProgram()) {
  1050. $wxPayType = 1;
  1051. }
  1052. $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType . '&wxPayType=' . $wxPayType;
  1053. //订单30分钟后过期
  1054. $now = time();
  1055. $expireTime = $now + 1800;
  1056. $wx = Yii::getAlias("@vendor/weixin");
  1057. require_once($wx . '/lib/WxPay.Api.php');
  1058. require_once($wx . '/example/WxPay.JsApiPay.php');
  1059. $input = new \WxPayUnifiedOrder();
  1060. $input->SetBody($name);
  1061. $input->SetOut_trade_no($orderSn);
  1062. $input->SetTotal_fee($totalFee * 100);
  1063. $input->SetTime_start(date("YmdHis", $now));
  1064. $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
  1065. $input->SetTime_expire(date("YmdHis", $expireTime));
  1066. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  1067. $input->SetTrade_type("JSAPI");
  1068. //花卉宝代为申请的微信支付
  1069. $merchantExtend = $this->sjExtend->attributes;
  1070. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  1071. $input->SetSub_openid($openId);
  1072. } else {
  1073. $input->SetOpenid($openId);
  1074. }
  1075. //小程序使用miniAppId
  1076. if (httpUtil::isMiniProgram()) {
  1077. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  1078. }
  1079. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  1080. $tools = new \JsApiPay();
  1081. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  1082. $newParams = json_decode($jsApiParameters, true);
  1083. //已请求微信不能修改价格
  1084. $updateData = [];
  1085. $updateData['modPrice'] = 0;
  1086. if (empty($order['deadline'])) {
  1087. $updateData['deadline'] = $expireTime;
  1088. }
  1089. OrderService::updateById($orderId, $updateData);
  1090. util::success($newParams);
  1091. }
  1092. //快捷付款订单
  1093. public function actionFastPay()
  1094. {
  1095. ini_set('date.timezone', 'Asia/Shanghai');
  1096. $post = Yii::$app->request->post();
  1097. $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
  1098. $shopId = !empty($this->shopId) ? $this->shopId : ShopService::getDefaultShopId($this->sj);
  1099. //验证门店是否有效
  1100. $shopInfo = ShopService::getById($shopId);
  1101. ShopService::valid($shopInfo, $this->sjId);
  1102. $post['shopId'] = $shopId;
  1103. //默认门店订单
  1104. $store = isset($post['store']) ? $post['store'] : 1;
  1105. $post['store'] = $store;
  1106. //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
  1107. $sourceType = $this->isWx ? 0 : 1;
  1108. if (httpUtil::isMiniProgram()) {
  1109. $sourceType = 2;
  1110. }
  1111. $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
  1112. //兼容旧系统sourceType=3表示朋友圈来源
  1113. $fromType = $sourceType == 3 ? 2 : 0;
  1114. $fromType = isset($post['fromType']) && !empty($post['fromType']) ? $post['fromType'] : $fromType;
  1115. $post['userId'] = $this->adminId;
  1116. $custom = $this->custom;
  1117. $post['bookName'] = $custom['userName'] ?? '';
  1118. $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
  1119. $bookMobile = empty($bookMobile) && isset($custom['mobile']) && !empty($custom['mobile']) ? $custom['mobile'] : $bookMobile;
  1120. $post['bookMobile'] = $bookMobile;
  1121. $prePrice = round($post['prePrice'], 2);
  1122. $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
  1123. $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
  1124. $actPrice = $discountData['price'];
  1125. $post['discountType'] = $discountData['discountType'];
  1126. $post['discountAmount'] = $discountData['discountAmount'];
  1127. $post['actPrice'] = $actPrice;
  1128. $post['realPrice'] = $actPrice;
  1129. $post['payStyle'] = 0;
  1130. $post['sjId'] = $this->sjId;
  1131. $now = time();
  1132. $expireTime = $now + 300;//订单5分钟后过期
  1133. $post['createTime'] = date("Y-m-d H:i:s", $now);
  1134. $post['deadline'] = $expireTime;
  1135. if ($actPrice <= 0) {
  1136. util::fail('请填写正确的金额');
  1137. }
  1138. //微信支付订单提交不能修改价格
  1139. $post['modPrice'] = $this->isWx ? 0 : 1;
  1140. $post['sourceType'] = $sourceType;
  1141. $post['goodsNum'] = 1;
  1142. $post['fromType'] = $fromType;
  1143. $order = OrderService::addOrder($post);
  1144. $orderId = $order['id'];
  1145. $orderSn = $order['orderSn'];
  1146. $sjId = $this->sjId;
  1147. if ($payWay == 0) {
  1148. $orderId = $order['id'];
  1149. $name = '购买商品';
  1150. $totalFee = $actPrice;
  1151. $user = UserService::getById($this->adminId);
  1152. $openId = isset($user['openId']) ? $user['openId'] : 0;
  1153. if (httpUtil::isMiniProgram()) {
  1154. //小程序使用miniOpenId
  1155. $openId = $user['miniOpenId'];
  1156. }
  1157. if (empty($openId)) {
  1158. util::fail('没有找到客户的openId');
  1159. }
  1160. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1161. //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
  1162. $wxPayType = 0;
  1163. if (httpUtil::isMiniProgram()) {
  1164. $wxPayType = 1;
  1165. }
  1166. $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
  1167. $wx = Yii::getAlias("@vendor/weixin");
  1168. require_once($wx . '/lib/WxPay.Api.php');
  1169. require_once($wx . '/example/WxPay.JsApiPay.php');
  1170. $input = new \WxPayUnifiedOrder();
  1171. $input->SetBody($name);
  1172. $input->SetOut_trade_no($orderSn);
  1173. $input->SetTotal_fee($totalFee * 100);
  1174. $input->SetTime_start(date("YmdHis", $now));
  1175. $input->SetAttach($attach);
  1176. //设置订单有效期5分钟
  1177. $input->SetTime_expire(date("YmdHis", $expireTime));
  1178. $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
  1179. $input->SetTrade_type("JSAPI");
  1180. //花卉宝代为申请的微信支付
  1181. $merchantExtend = $this->sjExtend->attributes;
  1182. if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
  1183. $input->SetSub_openid($openId);
  1184. } else {
  1185. $input->SetOpenid($openId);
  1186. }
  1187. //小程序使用miniAppId
  1188. if (httpUtil::isMiniProgram()) {
  1189. $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
  1190. }
  1191. Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
  1192. $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
  1193. $tools = new \JsApiPay();
  1194. $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
  1195. $newParams = json_decode($jsApiParameters, true);
  1196. $newParams['orderId'] = $orderId;
  1197. util::success($newParams);
  1198. } elseif ($payWay == 1) {
  1199. $extend = MerchantExtendService::getBySjId($sjId);
  1200. if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
  1201. util::fail('支付宝付款即将开通...');
  1202. }
  1203. $config = [
  1204. //应用ID,您的APPID。
  1205. 'app_id' => $extend['alipayPId'],
  1206. //商户私钥,您的原始格式RSA私钥
  1207. 'merchant_private_key' => $extend['alipayKey'],
  1208. //异步通知地址
  1209. 'notify_url' => Yii::$app->params['hdHost'] . "/notice/ali-callback",
  1210. //同步跳转
  1211. 'return_url' => "",
  1212. //编码格式
  1213. 'charset' => "UTF-8",
  1214. //签名方式
  1215. 'sign_type' => "RSA2",
  1216. //支付宝网关
  1217. 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
  1218. //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
  1219. 'alipay_public_key' => $extend['alipayPublicKey'],
  1220. ];
  1221. Yii::info(json_encode($config) . ' aplipay config');
  1222. $alipayWap = Yii::getAlias("@vendor/alipayWap");
  1223. require_once($alipayWap . '/wappay/service/AlipayTradeService.php');
  1224. require_once($alipayWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
  1225. $totalFee = $order['realPrice'];
  1226. $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
  1227. $subject = '购买商品';//订单名称,必填
  1228. $total_amount = $totalFee;//付款金额,必填
  1229. $body = '';//商品描述,可空
  1230. $timeout_express = "1m";//超时时间
  1231. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1232. $passBackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&sjId=' . $sjId;//将流水类型、优惠卷传过去
  1233. $passBackParams = urlencode($passBackParams);
  1234. $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
  1235. $payRequestBuilder->setBody($body);
  1236. $payRequestBuilder->setSubject($subject);
  1237. $payRequestBuilder->setOutTradeNo($out_trade_no);
  1238. $payRequestBuilder->setTotalAmount($total_amount);
  1239. $payRequestBuilder->setTimeExpress($timeout_express);
  1240. //在异步通知时将该参数原样返回
  1241. $payRequestBuilder->setPassbackParams($passBackParams);
  1242. //同步通知
  1243. $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$sjId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
  1244. //异步通知
  1245. $notifyUrl = Yii::$app->params['mallHost'] . "/notice/ali-callback";
  1246. $payResponse = new \AlipayTradeService($config);
  1247. $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
  1248. //直接将支付宝的html返回给前端
  1249. echo $result;
  1250. } elseif ($payWay == 2) {
  1251. //余额支付
  1252. util::fail('暂不支持');
  1253. } else {
  1254. util::fail('无效的支付方式');
  1255. }
  1256. }
  1257. //订单评价
  1258. public function actionComment()
  1259. {
  1260. $post = Yii::$app->request->post();
  1261. $id = $post['id'];
  1262. $order = OrderService::getById($id);
  1263. OrderService::valid($order, $this->mainId);
  1264. if ($order['grade'] > 0) {
  1265. util::fail('您已经评过了');
  1266. }
  1267. OrderService::comment($post);
  1268. util::complete('提交成功');
  1269. }
  1270. //订单详情,不需要登陆可以查看,要有盐,给跑腿上查看订单信息用的
  1271. public function actionInfo()
  1272. {
  1273. $get = Yii::$app->request->get();
  1274. $id = $get['id'] ?? 0;
  1275. $salt = $get['salt'] ?? '';
  1276. $detail = OrderClass::getFullInfo($id);
  1277. if (empty($detail)) {
  1278. util::fail('没有找到订单');
  1279. }
  1280. if (empty($detail['salt'])) {
  1281. util::fail('没有找到订单信息');
  1282. }
  1283. if (empty($salt)) {
  1284. util::fail('请求参数错误呢');
  1285. }
  1286. if ($detail['salt'] != $salt) {
  1287. util::fail('不是你的订单');
  1288. }
  1289. util::success($detail);
  1290. }
  1291. //订单详情
  1292. public function actionDetail()
  1293. {
  1294. $id = Yii::$app->request->get('id', 0);
  1295. $detail = OrderClass::getFullInfo($id);
  1296. OrderService::valid($detail, $this->mainId);
  1297. $main = $this->main;
  1298. // 是否须走隔天售后(前端提示)
  1299. $ret = OrderClass::ifShPay($detail, $main, 0);
  1300. $shAddPay = $ret['shAddPay'];
  1301. $shAddPayReason = $ret['shAddPayReason'];
  1302. $detail['shAddPay'] = $shAddPay;
  1303. $detail['shAddPayReason'] = $shAddPayReason;
  1304. util::success($detail);
  1305. }
  1306. /**
  1307. * 订单列表(PC/小程序共用)
  1308. * 支持图1独立筛选项:订单编号、货号、订单类型、配送方式、付款类型、人员关键词、创建时间
  1309. */
  1310. public function actionList()
  1311. {
  1312. $get = Yii::$app->request->get();
  1313. $searchText = $get['searchText'] ?? '';
  1314. $shopId = $this->shopId ?? 0;
  1315. if (empty($shopId)) {
  1316. //没有登录不显示数据
  1317. util::success(['list' => [], 'moreData' => 0, 'shop' => [], 'totalNum' => 0, 'totalPage' => 0]);
  1318. }
  1319. $where = [];
  1320. $where['shopId'] = $shopId;
  1321. if (!empty($get['customId'])) {
  1322. $where['customId'] = $get['customId'];
  1323. }
  1324. if (!empty($get['ids'])) {
  1325. $stringIds = $get['ids'];
  1326. $newIds = explode(',', $stringIds);
  1327. $where['id'] = ['in', $newIds];
  1328. }
  1329. $status = $get['status'] ?? 0;
  1330. if (!empty($status)) {
  1331. $where['status'] = $get['status'];
  1332. }
  1333. $debt = $get['debt'] ?? -1;
  1334. if ($debt > -1) {
  1335. $where['debt'] = $debt;
  1336. }
  1337. if (!empty($get['shopAdminId'])) {
  1338. $where['shopAdminId'] = $get['shopAdminId'];
  1339. }
  1340. // PC 端独立筛选:订单编号 / 货号
  1341. if (!empty($get['orderSn'])) {
  1342. $where['orderSn'] = ['like', trim((string)$get['orderSn'])];
  1343. }
  1344. if (!empty($get['sendNum'])) {
  1345. $where['sendNum'] = trim((string)$get['sendNum']);
  1346. }
  1347. // 订单类型 fromType:门店/商城/微信/美团/饿了么
  1348. if (isset($get['fromType']) && $get['fromType'] !== '' && (int)$get['fromType'] > -1) {
  1349. $where['fromType'] = (int)$get['fromType'];
  1350. }
  1351. // 配送方式 sendType
  1352. if (isset($get['sendType']) && $get['sendType'] !== '' && (int)$get['sendType'] > -1) {
  1353. $where['sendType'] = (int)$get['sendType'];
  1354. }
  1355. // 付款类型:兼容 payWay 或 onlinePay
  1356. if (isset($get['payWay']) && $get['payWay'] !== '' && (int)$get['payWay'] > -1) {
  1357. $where['payWay'] = (int)$get['payWay'];
  1358. }
  1359. if (isset($get['onlinePay']) && $get['onlinePay'] !== '' && (int)$get['onlinePay'] > -1) {
  1360. $where['onlinePay'] = (int)$get['onlinePay'];
  1361. }
  1362. // 下单人/收货人/姓名/手机号:多字段 OR 模糊匹配,先查 id 再并入 where(Base 条件不支持 OR)
  1363. if (!empty($get['keyword'])) {
  1364. $keywordIds = $this->findOrderIdsByKeyword($shopId, trim((string)$get['keyword']));
  1365. $where['id'] = ['in', !empty($keywordIds) ? $keywordIds : [0]];
  1366. }
  1367. // 按搜索词自动识别:纯数字查货号,否则查姓名(小程序兼容)
  1368. if (!empty($searchText)) {
  1369. $this->appendOrderListSearchWhere($where, $searchText);
  1370. }
  1371. if (isset($get['repeat']) && $get['repeat'] > -1) {
  1372. $where['repeat'] = $get['repeat'];
  1373. }
  1374. if (!empty($get['searchTime'])) {
  1375. $startTime = $get['startTime'] ?? '';
  1376. $endTime = $get['endTime'] ?? '';
  1377. $period = dateUtil::formatTime($get['searchTime'], $startTime, $endTime);
  1378. $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
  1379. }
  1380. $list = OrderService::getOrderList($where);
  1381. $list['shop'] = $this->shop->attributes ?? [];
  1382. util::success($list);
  1383. }
  1384. //订单归类 ssh 2019.12.17
  1385. public function actionClassify()
  1386. {
  1387. $post = Yii::$app->request->post();
  1388. $id = $post['id'] ?? 0;
  1389. $order = OrderService::getById($id);
  1390. OrderService::valid($order, $this->mainId);
  1391. $categoryId = $post['categoryId'];
  1392. $usageId = $post['usageId'];
  1393. OrderService::classify($id, $categoryId, $usageId);
  1394. util::complete();
  1395. }
  1396. //更新配送单 ssh 2019.12.17
  1397. public function actionUpdateSheet()
  1398. {
  1399. $post = Yii::$app->request->post();
  1400. $id = $post['id'] ?? 0;
  1401. unset($post['id']);
  1402. $order = OrderService::getById($id);
  1403. OrderService::valid($order, $this->mainId);
  1404. OrderService::updateSheet($order, $post);
  1405. util::complete('提交成功');
  1406. }
  1407. //商家收款与发货 ssh 2019.12.18
  1408. public function actionGathering()
  1409. {
  1410. $post = Yii::$app->request->post();
  1411. $price = isset($post['price']) && is_numeric($post['price']) ? $post['price'] : 0;
  1412. $payWay = isset($post['payWay']) && is_numeric($post['payWay']) ? $post['payWay'] : 0;
  1413. $userId = $post['userId'] ?? 0;
  1414. $userInfo = UserService::getById($userId);
  1415. if (empty($userInfo) || $userInfo['sjId'] != $this->sjId) {
  1416. util::fail('您选择的客户无效');
  1417. }
  1418. if ($price <= 0) {
  1419. util::fail('请输入金额');
  1420. }
  1421. $post['prePrice'] = $price;
  1422. $post['actPrice'] = $price;
  1423. $post['payWay'] = $payWay;
  1424. $post['sourceType'] = 1;
  1425. $post['userId'] = $userId;
  1426. $post['goodsNum'] = 1;
  1427. $post['orderName'] = '商品';
  1428. $shopId = MerchantService::getDefaultShopId($this->sj);
  1429. $post['shopId'] = $shopId;
  1430. $order = OrderService::addOrder($post);
  1431. $id = $order['id'];
  1432. $orderSn = $order['orderSn'];
  1433. //流水类型列表
  1434. $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
  1435. $callbackParams = [];
  1436. switch ($payWay) {
  1437. case 0:
  1438. xhPayToolService::wxPay($callbackParams, $orderSn, $price, $capitalType, 0);
  1439. break;
  1440. case 1:
  1441. xhPayToolService::alipay($callbackParams, $orderSn, $price, $capitalType, 0, []);
  1442. break;
  1443. case 2:
  1444. xhPayToolService::balancePay($callbackParams, $orderSn, $price, $capitalType, 0);
  1445. break;
  1446. default:
  1447. util::fail('无效支付方式');
  1448. }
  1449. util::success($order);
  1450. }
  1451. //免发货管理 ssh 2020.1.6
  1452. public function actionWithoutSend()
  1453. {
  1454. $id = Yii::$app->request->get('id');
  1455. $order = OrderService::getById($id);
  1456. OrderService::valid($order, $this->mainId);
  1457. //配送流程变更
  1458. $currentFlow = OrderSendClass::withoutSend($order);
  1459. util::success(['currentFlow' => $currentFlow]);
  1460. }
  1461. //修改价格 ssh 2020.1.6
  1462. public function actionUpdatePrice()
  1463. {
  1464. $id = Yii::$app->request->get('id');
  1465. $price = Yii::$app->request->get('price', 1);
  1466. $order = OrderService::getById($id);
  1467. OrderService::valid($order, $this->mainId);
  1468. if (isset($order['modPrice']) && $order['modPrice'] == 0) {
  1469. util::fail('已发起支付,不能修改价格');
  1470. }
  1471. OrderService::updateById($id, ['actPrice' => $price]);
  1472. util::complete('修改成功');
  1473. }
  1474. //配送单 ssh 2020.2.29
  1475. public function actionGetDeliverDetail()
  1476. {
  1477. $id = Yii::$app->request->get('id', 0);
  1478. $order = OrderService::getById($id);
  1479. OrderService::valid($order, $this->mainId);
  1480. $reachDate = isset($order['reachDate']) && !empty($order['reachDate']) ? $order['reachDate'] : '';
  1481. $reachPeriodId = $order['reachPeriod'];
  1482. $reachPeriodArr = [0 => '上午', 1 => '下午', 2 => '晚上'];
  1483. $reachPeriod = isset($reachPeriodArr[$reachPeriodId]) ? $reachPeriodArr[$reachPeriodId] : '';
  1484. $bookName = isset($order['bookName']) ? $order['bookName'] : '';
  1485. $bookMobile = isset($order['bookMobile']) ? $order['bookMobile'] : '';
  1486. if (isset($order['anonymity']) && $order['anonymity'] == 1) {
  1487. $bookName = '--';
  1488. $bookMobile = '--';
  1489. }
  1490. $data = [
  1491. 'reachDate' => $reachDate . ' ' . $reachPeriod,
  1492. 'orderSn' => $order['orderSn'],
  1493. 'receiveUserName' => $order['receiveUserName'],
  1494. 'receiveMobile' => $order['receiveMobile'],
  1495. 'fullAddress' => $order['fullAddress'] . "(" . $order['showAddress'] . ")",
  1496. 'cardInfo' => $order['cardInfo'],
  1497. 'bookMobile' => $bookMobile,
  1498. 'bookName' => $bookName,
  1499. 'remark' => $order['remark'],
  1500. 'sendNum' => $order['sendNum'],
  1501. 'telephone' => 18030142050,
  1502. 'printTime' => '',
  1503. 'img' => '',
  1504. ];
  1505. util::success($data);
  1506. }
  1507. //运费计算 lqh 2021.4.12 暂反回固定
  1508. public function actionFreight()
  1509. {
  1510. util::success(['sedCost' => 10]);
  1511. }
  1512. /**
  1513. * 订单列表搜索条件:纯数字按货号精确匹配,否则按客户姓名模糊匹配
  1514. * @param array $where 查询条件(引用传递)
  1515. * @param string $searchText 搜索关键词
  1516. */
  1517. private function appendOrderListSearchWhere(&$where, $searchText)
  1518. {
  1519. $searchText = trim((string)$searchText);
  1520. if ($searchText === '') {
  1521. return;
  1522. }
  1523. if (preg_match('/^\d+$/', $searchText)) {
  1524. $where['sendNum'] = $searchText;
  1525. return;
  1526. }
  1527. $where['customName'] = ['like', $searchText];
  1528. }
  1529. /**
  1530. * 按人员/手机关键词查订单 id(下单人、收货人、客户名、开单人、手机号)
  1531. * @param int $shopId 门店 id
  1532. * @param string $keyword 关键词
  1533. * @return array
  1534. */
  1535. private function findOrderIdsByKeyword($shopId, $keyword)
  1536. {
  1537. if ($keyword === '' || empty($shopId)) {
  1538. return [];
  1539. }
  1540. return (new \yii\db\Query())
  1541. ->select('id')
  1542. ->from(\bizHd\order\models\Order::tableName())
  1543. ->where(['shopId' => $shopId])
  1544. ->andWhere([
  1545. 'or',
  1546. ['like', 'bookName', $keyword],
  1547. ['like', 'receiveUserName', $keyword],
  1548. ['like', 'customName', $keyword],
  1549. ['like', 'shopAdminName', $keyword],
  1550. ['like', 'bookMobile', $keyword],
  1551. ['like', 'receiveMobile', $keyword],
  1552. ])
  1553. ->column();
  1554. }
  1555. /**
  1556. * 链科云打印纸张类型列表
  1557. */
  1558. public function actionCloudPrintPaperTypes()
  1559. {
  1560. util::success(['list' => cloudPrintPaperSpec::listTypes()]);
  1561. }
  1562. /**
  1563. * 解析打印请求中的纸张参数
  1564. */
  1565. protected function parseCloudPrintPaperOptions()
  1566. {
  1567. $get = Yii::$app->request->get();
  1568. $options = [];
  1569. if (!empty($get['paperType'])) {
  1570. $options['paperType'] = $get['paperType'];
  1571. }
  1572. if (!empty($get['paperSize'])) {
  1573. $options['paperSize'] = intval($get['paperSize']);
  1574. }
  1575. return $options;
  1576. }
  1577. /**
  1578. * 链科云打印鲜花配送单
  1579. */
  1580. public function actionCloudPrintDeliverySlip()
  1581. {
  1582. if (!cloudPrintUtil::isEnabled()) {
  1583. util::fail('链科云打印未启用,请配置 .env 中 LIANKENET_*');
  1584. }
  1585. $id = intval(Yii::$app->request->get('id', 0));
  1586. if ($id <= 0) {
  1587. util::fail('订单id不对');
  1588. }
  1589. try {
  1590. deliverySlipPrintUtil::printByOrderId($id, $this->mainId, $this->parseCloudPrintPaperOptions());
  1591. } catch (\Throwable $e) {
  1592. Yii::error('配送单云打印失败: ' . $e->getMessage(), __METHOD__);
  1593. util::fail($e->getMessage());
  1594. }
  1595. util::complete('已提交打印');
  1596. }
  1597. /**
  1598. * 链科云打印节日贺卡(文案暂写死)
  1599. */
  1600. public function actionCloudPrintGreetingCard()
  1601. {
  1602. if (!cloudPrintUtil::isEnabled()) {
  1603. util::fail('链科云打印未启用,请配置 .env 中 LIANKENET_*');
  1604. }
  1605. $id = intval(Yii::$app->request->get('id', 0));
  1606. if ($id <= 0) {
  1607. util::fail('订单id不对');
  1608. }
  1609. try {
  1610. greetingCardPrintUtil::printByOrderId($id, $this->mainId, $this->parseCloudPrintPaperOptions());
  1611. } catch (\Throwable $e) {
  1612. Yii::error('节日贺卡云打印失败: ' . $e->getMessage(), __METHOD__);
  1613. util::fail($e->getMessage());
  1614. }
  1615. util::complete('已提交打印');
  1616. }
  1617. }