| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665 |
- <?php
- namespace hd\controllers;
- use bizHd\hb\classes\HbClass;
- use Yii;
- use biz\shop\classes\ShopExtClass;
- use biz\sj\services\MerchantExtendService;
- use biz\sj\services\MerchantService;
- use bizHd\custom\classes\CustomClass;
- use bizHd\custom\classes\HdClass;
- use bizHd\goods\classes\GoodsClass;
- use bizHd\merchant\services\ShopService;
- use bizHd\order\classes\OrderClass;
- use bizHd\order\classes\OrderForwardClass;
- use bizHd\order\classes\OrderItemClass;
- use bizHd\order\classes\OrderSendClass;
- use hd\models\order\CreateOrderForm;
- use bizHd\express\classes\HdDeliveryOrderClass;
- use bizHd\order\services\OrderService;
- use bizHd\product\classes\ProductClass;
- use bizHd\saas\services\RegionService;
- use bizHd\shop\classes\ShopClass;
- use bizHd\user\services\UserService;
- use bizHd\work\classes\WorkClass;
- use common\components\dict;
- use common\components\dateUtil;
- use common\components\noticeUtil;
- use common\components\orderSn;
- use common\components\payUtil;
- use common\services\xhPayToolService;
- use common\components\util;
- use common\components\stringUtil;
- use bizHd\promote\services\CouponService;
- use common\components\httpUtil;
- use biz\wx\classes\WxMessageClass;
- use common\components\lakala\Lakala;
- use yii\helpers\ArrayHelper;
- class OrderController extends BaseController
- {
- public $guestAccess = ['order-relate', 'fast-pay', 'create-order', 'list', 'info'];
- public function actionDebt()
- {
- $get = Yii::$app->request->get();
- $id = $get['id'] ?? 0;
- $info = OrderClass::getById($id, true);
- if (empty($info)) {
- util::fail('没有找到订单');
- }
- if ($info->mainId != $this->mainId) {
- util::fail('不是你的订单');
- }
- //4秒内不允许重复提交
- util::checkRepeatCommit($id, 4);
- if ($info->status != 1) {
- util::fail('订单已付款或取消');
- }
- $payWay = dict::getDict('payWay', 'debtPay');
- $connection = Yii::$app->db;
- $transaction = $connection->beginTransaction();
- try {
- $actPrice = $info->actPrice ?? 0;
- $info->debtPrice = $actPrice;
- $info->remainDebtPrice = $actPrice;
- $info->debt = 1;
- $info->save();
- OrderClass::payAfter($info, $payWay);
- //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
- if ($info->getGoods == 1 && $info->sendType == 1 && $info->status == 2) {
- $info->status = 4;
- $info->save();
- }
- $transaction->commit();
- //付款成功了,通知发跑腿功能,关键词 hd_pay_after_call_pt,多处要同步修改
- HdDeliveryOrderClass::payAfter($info);
- util::complete('赊账成功');
- } catch (\Exception $exception) {
- $transaction->rollBack();
- Yii::info("赊账失败原因:" . $exception->getMessage());
- util::fail('操作失败');
- }
- }
- //取消订单 ssh 20221231
- public function actionCancel()
- {
- $shopAdmin = $this->shopAdmin;
- //避免重复提交
- $adminId = $this->adminId;
- util::checkRepeatCommit($adminId, 3);
- $get = Yii::$app->request->get();
- $cashier = $get['cashier'] ?? 0;
- //是否强制取消订单 0不要强制 1强制,没有关单成功也要取消
- $forceCancel = $get['forceCancel'] ?? 0;
- $id = $get['id'] ?? 0;
- $order = OrderClass::getById($id, true);
- if ($order->mainId != $this->mainId) {
- util::fail('不是你的订单');
- }
- //如果收银台的订单,取消时要关闭拉卡拉的订单
- if ($cashier == 1) {
- //已取消,不需要再走下面的流程
- if ($order->status == 5) {
- util::complete('已取消');
- }
- $orderSn = $order->orderSn ?? '';
- $shop = $this->shop;
- $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
- $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
- $params = [
- 'appid' => 'OP00002119',
- 'serial_no' => '018b08cfddbd',
- 'merchant_no' => $shop->lklSjNo,
- 'term_no' => $shop->lklScanTermNo,
- 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
- 'lklCertificatePath' => $lklCertificatePath,
- ];
- $laResource = new Lakala($params);
- // 1. 先查询拉卡拉侧订单状态
- $queryResponse = $laResource->query(['orderSn' => $orderSn]);
- //响应CODE为BBS00000,仅表示查到了这笔交易。交易本身的成功与否状态,要查看响应报文中的trade_state这个值
- if (isset($queryResponse['code']) && $queryResponse['code'] == 'BBS00000') {
- $tradeState = $queryResponse['resp_data']['trade_state'] ?? '';
- // 订单已支付,拦截取消操作
- if ($tradeState == 'SUCCESS') {
- util::fail('已付款,不能取消');
- }
- // 根据拉卡拉聚合支付文档(id=116)及实际情况,判断是否为非终态
- // INIT:初始化, CREATE:下单成功, DEAL:交易处理中, USERPAYING:支付中, NOTPAY:未支付
- $pendingStates = ['INIT', 'CREATE', 'DEAL', 'USERPAYING', 'NOTPAY'];
- if (in_array($tradeState, $pendingStates)) {
- $closeParams = ['orderSn' => $orderSn];
- $closeResponse = $laResource->close($closeParams);
- if (!isset($closeResponse['code']) || $closeResponse['code'] != 'BBS00000') {
- $msg = $closeResponse['msg'] ?? '关闭失败';
- noticeUtil::push("拉卡拉聚合支付关单失败:{$orderSn},原因:{$msg} 原单状态:{$tradeState}", '15280215347');
- if ($forceCancel == 0) {
- //返回禁止关单
- util::fail('取消失败,如必要请强制取消');
- }
- }else{
- noticeUtil::push("关单成功,订单号:{$orderSn} 原单状态:{$tradeState}", '15280215347');
- }
- }
- }
- }
- $connection = Yii::$app->db;
- $transaction = $connection->beginTransaction();
- try {
- OrderClass::setExpire($order, true, $shopAdmin);
- $transaction->commit();
- util::complete('已取消');
- } catch (\Exception $exception) {
- $transaction->rollBack();
- Yii::info("取消原因:" . $exception->getMessage());
- util::fail('取消失败');
- }
- }
- //修改订单 ssh 20220926
- public function actionUpdate()
- {
- $post = Yii::$app->request->post();
- $id = $post['id'] ?? 0;
- $order = OrderClass::getById($id, true);
- OrderClass::valid($order, $this->mainId);
- unset($post['id']);
- if ($order->status == 3) {
- util::fail('订单已配送');
- }
- if ($order->status == 4) {
- util::fail('订单已完成');
- }
- if ($order->status == 5) {
- util::fail('订单已取消');
- }
- if ($order->fromType == 4) {
- util::fail('请在美团APP上修改');
- }
- $address = $post['address'] ?? '';
- $floor = $post['floor'] ?? '';
- $post['fullAddress'] = $address . $floor;
- OrderClass::updateById($id, $post);
- $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
- $remark = $post['remark'] ?? '';
- $reachDate = $post['reachDate'] ?? '';
- $reachPeriod = $post['reachPeriod'] ?? '';
- $cardInfo = $post['cardInfo'] ?? '';
- $anonymity = $post['anonymity'] ?? 0;
- $bookName = $post['bookName'] ?? '';
- if (!empty($workList)) {
- foreach ($workList as $work) {
- $work->remark = $remark;
- $work->reachDate = $reachDate;
- $work->reachPeriod = $reachPeriod;
- $work->cardInfo = $cardInfo;
- $work->anonymity = $anonymity;
- $work->bookName = $bookName;
- $work->save();
- }
- }
- $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
- ShopExtClass::orderUpdateRemind($shopExt, $order);
- util::complete();
- }
- //客户欠款的订单 ssh 2021.2.4
- public function actionDebtList()
- {
- $get = Yii::$app->request->get();
- $id = $get['id'] ?? 0;
- $info = CustomClass::getById($id, true);
- CustomClass::valid($info, $this->shopId);
- $where = ['customId' => $id, 'debt' => 1];
- $searchTime = $get['searchTime'] ?? '';
- if (!empty($searchTime)) {
- $startTime = $get['startTime'] ?? '';
- $endTime = $get['endTime'] ?? '';
- $period = dateUtil::formatTime($searchTime, $startTime, $endTime);
- $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
- }
- $allowedPageSizes = [100, 200, 300];
- $pageSize = isset($get['pageSize']) && in_array((int)$get['pageSize'], $allowedPageSizes, true)
- ? (int)$get['pageSize'] : 100;
- $page = max(1, (int)($get['page'] ?? 1));
- $fields = ['id', 'orderSn', 'actPrice', 'addTime', 'remainDebtPrice', 'debtPrice'];
- Yii::$app->request->setQueryParams(array_merge($get, ['page' => $page, 'pageSize' => $pageSize]));
- $result = OrderClass::getList($fields, $where, 'addTime DESC');
- if (!empty($result['list'])) {
- foreach ($result['list'] as $key => $value) {
- $debtPrice = $value['debtPrice'] ?? 0;
- $remainDebtPrice = $value['remainDebtPrice'] ?? 0;
- $hasPayDebt = 0;
- if ($debtPrice > $remainDebtPrice) {
- $hasPayDebt = bcsub($debtPrice, $remainDebtPrice, 2);
- }
- $result['list'][$key]['hasPayDebt'] = floatval($hasPayDebt);
- }
- }
- $result['customInfo'] = $info;
- util::success($result);
- }
- //确认送达 ssh 20250902
- public function actionReach()
- {
- //解决重复提交
- util::checkRepeatCommit($this->adminId, 5);
- $get = Yii::$app->request->get();
- $id = $get['id'] ?? 0;
- $order = OrderClass::getById($id, true);
- if (empty($order)) {
- util::fail('没有找到订单');
- }
- OrderClass::valid($order, $this->mainId);
- if ($order->status == 5) {
- util::fail('订单已取消');
- }
- if ($order->status == 1) {
- util::fail('订单待付款');
- }
- if ($order->status == 2) {
- util::fail('订单未发货');
- }
- if ($order->status == 4) {
- util::fail('订单已经送到了');
- }
- if (!in_array($order->sendStatus, [-1, -4])) {
- util::fail('由跑腿送货,无需确认');
- }
- $order->status = 4;
- $order->save();
- util::complete('操作成功');
- }
- //确认取货
- public function actionFetch()
- {
- $get = Yii::$app->request->get();
- $id = $get['id'] ?? 0;
- //解决重复提交
- util::checkRepeatCommit($id . '_' . $this->adminId, 5);
- $order = OrderClass::getById($id, true);
- if (empty($order)) {
- util::fail('没有找到订单');
- }
- OrderClass::valid($order, $this->mainId);
- if ($order->status == 5) {
- util::fail('订单已取消');
- }
- if ($order->status == 1) {
- util::fail('订单待付款');
- }
- if ($order->status == 4) {
- util::fail('订单已取过了');
- }
- if (in_array($order->sendStatus, [-1, 0, 1, 2, 4, 5])) {
- util::fail('由跑腿送货,无需确认');
- }
- $order->status = 4;
- $order->save();
- util::complete('操作成功');
- }
- //批量确认取货 待发货的自取订单 每次500个
- public function actionBatchFetch()
- {
- $where = ["status" => 2, "sendType" => 1, "shopId" => $this->shopId];
- $orderList = OrderService::getLimitList("id", $where, 500, "id desc");
- $ids = ArrayHelper::getColumn($orderList, "id");
- OrderService::updateByIds($ids, ["status" => 4]);
- util::complete($ids);
- }
- //确认发货
- public function actionSend()
- {
- //解决重复提交
- util::checkRepeatCommit($this->adminId, 5);
- $get = Yii::$app->request->get();
- $id = $get['id'] ?? 0;
- $order = OrderClass::getById($id, true);
- if (empty($order)) {
- util::fail('没有找到订单');
- }
- OrderClass::valid($order, $this->mainId);
- if ($order->status != 2) {
- util::fail('订单不是待发货状态');
- }
- // $workList = WorkClass::getAllByCondition(['orderId' => $id], null, '*', null, true);
- // if (!empty($workList)) {
- // $unComplete = false;
- // foreach ($workList as $work) {
- // if ($work->status != 1) {
- // $unComplete = true;
- // }
- // }
- // if ($unComplete == true) {
- // util::fail('还有制作单没有完成');
- // }
- // }
- $order->status = 3;
- $order->save();
- util::complete('已发货');
- }
- //打印订单 ssh 20220601
- public function actionPrintOrder()
- {
- $get = Yii::$app->request->get();
- $id = isset($get['id']) ? $get['id'] : 0;
- $order = OrderClass::getById($id, true);
- if (empty($order)) {
- util::fail('没有找到订单');
- }
- if ($order->forward == 1) {
- util::fail('红冲订单不能打印');
- }
- OrderClass::valid($order, $this->mainId);
- OrderClass::onlinePrint($order, true);
- util::complete();
- }
- //微信和支付宝付款码支付复查 ssh 20220422
- public function actionCodePayCheck()
- {
- ini_set('date.timezone', 'Asia/Shanghai');
- header("Content-type: text/html; charset=utf-8");
- $get = Yii::$app->request->get();
- $id = isset($get['id']) ? $get['id'] : 0;
- util::checkRepeatCommit($id, 3);
- $order = OrderClass::getById($id, true);
- OrderClass::valid($order, $this->mainId);
- $orderSn = $order->orderSn ?? '';
- $totalFee = $order->mainPay ?? 0;
- if ($order->payStatus == 1) {
- util::success(['returnStatus' => 'SUCCESS']);
- }
- if ($order->status == 5) {
- util::success(['returnStatus' => 'CANCEL']);
- }
- $connection = Yii::$app->db;
- $transaction = $connection->beginTransaction();
- try {
- $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
- $shop = $this->shop;
- $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
- $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
- $params = [
- 'appid' => 'OP00002119',
- 'serial_no' => '018b08cfddbd',
- 'merchant_no' => $shop->lklSjNo,
- 'term_no' => $shop->lklScanTermNo,
- 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
- 'lklCertificatePath' => $lklCertificatePath,
- ];
- $laResource = new Lakala($params);
- $scanParams = ['orderSn' => $orderSn,];
- $response = $laResource->query($scanParams);
- if (isset($response['code']) && $response['code'] == 'BBS00000') {
- if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
- $payWayType = dict::getDict('payWay', 'wxPay');
- $account_type = $response['resp_data']['account_type'] ?? '';
- if ($account_type == 'WECHAT') {
- $payWayType = dict::getDict('payWay', 'wxPay');
- }
- if ($account_type == 'ALIPAY') {
- $payWayType = dict::getDict('payWay', 'alipay');
- }
- $transactionId = $response['resp_data']['trade_no'] ?? '';
- $order->onlinePay = dict::getDict('onlinePay', 'yes');
- $order->save();
- $attach = '';
- payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
- $transaction->commit();
- //解决重复通知
- $cacheKey = 'pay_success_notice_' . $orderSn;
- $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
- if (empty($has)) {
- Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
- //打印小票和语音播报
- $newOrder = OrderClass::getById($id, true);
- OrderClass::onlinePrint($newOrder);
- ShopExtClass::hdGatheringReport($newOrder);
- //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
- if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
- $newOrder->status = 4;
- $newOrder->save();
- }
- HdDeliveryOrderClass::payAfter($newOrder);
- $shopId = $newOrder->shopId ?? 0;
- $shop = ShopClass::getById($shopId, true);
- WxMessageClass::gatheringIncomeInform($shop, $newOrder);
- }
- util::success(['returnStatus' => 'SUCCESS']);
- } else {
- util::complete('未知状态..');
- }
- }
- util::complete('未知状态..');
- } catch (\Exception $e) {
- $transaction->rollBack();
- util::complete('支付失败');
- }
- }
- //微信和支付宝付款码支付复查 ssh 20260716
- public function actionCodePayVerify()
- {
- ini_set('date.timezone', 'Asia/Shanghai');
- header("Content-type: text/html; charset=utf-8");
- $get = Yii::$app->request->get();
- $id = $get['id'] ?? 0;
- util::checkRepeatCommit($id, 3);
- $order = OrderClass::getById($id, true);
- OrderClass::valid($order, $this->mainId);
- $orderSn = $order->orderSn ?? '';
- $totalFee = $order->mainPay ?? 0;
- if ($order->payStatus == 1) {
- util::success(['returnStatus' => 'SUCCESS']);
- }
- if ($order->status == 5) {
- util::success(['returnStatus' => 'CANCEL']);
- }
- $connection = Yii::$app->db;
- $transaction = $connection->beginTransaction();
- try {
- $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
- $shop = $this->shop;
- $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
- $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
- $params = [
- 'appid' => 'OP00002119',
- 'serial_no' => '018b08cfddbd',
- 'merchant_no' => $shop->lklSjNo,
- 'term_no' => $shop->lklScanTermNo,
- 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
- 'lklCertificatePath' => $lklCertificatePath,
- ];
- $laResource = new Lakala($params);
- $scanParams = ['orderSn' => $orderSn,];
- $response = $laResource->query($scanParams);
- if (isset($response['code']) && $response['code'] == 'BBS00000') {
- if (isset($response['resp_data']['trade_state']) && $response['resp_data']['trade_state'] == 'SUCCESS') {
- $payWayType = dict::getDict('payWay', 'wxPay');
- $account_type = $response['resp_data']['account_type'] ?? '';
- if ($account_type == 'WECHAT') {
- $payWayType = dict::getDict('payWay', 'wxPay');
- }
- if ($account_type == 'ALIPAY') {
- $payWayType = dict::getDict('payWay', 'alipay');
- }
- $transactionId = $response['resp_data']['trade_no'] ?? '';
- $order->onlinePay = dict::getDict('onlinePay', 'yes');
- $order->save();
- $attach = '';
- payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
- $transaction->commit();
- //解决重复通知
- $cacheKey = 'pay_success_notice_' . $orderSn;
- $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
- if (empty($has)) {
- Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
- //打印小票和语音播报
- $newOrder = OrderClass::getById($id, true);
- OrderClass::onlinePrint($newOrder);
- ShopExtClass::hdGatheringReport($newOrder);
- //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
- if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
- $newOrder->status = 4;
- $newOrder->save();
- }
- HdDeliveryOrderClass::payAfter($newOrder);
- $shopId = $newOrder->shopId ?? 0;
- $shop = ShopClass::getById($shopId, true);
- WxMessageClass::gatheringIncomeInform($shop, $newOrder);
- }
- util::success(['returnStatus' => 'SUCCESS']);
- } else {
- util::success(['returnStatus' => 'PENDING'], '等待支付中...');
- }
- }
- util::success(['returnStatus' => 'PENDING'], '等待支付中...');
- } catch (\Exception $e) {
- $transaction->rollBack();
- util::complete('支付失败');
- }
- }
- /**
- * 微信和支付宝付款码支付
- * 职责:处理商户扫描客户付款码(被扫支付)的请求,调用拉卡拉支付接口并更新本地订单状态(零售端)
- * 入参:GET 传参 id (订单ID), authCode (付款码), version (版本号)
- * 返回:JSON 格式的支付结果(SUCCESS/FAILURE)
- * 副作用:更新订单支付状态、支付方式,记录支付日志,触发云打印、跑腿呼叫及语音播报
- * 关键边界:
- * 1. 验证订单有效性与待付款状态
- * 2. 校验付款码格式(微信/支付宝)
- * 3. 优化:将拉卡拉外部网络请求移出数据库事务,避免因网络延迟长时间占用数据库连接和行锁
- */
- public function actionCodePay()
- {
- ini_set('date.timezone', 'Asia/Shanghai');
- header("Content-type: text/html; charset=utf-8");
- $get = Yii::$app->request->get();
- $id = isset($get['id']) ? $get['id'] : 0;
- util::checkRepeatCommit($id, 3);
- $version = $get['version'] ?? 0;
- $order = OrderClass::getById($id, true);
- OrderClass::valid($order, $this->mainId);
- if ($order->status == OrderClass::ORDER_STATUS_CANCEL) {
- $msg = '订单已取消';
- util::success(['returnStatus' => 'FAILURE'], $msg);
- }
- if ($order->status != OrderClass::ORDER_STATUS_UN_PAY) {
- $msg = '订单不是待付款状态';
- util::success(['returnStatus' => 'FAILURE'], $msg);
- }
- $shop = $this->shop;
- $sj = $shop->merchantName;
- $shopName = $shop->shopName;
- $name = $shopName == '首店' ? $sj : $sj . '-' . $shopName;
- $authCode = (string)$get['authCode'] ?? '';
- if ($version > 0) {
- if (empty($authCode)) {
- $msg = '没有扫到付款码';
- $remind = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
- noticeUtil::push($remind . ' 编号005', '15280215347');
- util::success(['returnStatus' => 'FAILURE'], $msg);
- }
- //微信文档说明 https://pay.weixin.qq.com/doc/v2/merchant/4011936234
- $wxPattern = '/^(10|11|12|13|14|15)\d{16}$/';
- //支付宝文档说明 https://opendocs.alipay.com/open/194/106039/
- $aliPattern = '/^(25|26|27|28|29|30)\d{14,22}$/';
- if (!preg_match($wxPattern, $authCode) && !preg_match($aliPattern, $authCode)) {
- $msg = '付款码错误,请使用微信或支付宝付款码';
- $remind = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
- //noticeUtil::push($remind . ' 编号009', '15280215347');
- util::success(['returnStatus' => 'FAILURE'], $msg);
- }
- } else {
- if (empty($authCode)) {
- util::fail('没有获取到支付码');
- }
- }
- $orderSn = $order->orderSn ?? '';
- $lsCodePayErrorKey = 'ls_code_pay_error_' . $id;
- $hasFailPay = Yii::$app->redis->executeCommand('GET', [$lsCodePayErrorKey]);
- //前面有付失败过,要重新生成单号
- if (!empty($hasFailPay)) {
- $oldOrderSn = $order->orderSn;
- $orderSn = orderSn::getOrderSn();
- $order->orderSn = $orderSn;
- $order->save();
- OrderItemClass::updateByCondition(['orderSn' => $oldOrderSn], ['orderSn' => $orderSn]);
- }
- $subject = '购买花材 ' . $orderSn;
- $totalFee = $order->mainPay ?? 0;
- $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
- try {
- $merchantPrivateKeyPath = Yii::getAlias("@vendor/lakala") . '/production/api_private_key.pem';
- $lklCertificatePath = Yii::getAlias("@vendor/lakala") . '/production/lkl-apigw-v1.cer';
- $params = [
- 'appid' => 'OP00002119',
- 'serial_no' => '018b08cfddbd',
- 'merchant_no' => $shop->lklSjNo,
- 'term_no' => $shop->lklScanTermNo,
- 'merchantPrivateKeyPath' => $merchantPrivateKeyPath,
- 'lklCertificatePath' => $lklCertificatePath,
- ];
- $laResource = new Lakala($params);
- $notifyUrl = Yii::$app->params['hdHost'] . "/notice/pay-callback";
- $scanParams = [
- 'orderSn' => $orderSn,
- 'amount' => $totalFee,
- 'capitalType' => $capitalType,
- 'notifyUrl' => $notifyUrl,
- 'subject' => $subject,
- 'authCode' => $authCode,
- ];
- // 复杂分支/关键逻辑:在调用外部支付接口前不开启事务,防止网络延迟卡死数据库连接
- $response = $laResource->scanPay($scanParams);
- if (isset($response['code']) && $response['code'] == 'BBS00000') {
- // 复杂分支/关键逻辑:支付成功后,开启数据库事务,确保本地订单状态更新的原子性
- $connection = Yii::$app->db;
- $transaction = $connection->beginTransaction();
- try {
- $account_type = $response['resp_data']['account_type'] ?? '';
- $payWayType = dict::getDict('payWay', 'wxPay');
- if ($account_type == 'WECHAT') {
- $payWayType = dict::getDict('payWay', 'wxPay');
- }
- if ($account_type == 'ALIPAY') {
- $payWayType = dict::getDict('payWay', 'alipay');
- }
- $order->payWay = $payWayType;
- $transactionId = $response['resp_data']['trade_no'] ?? '';
- $order->onlinePay = dict::getDict('onlinePay', 'yes');
- $order->save();
- $attach = '';
- payUtil::thirdPay($payWayType, $capitalType, $orderSn, $totalFee, $attach, $transactionId);
- $transaction->commit();
- } catch (\Exception $e) {
- $transaction->rollBack();
- throw $e;
- }
- //解决重复通知
- $cacheKey = 'hd_shop_order_pay_' . $orderSn;
- $has = Yii::$app->redis->executeCommand('GET', [$cacheKey]);
- if (empty($has)) {
- Yii::$app->redis->executeCommand('SETEX', [$cacheKey, 300, 'has']);
- $newOrder = OrderClass::getById($id, true);
- //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
- if ($newOrder->getGoods == 1 && $newOrder->sendType == 1 && $newOrder->status == 2) {
- $newOrder->status = 4;
- $newOrder->save();
- }
- //打印小票
- OrderClass::onlinePrint($newOrder);
- HdDeliveryOrderClass::payAfter($newOrder);
- //语音播报
- ShopExtClass::hdGatheringReport($newOrder);
- $shopId = $newOrder->shopId ?? 0;
- $shop = ShopClass::getById($shopId, true);
- WxMessageClass::gatheringIncomeInform($shop, $newOrder);
- }
- util::success(['returnStatus' => 'SUCCESS']);
- } else {
- //标记有没付成功的次数,原因有可能是余额不足等
- Yii::$app->redis->executeCommand('SETEX', [$lsCodePayErrorKey, 1200, 'hasFail']);
- $msg = $response['msg'] ?? '';
- $retCode = $response['code'] ?? '';
- $fullMsg = $msg . "(零售端付款码:{$authCode})" . '(' . $name . ')';
- if ($retCode == 'BBS10000' || $retCode == 'BBS11105') {
- $shopId = $order->shopId;
- ShopExtClass::remindInputPassword($shopId);
- }
- //noticeUtil::push($fullMsg . ' ' . $retCode . ' 编号008', '15280215347');
- util::success(['returnStatus' => 'FAILURE', 'returnCode' => $retCode], $msg);
- }
- } catch (\Exception $e) {
- Yii::error("零售端支付失败原因:" . $e->getMessage());
- util::fail('支付失败');
- }
- }
- //开单操作 ssh 20220316
- public function actionCreateOrder()
- {
- $post = Yii::$app->request->post();
- $post['sjId'] = $this->sjId;
- $post['shopId'] = $this->shopId;
- $post['mainId'] = $this->mainId ?? 0;
- $shop = $this->shop;
- if ($shop->memberLevelSet == 0) {
- //util::fail('请先设置会员等级');
- }
- $now = time();
- $orderValidTime = 600;
- $expireTime = $now + $orderValidTime;
- $post['deadline'] = $expireTime;
- $post['staffId'] = $this->shopAdminId ?? 0;
- $post['staffName'] = $this->shopAdmin->name ?? '';
- $post['flowerNum'] = isset($post['flowerNum']) && $post['flowerNum'] > 0 ? $post['flowerNum'] : 0;
- $version = $post['version'] ?? 0; //验证已移至 CreateOrderForm
- if ($version < 3) {
- util::fail('请升级版本,或用小程序');
- }
- //默认情况开单员工和收款员工是同个人
- $staffId = $this->shopAdminId ?? 0;
- $staffName = $this->shopAdmin->name ?? '';
- if (empty($post['shopAdminId'])) {
- $post['shopAdminId'] = $staffId;
- $post['shopAdminName'] = $staffName;
- }
- if (empty($post['getStaffId'])) {
- $post['getStaffId'] = $staffId;
- $post['getStaffName'] = $this->shopAdmin->name ?? '';
- }
- $groupId = !empty($post['groupId']) ? $post['groupId'] : 0;
- $post['fromType'] = $post['fromType'] ?? 1;
- if ($post['fromType'] == dict::getDict('fromType', 'friend')) {
- if (empty($post['bookName'])) {
- util::fail('请填写订花人姓名');
- }
- }
- $customId = $post['customId'] ?? 0;
- $custom = CustomClass::getById($customId, true);
- if (empty($custom)) {
- util::fail('没有找到客户哦');
- }
- $hdId = $custom->hdId ?? 0;
- $hd = HdClass::getById($hdId, true);
- if (empty($hd)) {
- util::fail('客户对应的花店信息缺失,编号869');
- }
- $hdName = $hd->name ?? '';
- $post['hdId'] = $hdId;
- $post['hdName'] = $hdName;
- $customName = $custom->name ?? '';
- $post['customName'] = $customName;
- $post['customNamePy'] = stringUtil::py($customName);
- if (!empty($post['receiveMobile'])) {
- if (!stringUtil::isMobile($post['receiveMobile'])) {
- util::fail('请填写正确的收花人手机号');
- }
- }
- if (!empty($post['bookMobile'])) {
- if (!stringUtil::isMobile($post['bookMobile'])) {
- util::fail('请填写正确的订花人手机号');
- }
- }
- $hasPay = $post['hasPay'] ?? dict::getDict('hasPay', 'unPay');
- $post['sendType'] = $post['sendType'] ?? 1;
- $forward = $post['forward'] ?? 0;
- if ($forward == 1) {
- if ($hasPay != 1) {
- util::fail('红冲订单只能走线下转账');
- }
- $historyDate = $post['historyDate'] ?? '';
- if (!empty($historyDate)) {
- if ($historyDate != date("Y-m-d")) {
- util::fail('红冲订单不能修改账单日期,只能今天');
- }
- }
- }
- $productJson = $post['product'] ?? '';
- $productList = [];
- if (!empty($productJson)) {
- $productList = json_decode($productJson, true);
- }
- if (empty($productList) && empty($groupId)) {
- //商家手机上开单并生成制作单
- if (!empty($post['unitGoodsPrice'])) {
- util::fail('此功能停用,有需要请联系管理员');
- $unitGoodsPrice = $post['unitGoodsPrice'];
- if (!is_numeric($unitGoodsPrice)) {
- util::fail('请输入正确的单价');
- }
- $productList = GoodsClass::orderCreateGoods($post);
- }
- }
- //直接收款
- $zjGathering = $post['zjGathering'] ?? 0;
- if ($zjGathering == 1) {
- $lsGoodsPrice = $post['lsGoodsPrice'] ?? 0;
- if (!is_numeric($lsGoodsPrice) || $lsGoodsPrice <= 0) {
- util::fail('请填写价格');
- }
- //直接收款不需要打印小票
- $post['needPrint'] = dict::getDict('needPrint', 'noNeed');
- $shopId = $this->shopId;
- $ext = ShopExtClass::getByCondition(['shopId' => $shopId], true);
- $zjGatheringItem = !empty($ext) ? $ext->zjGatheringItem : 0;
- if (empty($zjGatheringItem)) {
- util::fail('请设置直接收款的商品');
- }
- $zjGatheringItemInfo = ProductClass::getById($zjGatheringItem, true);
- if (empty($zjGatheringItemInfo)) {
- util::fail('请设置直接收款的商品哈');
- }
- $productList = [['productId' => $zjGatheringItem, 'unitType' => 0, 'num' => 1, 'property' => '1', 'unitPrice' => $lsGoodsPrice]];
- }
- $callErrand = $post['callErrand'] ?? 0;
- if ($callErrand == 1) {
- $shopId = $this->shopId;
- $shopExt = ShopExtClass::getByCondition(['shopId' => $shopId], true);
- if (!empty($shopExt) && $shopExt->orderFlow == 0) {
- util::fail('下单后要变待发货,才能直接发跑腿');
- }
- }
- $connection = Yii::$app->db;
- $transaction = $connection->beginTransaction();
- try {
- $post['product'] = $productList;
- $reduceStock = $post['reduceStock'] ?? 0;
- if ($reduceStock == 1) {
- //如果扣除库,则走另外一条路
- $return = OrderClass::reduceMyStock($post, $this->shop, $custom);
- $transaction->commit();
- util::success($return);
- }
- //解决开单提交订单时,别人修改价格,造成提交价格不是真实卖价问题!!
- $dealPrice = $post['dealPrice'] ?? 0;
- //解决重复提交
- util::checkRepeatCommit($this->adminId . '_' . $dealPrice, 3);
- $totalNum = 0;
- if ($dealPrice == 0) {
- $productIds = [];
- $hsIds = [];
- foreach ($productList as $pv) {
- $property = $pv['property'] ?? 0;
- $puId = $pv['productId'] ?? 0;
- if ($property == 0) {
- $hsIds[] = $puId;
- } else {
- $productIds[] = $puId;
- }
- }
- $itemInfo = [];
- if (!empty($productIds)) {
- $itemInfo = ProductClass::getByIds($productIds, null, 'id');
- }
- $hsInfo = [];
- if (!empty($hsIds)) {
- $hsInfo = GoodsClass::getByIds($hsIds, null, 'id');
- }
- $diff = [];
- $priceMap = \bizGhs\custom\classes\CustomClass::$levelPriceKeyMap;
- $addPriceMap = \bizGhs\custom\classes\CustomClass::$levelAddPriceKeyMap;
- $level = 0;
- foreach ($productList as $currentProduct) {
- $property = $currentProduct['property'] ?? 0;
- $currentPrice = $currentProduct['unitPrice'] ?? 0;
- $currentId = $currentProduct['productId'] ?? 0;
- if ($property == 1) {
- $systemInfo = $itemInfo[$currentId] ?? [];
- if (!empty($systemInfo)) {
- $name = $systemInfo['name'] ?? '';
- $systemPrice = \bizGhs\product\classes\ProductClass::getFinalPrice($systemInfo, $level, $priceMap, $addPriceMap);
- if (floatval($currentPrice) != floatval($systemPrice)) {
- $diff[] = [
- 'name' => $name,
- 'price' => $systemPrice,
- 'kdPrice' => $currentPrice,
- ];
- }
- }
- } else {
- $systemInfo = $hsInfo[$currentId] ?? [];
- if (!empty($systemInfo)) {
- $params = [];
- $name = $systemInfo['name'] ?? '';
- $hsData = GoodsClass::getFinalPrice($systemInfo, $shop, $custom, $params);
- $systemPrice = $hsData['price'] ?? 0;
- if ($systemInfo['priceType'] == 1) {
- if (floatval($currentPrice) != floatval($systemPrice)) {
- $diff[] = [
- 'name' => $name,
- 'price' => $systemPrice,
- 'kdPrice' => $currentPrice,
- ];
- }
- }
- }
- }
- $num = $currentProduct['num'];
- $totalNum = bcadd($totalNum, $num);
- }
- if (!empty($diff)) {
- util::success(['diff' => $diff, 'respondType' => 'priceError']);
- }
- }
- //红包使用,多有处,关键词 use_hb_action
- $hbId = $post['hbId'] ?? 0;
- $hb = null;
- if ($hbId > 0) { // 不使用 $hbId =! 0,因为要用负数来表示红包已取消
- $hb = HbClass::getById($hbId, true);
- if (!empty($hb)) {
- if ($hb->customId != $customId) {
- util::fail('不是这个客户的红包');
- }
- if ($hb->amount != $post['hbAmount']) {
- util::fail('红包错误'); //红包数据可能被串改
- }
- if ($hb->status == 1) {
- util::fail('红包已使用');
- }
- if ($hb->status == -1) {
- util::fail('红包已作废');
- }
- if ($hb->endTime < time()) {
- $hb->status = -1;
- $hb->save();
- util::fail('红包已失效');
- }
- if ($hb->beginTime > time()) {
- util::fail('红包可使用期未到');
- }
- if ($this->shop->rechargeWeal == 3) {
- // 判断支付方式是否是余额支付
- if ($hasPay != dict::getDict('hasPay', 'balance')) {
- util::fail('用红包要用余额支付');
- } else {
- if ($custom->balance < $post['modifyPrice']) {
- util::fail('用红包要用余额支付(您的余额不足)');
- }
- }
- }
- } else {
- Yii::error('没有找到红包,hbId: ', $hbId . ' ' . __METHOD__);
- util::fail('红包无效');
- }
- }
- $post['bigNum'] = $totalNum;
- //多处调用这个方法,注意同步修改,搜索关键词 createHdNewOrder
- $return = OrderService::createHdOrder($post, $custom, $hasPay);
- if (!empty($hb)) {
- $hb->status = 1;
- $hb->orderId = $return->id;
- $hb->save();
- }
- $staff = $this->shopAdmin;
- //售后开付款单,库存要变化,关系要建立,多处需要同步修改 sh_pay_change ssh
- OrderClass::shPayChange($return, $shop, $staff);
- //打印小票和语音播报等使用
- $id = $return->id ?? 0;
- $order = OrderClass::getById($id, true);
- //如果需要生成制作单
- $needWork = $post['needWork'] ?? 0;
- if ($needWork == 1) {
- $main = $this->main;
- WorkClass::needWork($order, $main);
- $has = WorkClass::getByCondition(['orderId' => $id], true);
- if (!empty($has)) {
- $return->hasWork = 1;
- $return->save();
- }
- }
- //到店自取订单,并且是待取货状态,则自动完成取货,多处要同步修改,关键词 reach_shop_fetch_goods
- if ($order->getGoods == 1 && $order->sendType == 1 && $order->status == 2) {
- $order->status = 4;
- $order->save();
- }
- $transaction->commit();
- if ($order->fromType == 3 || $order->fromType == 4) {
- //除了客服号下单和美团下单,其它情况允许打小票
- } else {
- //前台打小票
- OrderClass::onlinePrint($order);
- }
- //订单发跑腿流程
- HdDeliveryOrderClass::prepareAskData($post, $order);
- //前台提示收款多少钱
- ShopExtClass::hdGatheringReport($order);
- //前台提醒出示付款码
- if (isset($order->status) && $order->status == 1) {
- if (isset($post['isCashier']) && $post['isCashier'] == 1) {
- ShopExtClass::pleasePayReport($order);
- }
- }
- $shopId = $order->shopId ?? 0;
- $shop = ShopClass::getById($shopId, true);
- WxMessageClass::gatheringIncomeInform($shop, $order);
- if ($needWork == 1) {
- //新制作单提示
- $shopExt = ShopExtClass::getByCondition(['shopId' => $this->shopId], true);
- ShopExtClass::newWorkRemind($shopExt, $order);
- }
- util::success($return);
- } catch (\Exception $e) {
- $transaction->rollBack();
- Yii::error("下单失败原因:" . $e->getMessage());
- util::fail('下单失败');
- }
- }
- //下单要用到的相关信息 ssh 2019.12.6
- public function actionOrderRelate()
- {
- $regionTree = RegionService::tree();
- $shop = $this->shop->attributes;
- $freight = MerchantExtendService::getFreight($this->sjExtend);
- $mapKey = 'OFWBZ-2NTHP-EHNDD-LKWQY-GANM7-PXBJH';
- $out = ['freight' => $freight, 'shop' => $shop, 'region' => $regionTree, 'thirdMapKey' => $mapKey, 'merchant' => $shop];
- util::success($out);
- }
- //余额支付 ssh 2019.12.6
- public function actionBalancePay()
- {
- $post = Yii::$app->request->post();
- $orderSn = $post['orderSn'] ?? 0;
- $payPassword = $post['payPassword'] ?? 0;
- $couponId = $post['couponId'] ?? 0;
- $order = OrderService::getByOrderSn($orderSn);
- $userId = $this->adminId;
- $user = UserService::getUserInfo($userId);
- //验证支付密码是否正确
- UserService::validPayPassword($payPassword, $user);
- //支付前验证订单有效性
- OrderService::checkBeforePay($order);
- $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
- $totalFee = $order['prePrice'];
- $sourceType = 0;
- $discountData = OrderService::getDiscountPrice(['price' => $totalFee, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
- $actPrice = $discountData['price'];
- $callbackParams = [];
- $respond = xhPayToolService::balancePay($callbackParams, $orderSn, $actPrice, $capitalType, $couponId);
- $balance = $respond['balance'] ?? 0;
- util::success(['discountAmount' => $discountData['discountAmount'], 'discountType' => $discountData['discountType'], 'balance' => $balance]);
- }
- //获取商城下单要用的微信支付和小程序支付参数 ssh 2019.21.3
- public function actionWxPay()
- {
- ini_set('date.timezone', 'Asia/Shanghai');
- $post = Yii::$app->request->post();
- $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
- $orderSn = isset($post['orderSn']) ? $post['orderSn'] : 0;
- $order = OrderService::getByOrderSn($orderSn);
- $orderId = $order['id'];
- //验证优惠券是否还有效
- if (!empty($couponId)) {
- CouponService::checkBeforeUse($couponId, $order['prePrice'], $order['userId']);
- }
- //支付前验证订单有效性
- OrderService::checkBeforePay($order);
- $name = isset($order['orderName']) && !empty($order['orderName']) ? $order['orderName'] : '购买商品';
- $totalFee = $order['realPrice'];
- //小程序使用miniOpenId
- if (httpUtil::isMiniProgram()) {
- $openId = $this->user['miniOpenId'];
- } else {
- $openId = $this->user['openId'];
- }
- $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
- //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
- $wxPayType = 0;
- if (httpUtil::isMiniProgram()) {
- $wxPayType = 1;
- }
- $attach = "couponId=" . $couponId . "&capitalType=" . $capitalType . '&wxPayType=' . $wxPayType;
- //订单30分钟后过期
- $now = time();
- $expireTime = $now + 1800;
- $wx = Yii::getAlias("@vendor/weixin");
- require_once($wx . '/lib/WxPay.Api.php');
- require_once($wx . '/example/WxPay.JsApiPay.php');
- $input = new \WxPayUnifiedOrder();
- $input->SetBody($name);
- $input->SetOut_trade_no($orderSn);
- $input->SetTotal_fee($totalFee * 100);
- $input->SetTime_start(date("YmdHis", $now));
- $input->SetAttach($attach);//将流水类型、代金劵等传给微信再回传
- $input->SetTime_expire(date("YmdHis", $expireTime));
- $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
- $input->SetTrade_type("JSAPI");
- //花卉宝代为申请的微信支付
- $merchantExtend = $this->sjExtend->attributes;
- if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
- $input->SetSub_openid($openId);
- } else {
- $input->SetOpenid($openId);
- }
- //小程序使用miniAppId
- if (httpUtil::isMiniProgram()) {
- $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
- }
- $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
- $tools = new \JsApiPay();
- $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
- $newParams = json_decode($jsApiParameters, true);
- //已请求微信不能修改价格
- $updateData = [];
- $updateData['modPrice'] = 0;
- if (empty($order['deadline'])) {
- $updateData['deadline'] = $expireTime;
- }
- OrderService::updateById($orderId, $updateData);
- util::success($newParams);
- }
- //快捷付款订单
- public function actionFastPay()
- {
- ini_set('date.timezone', 'Asia/Shanghai');
- $post = Yii::$app->request->post();
- $payWay = isset($post['payWay']) ? $post['payWay'] : 0;
- $shopId = !empty($this->shopId) ? $this->shopId : ShopService::getDefaultShopId($this->sj);
- //验证门店是否有效
- $shopInfo = ShopService::getById($shopId);
- ShopService::valid($shopInfo, $this->sjId);
- $post['shopId'] = $shopId;
- //默认门店订单
- $store = isset($post['store']) ? $post['store'] : 1;
- $post['store'] = $store;
- //来源 0微信 1支付宝 2小程序 3朋友圈 4美团
- $sourceType = $this->isWx ? 0 : 1;
- if (httpUtil::isMiniProgram()) {
- $sourceType = 2;
- }
- $sourceType = isset($post['sourceType']) ? $post['sourceType'] : 0;
- //兼容旧系统sourceType=3表示朋友圈来源
- $fromType = $sourceType == 3 ? 2 : 0;
- $fromType = isset($post['fromType']) && !empty($post['fromType']) ? $post['fromType'] : $fromType;
- $post['userId'] = $this->adminId;
- $custom = $this->custom;
- $post['bookName'] = $custom['userName'] ?? '';
- $bookMobile = isset($post['bookMobile']) && !empty($post['bookMobile']) && stringUtil::isMobile($post['bookMobile']) ? $post['bookMobile'] : '';
- $bookMobile = empty($bookMobile) && isset($custom['mobile']) && !empty($custom['mobile']) ? $custom['mobile'] : $bookMobile;
- $post['bookMobile'] = $bookMobile;
- $prePrice = round($post['prePrice'], 2);
- $couponId = isset($post['couponId']) ? $post['couponId'] : 0;
- $discountData = OrderService::getDiscountPrice(['price' => $prePrice, 'sourceType' => $sourceType, 'couponId' => $couponId, 'userId' => $this->adminId]);
- $actPrice = $discountData['price'];
- $post['discountType'] = $discountData['discountType'];
- $post['discountAmount'] = $discountData['discountAmount'];
- $post['actPrice'] = $actPrice;
- $post['realPrice'] = $actPrice;
- $post['payStyle'] = 0;
- $post['sjId'] = $this->sjId;
- $now = time();
- $expireTime = $now + 300;//订单5分钟后过期
- $post['createTime'] = date("Y-m-d H:i:s", $now);
- $post['deadline'] = $expireTime;
- if ($actPrice <= 0) {
- util::fail('请填写正确的金额');
- }
- //微信支付订单提交不能修改价格
- $post['modPrice'] = $this->isWx ? 0 : 1;
- $post['sourceType'] = $sourceType;
- $post['goodsNum'] = 1;
- $post['fromType'] = $fromType;
- $order = OrderService::addOrder($post);
- $orderId = $order['id'];
- $orderSn = $order['orderSn'];
- $sjId = $this->sjId;
- if ($payWay == 0) {
- $orderId = $order['id'];
- $name = '购买商品';
- $totalFee = $actPrice;
- $user = UserService::getById($this->adminId);
- $openId = isset($user['openId']) ? $user['openId'] : 0;
- if (httpUtil::isMiniProgram()) {
- //小程序使用miniOpenId
- $openId = $user['miniOpenId'];
- }
- if (empty($openId)) {
- util::fail('没有找到客户的openId');
- }
- $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
- //流水类型、优惠卷、微信支付(h5还是小程序支付)类型 带到回调
- $wxPayType = 0;
- if (httpUtil::isMiniProgram()) {
- $wxPayType = 1;
- }
- $attach = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&wxPayType=' . $wxPayType;
- $wx = Yii::getAlias("@vendor/weixin");
- require_once($wx . '/lib/WxPay.Api.php');
- require_once($wx . '/example/WxPay.JsApiPay.php');
- $input = new \WxPayUnifiedOrder();
- $input->SetBody($name);
- $input->SetOut_trade_no($orderSn);
- $input->SetTotal_fee($totalFee * 100);
- $input->SetTime_start(date("YmdHis", $now));
- $input->SetAttach($attach);
- //设置订单有效期5分钟
- $input->SetTime_expire(date("YmdHis", $expireTime));
- $input->SetNotify_url(Yii::$app->params['hdHost'] . '/notice/wx-callback/');
- $input->SetTrade_type("JSAPI");
- //花卉宝代为申请的微信支付
- $merchantExtend = $this->sjExtend->attributes;
- if (isset($merchantExtend['wxPayApply']) && $merchantExtend['wxPayApply'] == 1) {
- $input->SetSub_openid($openId);
- } else {
- $input->SetOpenid($openId);
- }
- //小程序使用miniAppId
- if (httpUtil::isMiniProgram()) {
- $merchantExtend['wxAppId'] = $merchantExtend['miniAppId'];
- }
- Yii::info('支付发起使用小程序信息' . json_encode($merchantExtend));
- $wxOrder = \WxPayApi::unifiedOrder($input, 6, $merchantExtend);
- $tools = new \JsApiPay();
- $jsApiParameters = $tools->GetJsApiParameters($wxOrder, $merchantExtend);
- $newParams = json_decode($jsApiParameters, true);
- $newParams['orderId'] = $orderId;
- util::success($newParams);
- } elseif ($payWay == 1) {
- $extend = MerchantExtendService::getBySjId($sjId);
- if (isset($extend['alipayInit']) == false || $extend['alipayInit'] == 0) {
- util::fail('支付宝付款即将开通...');
- }
- $config = [
- //应用ID,您的APPID。
- 'app_id' => $extend['alipayPId'],
- //商户私钥,您的原始格式RSA私钥
- 'merchant_private_key' => $extend['alipayKey'],
- //异步通知地址
- 'notify_url' => Yii::$app->params['hdHost'] . "/notice/ali-callback",
- //同步跳转
- 'return_url' => "",
- //编码格式
- 'charset' => "UTF-8",
- //签名方式
- 'sign_type' => "RSA2",
- //支付宝网关
- 'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
- //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
- 'alipay_public_key' => $extend['alipayPublicKey'],
- ];
- Yii::info(json_encode($config) . ' aplipay config');
- $alipayWap = Yii::getAlias("@vendor/alipayWap");
- require_once($alipayWap . '/wappay/service/AlipayTradeService.php');
- require_once($alipayWap . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php');
- $totalFee = $order['realPrice'];
- $out_trade_no = $orderSn;//商户订单号,商户网站订单系统中唯一订单号,必填
- $subject = '购买商品';//订单名称,必填
- $total_amount = $totalFee;//付款金额,必填
- $body = '';//商品描述,可空
- $timeout_express = "1m";//超时时间
- $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
- $passBackParams = 'capitalType=' . $capitalType . '&couponId=' . $couponId . '&sjId=' . $sjId;//将流水类型、优惠卷传过去
- $passBackParams = urlencode($passBackParams);
- $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
- $payRequestBuilder->setBody($body);
- $payRequestBuilder->setSubject($subject);
- $payRequestBuilder->setOutTradeNo($out_trade_no);
- $payRequestBuilder->setTotalAmount($total_amount);
- $payRequestBuilder->setTimeExpress($timeout_express);
- //在异步通知时将该参数原样返回
- $payRequestBuilder->setPassbackParams($passBackParams);
- //同步通知
- $returnUrl = Yii::$app->params['mallDomain'] . "/#/pages/callback/success?account={$sjId}&shopId={$shopId}&orderSn={$orderSn}&totalPrice={$totalFee}&pageStatus=3&payDiscountPrice=0&payDiscountType=0";
- //异步通知
- $notifyUrl = Yii::$app->params['mallHost'] . "/notice/ali-callback";
- $payResponse = new \AlipayTradeService($config);
- $result = $payResponse->wapPay($payRequestBuilder, $returnUrl, $notifyUrl);
- //直接将支付宝的html返回给前端
- echo $result;
- } elseif ($payWay == 2) {
- //余额支付
- util::fail('暂不支持');
- } else {
- util::fail('无效的支付方式');
- }
- }
- //订单评价
- public function actionComment()
- {
- $post = Yii::$app->request->post();
- $id = $post['id'];
- $order = OrderService::getById($id);
- OrderService::valid($order, $this->mainId);
- if ($order['grade'] > 0) {
- util::fail('您已经评过了');
- }
- OrderService::comment($post);
- util::complete('提交成功');
- }
- //订单详情,不需要登陆可以查看,要有盐,给跑腿上查看订单信息用的
- public function actionInfo()
- {
- $get = Yii::$app->request->get();
- $id = $get['id'] ?? 0;
- $salt = $get['salt'] ?? '';
- $detail = OrderClass::getFullInfo($id);
- if (empty($detail)) {
- util::fail('没有找到订单');
- }
- if (empty($detail['salt'])) {
- util::fail('没有找到订单信息');
- }
- if (empty($salt)) {
- util::fail('请求参数错误呢');
- }
- if ($detail['salt'] != $salt) {
- util::fail('不是你的订单');
- }
- util::success($detail);
- }
- //订单详情
- public function actionDetail()
- {
- $id = Yii::$app->request->get('id', 0);
- $detail = OrderClass::getFullInfo($id);
- OrderService::valid($detail, $this->mainId);
- $forwardMap = [];
- if ($detail['forward'] == 1) {
- //当前单如果已经是红冲订单,则取出其对应的原单
- $map = OrderForwardClass::getByCondition(['shOrderId' => $id], true);
- if (!empty($map)) {
- $originOrderId = $map->orderId ?? 0;
- $forwardMap['orderId'] = $originOrderId;
- }
- }
- $detail['forwardMap'] = $forwardMap;
- $shOrderMap = [];
- if ($detail['hasForward'] == 1) {
- $shOrderMap = OrderForwardClass::getAllByCondition(['orderId' => $id], null, '*');
- }
- $detail['shOrderMap'] = $shOrderMap;
- $main = $this->main;
- //是否走红冲订单模式判断 ssh
- $ret = OrderClass::ifShPay($detail, $main, 0);
- $shAddPay = $ret['shAddPay'];
- $shAddPayReason = $ret['shAddPayReason'];
- $detail['shAddPay'] = $shAddPay;
- $detail['shAddPayReason'] = $shAddPayReason;
- util::success($detail);
- }
- public function actionList()
- {
- $get = Yii::$app->request->get();
- $searchText = $get['searchText'] ?? '';
- $shopId = $this->shopId ?? 0;
- if (empty($shopId)) {
- //没有登录不显示数据
- util::success(['list' => [], 'moreData' => 0, 'shop' => [], 'totalNum' => 0, 'totalPage' => 0]);
- }
- $where = [];
- $where['shopId'] = $shopId;
- if (!empty($get['customId'])) {
- $where['customId'] = $get['customId'];
- }
- if (!empty($get['ids'])) {
- $stringIds = $get['ids'];
- $newIds = explode(',', $stringIds);
- $where['id'] = ['in', $newIds];
- }
- $status = $get['status'] ?? 0;
- if (!empty($status)) {
- $where['status'] = $get['status'];
- }
- $debt = $get['debt'] ?? -1;
- if ($debt > -1) {
- $where['debt'] = $debt;
- }
- if (!empty($get['shopAdminId'])) {
- $where['shopAdminId'] = $get['shopAdminId'];
- }
- // 按搜索词自动识别:纯数字查货号,否则查姓名
- if (!empty($searchText)) {
- $this->appendOrderListSearchWhere($where, $searchText);
- }
- if (isset($get['repeat']) && $get['repeat'] > -1) {
- $where['repeat'] = $get['repeat'];
- }
- if (!empty($get['searchTime'])) {
- $startTime = $get['startTime'] ?? '';
- $endTime = $get['endTime'] ?? '';
- $period = dateUtil::formatTime($get['searchTime'], $startTime, $endTime);
- $where['addTime'] = ['between', [$period['startTime'], $period['endTime']]];
- }
- $list = OrderService::getOrderList($where);
- $list['shop'] = $this->shop->attributes ?? [];
- util::success($list);
- }
- //订单归类 ssh 2019.12.17
- public function actionClassify()
- {
- $post = Yii::$app->request->post();
- $id = $post['id'] ?? 0;
- $order = OrderService::getById($id);
- OrderService::valid($order, $this->mainId);
- $categoryId = $post['categoryId'];
- $usageId = $post['usageId'];
- OrderService::classify($id, $categoryId, $usageId);
- util::complete();
- }
- //更新配送单 ssh 2019.12.17
- public function actionUpdateSheet()
- {
- $post = Yii::$app->request->post();
- $id = $post['id'] ?? 0;
- unset($post['id']);
- $order = OrderService::getById($id);
- OrderService::valid($order, $this->mainId);
- OrderService::updateSheet($order, $post);
- util::complete('提交成功');
- }
- //商家收款与发货 ssh 2019.12.18
- public function actionGathering()
- {
- $post = Yii::$app->request->post();
- $price = isset($post['price']) && is_numeric($post['price']) ? $post['price'] : 0;
- $payWay = isset($post['payWay']) && is_numeric($post['payWay']) ? $post['payWay'] : 0;
- $userId = $post['userId'] ?? 0;
- $userInfo = UserService::getById($userId);
- if (empty($userInfo) || $userInfo['sjId'] != $this->sjId) {
- util::fail('您选择的客户无效');
- }
- if ($price <= 0) {
- util::fail('请输入金额');
- }
- $post['prePrice'] = $price;
- $post['actPrice'] = $price;
- $post['payWay'] = $payWay;
- $post['sourceType'] = 1;
- $post['userId'] = $userId;
- $post['goodsNum'] = 1;
- $post['orderName'] = '商品';
- $shopId = MerchantService::getDefaultShopId($this->sj);
- $post['shopId'] = $shopId;
- $order = OrderService::addOrder($post);
- $id = $order['id'];
- $orderSn = $order['orderSn'];
- //流水类型列表
- $capitalType = dict::getDict('capitalType', 'xhOrder', 'id');
- $callbackParams = [];
- switch ($payWay) {
- case 0:
- xhPayToolService::wxPay($callbackParams, $orderSn, $price, $capitalType, 0);
- break;
- case 1:
- xhPayToolService::alipay($callbackParams, $orderSn, $price, $capitalType, 0, []);
- break;
- case 2:
- xhPayToolService::balancePay($callbackParams, $orderSn, $price, $capitalType, 0);
- break;
- default:
- util::fail('无效支付方式');
- }
- util::success($order);
- }
- //免发货管理 ssh 2020.1.6
- public function actionWithoutSend()
- {
- $id = Yii::$app->request->get('id');
- $order = OrderService::getById($id);
- OrderService::valid($order, $this->mainId);
- //配送流程变更
- $currentFlow = OrderSendClass::withoutSend($order);
- util::success(['currentFlow' => $currentFlow]);
- }
- //修改价格 ssh 2020.1.6
- public function actionUpdatePrice()
- {
- $id = Yii::$app->request->get('id');
- $price = Yii::$app->request->get('price', 1);
- $order = OrderService::getById($id);
- OrderService::valid($order, $this->mainId);
- if (isset($order['modPrice']) && $order['modPrice'] == 0) {
- util::fail('已发起支付,不能修改价格');
- }
- OrderService::updateById($id, ['actPrice' => $price]);
- util::complete('修改成功');
- }
- //配送单 ssh 2020.2.29
- public function actionGetDeliverDetail()
- {
- $id = Yii::$app->request->get('id', 0);
- $order = OrderService::getById($id);
- OrderService::valid($order, $this->mainId);
- $reachDate = isset($order['reachDate']) && !empty($order['reachDate']) ? $order['reachDate'] : '';
- $reachPeriodId = $order['reachPeriod'];
- $reachPeriodArr = [0 => '上午', 1 => '下午', 2 => '晚上'];
- $reachPeriod = isset($reachPeriodArr[$reachPeriodId]) ? $reachPeriodArr[$reachPeriodId] : '';
- $bookName = isset($order['bookName']) ? $order['bookName'] : '';
- $bookMobile = isset($order['bookMobile']) ? $order['bookMobile'] : '';
- if (isset($order['anonymity']) && $order['anonymity'] == 1) {
- $bookName = '--';
- $bookMobile = '--';
- }
- $data = [
- 'reachDate' => $reachDate . ' ' . $reachPeriod,
- 'orderSn' => $order['orderSn'],
- 'receiveUserName' => $order['receiveUserName'],
- 'receiveMobile' => $order['receiveMobile'],
- 'fullAddress' => $order['fullAddress'] . "(" . $order['showAddress'] . ")",
- 'cardInfo' => $order['cardInfo'],
- 'bookMobile' => $bookMobile,
- 'bookName' => $bookName,
- 'remark' => $order['remark'],
- 'sendNum' => $order['sendNum'],
- 'telephone' => 18030142050,
- 'printTime' => '',
- 'img' => '',
- ];
- util::success($data);
- }
- //运费计算 lqh 2021.4.12 暂反回固定
- public function actionFreight()
- {
- util::success(['sedCost' => 10]);
- }
- /**
- * 订单列表搜索条件:纯数字按货号精确匹配,否则按客户姓名模糊匹配
- * @param array $where 查询条件(引用传递)
- * @param string $searchText 搜索关键词
- */
- private function appendOrderListSearchWhere(&$where, $searchText)
- {
- $searchText = trim((string)$searchText);
- if ($searchText === '') {
- return;
- }
- if (preg_match('/^\d+$/', $searchText)) {
- $where['sendNum'] = $searchText;
- return;
- }
- $where['customName'] = ['like', $searchText];
- }
- }
|