| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731 |
- <?php
- namespace ghs\controllers;
- use biz\wx\classes\WxMessageClass;
- use biz\wx\classes\WxOpenClass;
- use bizGhs\express\classes\GhsExpressOrderClass as ExpressOrderClass;
- use bizHd\order\classes\OrderGoodsClass;
- use bizHd\user\classes\UserClass;
- use bizGhs\order\classes\OrderItemClass;
- use common\components\dict;
- use common\components\imgUtil;
- use hd\models\IntraCity\StoreFeeForm;
- // 以上类来自零售端
- use bizGhs\order\classes\OrderClass;
- use biz\shop\classes\MainClass;
- use biz\shop\classes\ShopClass;
- use common\components\noticeUtil;
- use common\components\util;
- use common\components\IntraCityExpress;
- use yii\helpers\Json;
- use yii\db\Query;
- use Yii;
- /**
- * 同城配送控制器
- *
- * 提供同城配送相关的API接口
- */
- class IntraCityController extends BaseController
- {
- public $guestAccess = ['callback'];
- /**
- * 创建门店
- * POST /intra-city/create-store
- */
- public function actionCreateStore()
- {
- try {
- $shop = $this->shop;
- $shopName = $shop->shopName ?? '';
- $sjName = $shop->merchantName ?? '';
- $name = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
- $storeData = [
- 'out_store_id' => $this->mainId, //自定义门店编号
- 'store_name' => $name,
- 'address_info' => [
- 'province' => $shop->province,
- 'city' => $shop->city,
- 'area' => $shop->dist,
- 'street' => '',
- 'house' => $shop->floor ? $shop->address . $shop->floor : $shop->address,
- 'lat' => $shop->lat,
- 'lng' => $shop->long,
- 'phone' => $shop->telephone
- ]
- ];
- // 验证必填参数
- $requiredFields = ['out_store_id', 'store_name', 'address_info'];
- foreach ($requiredFields as $field) {
- if (empty($storeData[$field])) {
- util::fail("缺少必填参数:{$field}");
- }
- }
- // 创建门店前,检查是否已经 开通门店权限 (有wxStoreId,即说明开通了)
- $main = MainClass::getById($this->mainId, true, 'id, wxStoreId');
- // 查询是否存在 wx_store_id,不存在则执行apply
- if ($main->wxStoreId == '') {
- $re = IntraCityExpress::applyStore();
- if (!is_array($re)) {
- $re = Json::decode($re, true);
- }
- if ($re['errcode'] != 0) {
- Yii::error("开通门店权限失败:" . $re['errmsg']);
- util::fail('开通门店权限失败');
- }
- }
- $result = IntraCityExpress::createStore($storeData);
- if ($result['errcode'] === 0) {
- // 保存微信门店编号(wx_store_id)
- $main->wxStoreId = $result['wx_store_id'];
- $main->save();
- util::success($result, "门店创建成功");
- } else {
- Yii::error("门店创建失败:" . $result['errmsg']);
- util::fail($result['errmsg']);
- }
- } catch (\Exception $e) {
- Yii::error("门店创建失败:" . $e->getMessage());
- util::fail("系统出错");
- }
- }
- /**
- * 查询门店创建情况
- */
- public function actionStore()
- {
- $shopId = $this->shopId;
- // 首先从门店扩展表查询是否已经创建
- $main = MainClass::getById($this->mainId, true, 'id, wxStoreId');
- if ($main->wxStoreId == '') { // 不存在,则从微信接口查询
- $result = IntraCityExpress::getStore($this->mainId);
- if ($result['errcode'] === 0) {
- $store = $result['store_list'][0];
- // 保存 wx_store_id
- $main->wxStoreId = $store['wx_store_id'];
- $main->save();
- util::success($store, "门店查询成功");
- } else {
- Yii::error("门店查询失败:" . $result['errmsg']);
- util::error(-1,'门店查询失败');
- }
- } else {
- $field = 'province, city, dist, lat, long, floor, address';
- $shop = ShopClass::getById($shopId, false, $field);
- $data = array_merge($shop, $main->toArray());
- util::success($data, "门店查询成功");
- }
- }
- /**
- * 更新门店
- */
- public function actionUpdateStore()
- {
- // 首先从门店扩展表查询是否已经创建
- $main = MainClass::getById($this->mainId, false, 'id, wxStoreId');
- if ($main['wxStoreId'] == '') {
- util::fail('未创建门店,请先创建');
- }
- $shop = $this->shop;
- $shopName = $shop->shopName ?? '';
- $sjName = $shop->merchantName ?? '';
- $name = $shopName == '首店' ? $sjName : $sjName . ' ' . $shopName;
- $storeData = [
- 'keys' => ['wx_store_id' => $main['wxStoreId']],
- 'content' => [
- 'store_name' => $name,
- 'address_info' => [
- 'province' => $shop->province,
- 'city' => $shop->city,
- 'area' => $shop->dist,
- 'street' => '',
- 'house' => $shop->floor ? $shop->address . $shop->floor : $shop->address,
- 'lat' => $shop->lat,
- 'lng' => $shop->long,
- 'phone' => $shop->telephone
- ],
- //"order_pattern" => 2,
- //"service_trans_prefer" => "SFTC" //order_pattern = 2时必填
- ]
- ];
- $result = IntraCityExpress::updateStore($storeData);
- if ($result['errcode'] === 0) {
- util::success($result, "门店更新成功");
- } else {
- Yii::error("门店更新失败:" . $result['errmsg']);
- util::fail($result['errmsg']);
- }
- }
- /**
- * 门店运费充值
- */
- public function actionStoreCharge()
- {
- $post = Yii::$app->request->post();
- $amount = floatval($post['amount']);
- $amountTurnFen = $amount * 100;
- if ($amountTurnFen < 5000) {
- util::fail('50元起充');
- }
- $expressId = $post['expressId'];
- $serviceTransIds = ['SFTC', 'DADA'];
- if (!in_array($expressId, $serviceTransIds)) {
- util::fail('快递动力ID出错');
- }
- $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
- if ($shopExt['wxStoreId'] == '') {
- util::fail('微信门店编号为空');
- }
- $wxStoreId = $shopExt['wxStoreId'];
- $result = IntraCityExpress::storeCharge($wxStoreId, $expressId, $amountTurnFen);
- if ($result['errcode'] === 0) {
- util::success($result, "门店余额充值单已生成");
- } else {
- Yii::error("门店余额充值失败:" . $result['errmsg']);
- util::fail('门店余额充值失败');
- }
- }
- /**
- * 门店余额查询
- */
- public function actionStoreBalance()
- {
- $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
- if ($shopExt['wxStoreId'] == '') {
- util::error(-1,'微信门店编号为空');
- }
- $wxStoreId = $shopExt['wxStoreId'];
- $result = IntraCityExpress::getBalance($wxStoreId);
- if ($result['errcode'] === 0) {
- $data = ['all_balance' => $result['all_balance'] / 100.0];
- foreach ($result['balance_detail'] as $item) {
- if ($item['service_trans_id'] == 'DADA') {
- $data['dada_balance'] = $item['balance'] / 100.0;
- }
- if ($item['service_trans_id'] == 'SFTC') {
- $data['sf_balance'] = $item['balance'] / 100.0;
- }
- }
- util::success($data, "门店余额查询成功");
- } else {
- Yii::error("门店余额查询失败:" . $result['errmsg']);
- util::fail('门店余额查询失败');
- }
- }
- /**
- * 查询运费
- */
- public function actionStoreFee()
- {
- $post = Yii::$app->request->post();
- // 创建表单验证模型
- $form = new StoreFeeForm();
- $form->setScenario('store_fee');
- $form->load($post, ''); // 直接从 post 数据加载,不使用模型名作为前缀
- // 执行表单验证
- $form->validateForm();
- $orderId = $post['orderId'];
- $order = OrderClass::getById($orderId);
- if (empty($order)) {
- util::fail('订单出错');
- }
- if ($order['mainId'] != $this->mainId) {
- util::fail('订单出错');
- }
- $sn = $order['orderSn'];
- $shopId = intval($this->shopId);
- if (empty($shopId)) {
- util::fail("门店不存在");
- }
- $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
- if (empty($shopExt)) {
- util::fail("微信门店不存在");
- }
- $itemInfoList = OrderItemClass::getAllByCondition(['orderSn'=>$sn], null,'id, name, cover, num');
- $orderType = 2; // 默认是 2。说明:1花束订单 2花材订单 3花束和花材都有
- if (empty($itemInfoList)) {
- $orderType = 1;
- }
- $cargoName = '花材'; // 商品名称,默认是花材
- $goodsInfoList = OrderGoodsClass::getListBySn($sn);
- if (count($goodsInfoList) == 1) {
- $goodsInfo = $goodsInfoList[0];
- $cargoName = $goodsInfo['name'];
- } else {
- if ($orderType != 2) {
- util::fail("订单商品数量不正确");
- }
- }
- $cargo = [
- 'cargo_name' => $cargoName, // 商品名称 -- $order 中没有,要在 goodsInfo 中取
- 'cargo_weight' => intval($post['weight'] * 1000), // 单位:克 -- 把千克转换为克
- 'cargo_price' => intval($post['price'] * 100), // 单位:分 -- 把元转换为分
- 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
- 'cargo_num' => intval($post['packageNum'])
- ];
- $originalLng = doubleval($post['user_lng']);
- $originalLat = doubleval($post['user_lat']);
- $orderData = [
- //'out_store_id' => $shopId,
- 'wx_store_id' => $shopExt['wxStoreId'],
- 'user_name' => $post['user_name'],
- 'user_phone' => $post['user_phone'],
- 'user_lng' => $originalLng,
- 'user_lat' => $originalLat,
- 'user_address' => $post['user_address'],
- 'cargo' => $cargo,
- //'use_sandbox' => 1 // 如果不需要沙箱,use_sandbox就不传就好了 -- 踩坑人的经验
- //'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1 // 根据环境变量判断是否使用沙盒环境 -- 没用,不生效
- ];
- //多处有用到这个方法,需修改请同步修改,搜索关键词 intra_city_express_pre_add
- $result = IntraCityExpress::preAddOrder($orderData);
- if ($result['errcode'] === 0) {
- util::success($result, "查询成功");
- } else {
- Yii::error("运费查询失败:" . json_encode($result));
- util::fail('运费查询失败' . json_encode($result));
- }
- }
- /**
- * 创建订单
- * POST /intra-city/create-order
- */
- public function actionCreateOrder()
- {
- try {
- $post = Yii::$app->request->post();
- $orderId = intval($post['orderId']);
- $order = OrderClass::getById($orderId);
- if (empty($order)) {
- util::fail('订单出错');
- }
- if ($order['mainId'] != $this->mainId) {
- util::fail('订单出错');
- }
- $sn = $order['orderSn'];
- $itemInfoList = OrderItemClass::getAllByCondition(['orderSn'=>$sn], null,'id, name, cover, num');
- $itemList = [];
- $itemCount = 0;
- foreach ($itemInfoList as $itemInfo) {
- $itemList[] = [
- 'item_name' => $itemInfo['name'],
- 'item_pic_url' => imgUtil::groupImg($itemInfo['cover']) . "?x-oss-process=image/resize,m_fill,h_130,w_130",
- 'count' => intval($itemInfo['num']),
- ];
- $itemCount += intval($itemInfo['num']);
- }
- $post['packageNum'] = $itemCount;
- $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
- if (empty($shopExt)) {
- util::fail("微信门店不存在");
- }
- // 获取 openid(小程序OpenId)
- $user = UserClass::getByCondition(['mobile'=>$order['customMobile']], false, false,'id, miniOpenId');
- if (empty($user)) {
- noticeUtil::push("通过手机号-".$order['customMobile'].",获取小程序OpenId失败");
- Yii::error('获取用户openId出错');
- util::fail('数据出错');
- }
- $cargoName = '花材'; // 商品名称
- $cargo = [
- 'cargo_name' => $cargoName,
- 'cargo_weight' => intval($post['weight'] * 1000),
- 'cargo_type' => IntraCityExpress::GOODS_TYPE_FLOWER,
- 'cargo_num' => intval($post['packageNum']),
- 'cargo_price' => intval($order['actPrice'] * 100), // $order 中有各个价格,请注意
- 'item_list' => $itemList,
- ];
- //生成 store_order_id
- $storeOrderId = $orderId . '_ghs';;
- if (true) { // 如果不是首次用 $orderId 创建快递配送,则要生成新 store_order_id
- // store_order_id 门店订单编号, 即 orderId。如果是重新配送的第n次,订单编号的命名规则为:orderId_cp_n
- $query = (new Query())
- ->from('xhGhsExpressOrder')
- ->where(['orderId' => $orderId]);
- $copyOrderCount = $query->count();
- $copyOrderCount += 1;
- //区分线上线下
- if (getenv('YII_ENV') == 'production') {
- $storeOrderId = $storeOrderId . '_cp_' . $copyOrderCount;
- } else {
- $storeOrderId = $storeOrderId . '_cs_cp_' . $copyOrderCount;
- }
- }
- $callbackUrl = Yii::$app->params['ghsHost'] . '/intra-city/callback';
- $orderData = [
- 'wx_store_id' => $shopExt['wxStoreId'],
- 'store_order_id' => $storeOrderId, //同一个门店订单编号要保证唯一,相同的订单号会重入
- 'user_openid' => $user['miniOpenId'],//'o-hXO4kkdM2nqORdiII42FlcdeL4'
- 'user_lng' => (float)$post['user_lng'],
- 'user_lat' => (float)$post['user_lat'],
- 'user_address' => $post['user_address'],
- 'user_name' => $post['user_name'],
- 'user_phone' => (string)$post['user_phone'],
- 'order_seq' => $order['sendNum'], // 用于配送员快速寻找到匹配的商品(非必传) -- 对应 xhOrder 表的 sendNum
- 'verify_code_type' => 0,
- 'order_detail_path' => '/pagesOrder/detail?id=' . $orderId, // TODO 后期要重新选个地址
- 'callback_url' => $callbackUrl, // 订单状态回调地址(非必传)
- //'use_sandbox' => getenv('YII_ENV') == 'production' ? 0 : 1, // 是否使用沙箱(非必传)
- 'cargo' => $cargo
- ];
- $result = IntraCityExpress::createOrder($orderData);
- if (isset($result['errcode']) && $result['errcode'] === 0) {
- try {
- // 保存进 xhGhsExpressOrder 表
- $data = [
- 'mainId' => $this->mainId,
- 'shopId' => $this->shopId,
- 'deliveryId' => isset($result['service_trans_id']) ? $result['service_trans_id'] : '',
- 'wxOrderId' => isset($result['wx_order_id']) ? $result['wx_order_id'] : '',
- 'wxStoreId' => isset($result['wx_store_id']) ? $result['wx_store_id'] : '',
- 'storeOrderId' => isset($result['store_order_id']) ? $result['store_order_id'] : '',
- 'orderId' => $orderId,
- 'transOrderId' => isset($result['trans_order_id']) ? $result['trans_order_id'] : '',
- 'distance' => isset($result['distance']) ? $result['distance'] : 0,
- 'fee' => isset($result['fee']) ? $result['fee'] : 0,
- 'fetchCode' => isset($result['fetch_code']) ? $result['fetch_code'] : '',
- 'orderSeq' => isset($result['order_seq']) ? $result['order_seq'] : ''
- ];
- ExpressOrderClass::add($data);
- $updateData = [
- 'sendDistance' => $data['distance'],
- 'sendStatus' => 0,
- 'deliveryId' => $data['deliveryId'],
- ];
- OrderClass::updateById($orderId, $updateData); // 更新订单状态为配送中
- util::success(['fee' => $data['fee']], '订单创建成功');
- } catch (\Exception $e) {
- Yii::error('同城配送创建订单保存数据失败:' . $e->getMessage());
- util::fail('订单创建失败');
- }
- } else if (isset($result['errcode']) && $result['errcode'] === 934002) {
- Yii::error("重复创建订单:" . ($result['errmsg'] ?? '未知错误'), 'intraCity');
- util::fail( '重复创建订单: ' . $result['errcode']);
- } else {
- noticeUtil::push("批发 -- " . $this->mainId . ",订单创建失败:" . json_encode($result));
- Yii::error("订单创建失败:" . ($result['errmsg'] ?? '未知错误'), 'intraCity');
- util::fail( '订单创建失败: ' . $result['errcode']);
- }
- } catch (\Exception $e) {
- Yii::error("订单创建异常:" . $e->getMessage(), 'intraCity');
- util::fail("系统出错");
- }
- }
- /**
- * 查询订单
- * GET /intra-city/get-order
- */
- public function actionGetOrder()
- {
- try {
- $shopExt = MainClass::getById($this->mainId, false, 'id, wxStoreId');
- if (empty($shopExt)) {
- util::fail("微信门店不存在");
- }
- $post = Yii::$app->request->post();
- $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
- $orderId = $post['orderId'];
- $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $shopExt['wxStoreId'];
- if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
- util::fail("参数不足:wx_order_id 或 (order_id + wx_store_id) 必须提供一组");
- }
- $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
- if ($order['mainId'] != $this->mainId) {
- util::fail('订单未找到');
- }
- // 检查是否存在重复的订单:如果存在,则使用最后一个订单的 store_order_id
- $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
- $query = (new Query())
- ->from('xhGhsExpressOrder')
- ->where(['orderId' => $orderId])
- ->andWhere(['mainId' => $this->mainId]);
- $esDatas = $query->all();
- $count = count($esDatas);
- if ($count > 0) {
- $es = $esDatas[0];
- $storeOrderId = $es['storeOrderId'];
- }
- $result = IntraCityExpress::queryOrder($wxStoreId, $storeOrderId, $wxOrderId);
- if (isset($result['errcode']) && $result['errcode'] === 0) {
- util::success($result, "查询成功");
- } else {
- Yii::error("订单查询失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
- util::fail( '订单查询失败: ' . $result['errcode']);
- }
- } catch (\Exception $e) {
- Yii::error("订单查询异常:" . $e->getMessage(), 'intracity');
- util::fail("系统出错");
- }
- }
- /**
- * 取消订单
- * POST /intra-city/cancel-order
- */
- public function actionCancelOrder()
- {
- try {
- $post = Yii::$app->request->post();
- $main = MainClass::getById($this->mainId, false, 'id, wxStoreId');
- if (empty($main)) {
- util::fail("微信门店不存在");
- }
- $wxOrderId = isset($post['wx_order_id']) ? $post['wx_order_id'] : '';
- $orderId = $post['orderId']; //配送订单创建成功后,也会返回的 store_order_id。 即 orderId
- $wxStoreId = isset($post['wx_store_id']) ? $post['wx_store_id'] : $main['wxStoreId'];
- if (empty($wxOrderId) && (empty($orderId) || empty($wxStoreId))) {
- util::fail("参数不足:wx_order_id 或 (store_order_id + wx_store_id) 必须提供一组");
- }
- $order = OrderClass::getById($orderId, false, 'id, mainId, sendStatus');
- if ($order['mainId'] != $this->mainId) {
- util::fail('订单未找到');
- }
- if (!in_array($order['sendStatus'], [0, 1, 4, 5])) {
- util::fail('配送单当前状态不能取消');
- }
- // 检查是否存在重复的订单,如果存在,则使用最后一个订单的 store_order_id
- $storeOrderId = $orderId; // ------------------------------------- 注意区分:$storeOrderId , $orderId 。它们有可能不相同
- $query = (new Query())
- ->from('xhGhsExpressOrder')
- ->where(['orderId' => $orderId])
- ->andWhere(['status' => 1])
- ->orderBy('addTime DESC');
- // $command = $query->createCommand();
- // $sql = $command->sql;
- $esDatas = $query->all();
- $count = count($esDatas);
- if ($count > 0) {
- $es = $esDatas[0];
- $storeOrderId = $es['storeOrderId'];
- if ($count > 1) {
- noticeUtil::push('同城配送订单重复多于1个. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId);
- }
- }
- $result = IntraCityExpress::cancelOrder($wxOrderId, $storeOrderId, $wxStoreId);
- if (isset($result['errcode']) && $result['errcode'] === 0) {
- // 更新订单状态
- OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
- $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true);
- if (!empty($eo)) {
- $eo->status = 3;
- $eo->cancelTime = date('Y-m-d H:i:s');
- $eo->deductfee = $result['deductfee'];
- $eo->save();
- }
- util::success($result, "订单取消成功");
- } else {
- if ($result['errcode'] == 934018) { // 93401 -- 订单已取消,请勿重复操作
- // 更新订单状态
- OrderClass::updateById($orderId, ['sendStatus' => 3]);//设置为取消状态
- util::success($result, "订单取消成功");
- }
- Yii::error("订单取消失败:" . ($result['errmsg'] ?? '未知错误'), 'intracity');
- util::fail('订单取消失败: ' . $result['errcode']);
- }
- } catch (\Exception $e) {
- Yii::error("订单取消异常:" . $e->getMessage(), 'intraCity');
- util::fail("系统出错");
- }
- }
- /**
- * 微信回调接口
- */
- public function actionCallback()
- {
- $callbackData = Yii::$app->request->post();
- if (empty($callbackData)) {
- $postStr = file_get_contents('php://input');
- $callbackData = json_decode($postStr, true);
- if (empty($callbackData)) {
- util::fail('回调请求的数据为空');
- }
- }
- // 从配置中获取安全token
- // $token = Yii::$app->params['wx_intracity_token'] ?? 'your_token_here';
- // $result = IntraCityExpress::handleOrderCallback($callbackData, $token);
- // 记录回调日志
- Yii::info('同城配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'intraCity');
- $storeOrderId = $callbackData['store_order_id'] ?? 0;
- $wxStoreId = $callbackData['wx_store_id'] ?? ''; //微信门店编号
- if (empty($storeOrderId) || empty($wxStoreId)) {
- Yii::error("配送单回调接口的请求参数出错,storeOrderId = $storeOrderId, wxStoreId = $wxStoreId");
- return $this->asJson(['return_code' => 1, 'return_msg' => '请求参数不正确']);
- }
- try {
- // 使用 storeOrderId 与 wxStoreId 去查询 xhExpressOrder 表
- $eo = ExpressOrderClass::getByCondition(['storeOrderId' => $storeOrderId, 'wxStoreId' => $wxStoreId], true, false);
- if (empty($eo)) {
- Yii::error('订单不存在. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
- return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
- }
- // 从 $storeOrderId 提取 orderId
- $arr = explode('_', $storeOrderId);
- $orderId = intval($arr[0]);
- if ($orderId == 0) {
- Yii::error('订单号为0. store_order_id: ' . $storeOrderId . ',wx_store_id: ' . $wxStoreId);
- return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
- }
- $tx = Yii::$app->db->beginTransaction(); // ====================== 开启事务
- $msg = ''; // 发通知的内容(默认为空,根据情况生成。没有内容则不会发通知)
- $orderStatus = intval($callbackData['order_status']);
- switch ($orderStatus) {
- // 订单创建成功
- case IntraCityExpress::ORDER_STATUS_CREATED:
- $eo->orderStatus = 1;
- // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
- OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 0]);
- break;
- // 商家取消订单
- case IntraCityExpress::ORDER_STATUS_CANCELED_BY_MERCHANT:
- $eo->orderStatus = 2;
- // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|取消
- OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
- $msg = '取消配送,订单编号 ';
- break;
- // 配送方取消订单
- case IntraCityExpress::ORDER_STATUS_CANCELED_BY_DELIVERY:
- $eo->orderStatus = 3;
- $eo->status = 0;
- // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|取消
- OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
- $msg = '配送方取消配送,订单编号 ';
- break;
- // 配送员接单
- case IntraCityExpress::ORDER_STATUS_ACCEPTED:
- $eo->orderStatus = 4;
- // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
- OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 1]); //订单创建时已执行了,这儿重复更新
- break;
- // 配送员到店
- case IntraCityExpress::ORDER_STATUS_ARRIVED:
- $eo->orderStatus = 5;
- // 更新 xhOrder 表的订单状态与配送状态 -- 配送中|已发货
- OrderClass::updateById($orderId, ['status' => 3, 'sendStatus' => 4]); //订单创建时已执行了,这儿重复更新
- break;
- // 配送中
- case IntraCityExpress::ORDER_STATUS_DELIVERING:
- $eo->orderStatus = 6;
- OrderClass::updateById($orderId, ['sendStatus' => 5]);
- break;
- // 配送员撤单
- case IntraCityExpress::ORDER_STATUS_WITHDRAWN:
- $eo->orderStatus = 7;
- $eo->status = 0;
- // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|未发货
- OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
- $msg = '跑腿取消配送,订单编号 ';
- break;
- // 配送完成
- case IntraCityExpress::ORDER_STATUS_COMPLETED:
- $eo->orderStatus = 8;
- // 更新 xhOrder 表的订单状态与配送状态 -- 已完成|已送达
- OrderClass::updateById($orderId, ['status' => 4, 'sendStatus' => 2]);
- break;
- // 配送异常
- case IntraCityExpress::ORDER_STATUS_EXCEPTION:
- $eo->orderStatus = 9;
- $eo->status = 0;
- noticeUtil::push('同城配送异常 --- store_order_id(orderId):' . $storeOrderId . ',wx_store_id:' . $wxStoreId);
- // 更新 xhOrder 表的订单状态与配送状态 -- 待配送|未发货
- OrderClass::updateById($orderId, ['status' => 2, 'sendStatus' => 3]);
- $msg = '订单配送异常,订单编号 ';
- break;
- }
- if ($msg != '') { // $msg 不为空,则发通知
- $order = OrderClass::getById($orderId, true, 'id, shopId, customName, sendNum');
- $shop = ShopClass::getById($order->shopId, true, 'id, ptStyle, mainId');
- $result = $msg . $order->sendNum;
- WxMessageClass::expressErrorInform($shop, $order->customName, $orderId, $result);
- }
- $re = $eo->save();
- if (!$re) {
- noticeUtil::push('同城配送回调更新订单状态失败. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId . ',status:' . $eo->status);
- Yii::error('更新订单状态失败. store_order_id:' . $storeOrderId . ',wx_store_id:' . $wxStoreId . ',status:' . $eo->status);
- $tx->rollBack(); // ====================== 事务回滚
- return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
- }
- $tx->commit(); // ====================== 事务提交
- return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']); // 成功状态的返回数据
- } catch (\Exception $e) {
- Yii::error('同城配送回调处理异常:' . $e->getMessage());
- return $this->asJson(['return_code' => 1, 'return_msg' => '系统错误']);
- }
- }
- //模拟接口回调 ssh 20250826
- public function actionMockNotify()
- {
- if (getenv('YII_ENV') != 'production') {
- $post = Yii::$app->request->post();
- $orderStatus = $post['orderStatus'] ?? 0;
- $wxOrderId = $post['wxOrderId'] ?? '';
- $ptStyle = dict::getDict('ptStyle', 'hd');
- $merchant = WxOpenClass::getWxInfo();
- $ret = IntraCityExpress::mockNotify($orderStatus, $wxOrderId, '', '', $merchant, $ptStyle);
- util::success($ret);
- }
- util::complete();
- }
- }
|