| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015 |
- <?php
- namespace ghs\controllers;
- use biz\common\classes\GhsNotifyClass;
- use Yii;
- use biz\shop\classes\ShopClass;
- use bizGhs\express\classes\GhsDeliveryOrderClass;
- use bizGhs\express\classes\DeliveryAuthTokenClass;
- use bizGhs\order\classes\OrderClass;
- use common\components\noticeUtil;
- use common\components\util;
- use common\components\delivery\services\DispatchService;
- use ghs\models\delivery\CancelOrderForm;
- use ghs\models\delivery\CreateOrderForm;
- use ghs\models\delivery\OrderDetailForm;
- use yii\web\Response;
- /**
- * 聚合配送
- * Class DeliveryController
- * @package ghs\controllers
- */
- class DeliveryController extends BaseController
- {
- public $guestAccess = [
- 'callback',
- 'shansong-auth-callback', 'shansong-callback',
- 'huolala-auth-callback', 'huolala-callback',
- 'fengniao-auth-callback', 'fengniao-callback',
- 'shunfeng-callback',
- 'dada-auth-callback', 'dada-callback',
- 'didi-auth-callback', 'didi-callback',
- ];
- public function actionList()
- {
- $platformList = [];
- $platformLogos = [
- 'dada' => ['name' => '达达', 'logo' => '📦'],
- 'shunfeng' => ['name' => '顺丰同城', 'logo' => '🚚'],
- 'meituan' => ['name' => '美团', 'logo' => '🍱'],
- 'fengniao' => ['name' => '蜂鸟', 'logo' => '🍜'],
- 'huolala' => ['name' => '货拉拉跑腿', 'logo' => '🚛'],
- 'shansong' => ['name' => '闪送', 'logo' => '⚡'],
- 'didi' => ['name' => '滴滴', 'logo' => '🚗'],
- 'uu' => ['name' => 'UU跑腿', 'logo' => '🛵']
- ];
- $allDeliveries = DeliveryAuthTokenClass::getAllByCondition(['mainId' => $this->mainId]);
- foreach ($allDeliveries as $d) {
- $item = [
- 'id' => $d['platform'],
- 'logo' => $platformLogos[$d['platform']]['logo'],
- 'name' => $platformLogos[$d['platform']]['name'],
- 'is_authorized' => true,
- 'balance' => $d['balance'] / 100.0,
- 'access_type' => 'oauth'
- ];
- $platformList[] = $item;
- }
- util::success(['platformList' => $platformList]);
- }
- // 获取授权URL
- public function actionGetAuthUrl()
- {
- $platform = Yii::$app->request->get('platformId');
- $Auth = new \common\components\delivery\services\AuthService();
- $mainId = $this->mainId;
- switch ($platform) {
- case 'shansong':
- $Auth->shansongAuth($mainId);
- break;
- case 'huolala':
- $Auth->huolalaAuth($mainId);
- break;
- case 'fengniao':
- $Auth->fengniaoAuth($mainId);
- break;
- case 'shunfeng':
- $Auth->shunfengAuth($mainId);
- break;
- case 'didi':
- $Auth->didiAuth($mainId, $this->shopId);
- break;
- case 'dada':
- $Auth->dadaAuth($mainId, $this->shopId);
- break;
- default:
- util::error(-1, $platform . '不存在');
- break;
- }
- }
- // 取消授权
- public function actionCancelAuth()
- {
- // 有平台有对应的取消授权接口,有的没有。
- // 有的就对接下,然后再删除数据。没有的直接删除数据就行。
- $platform = Yii::$app->request->get('platform');
- $delivery = DeliveryAuthTokenClass::getByCondition(['mainId' => $this->mainId, 'platform' => $platform]);
- if ($delivery) {
- if ($platform == 'shansong') {
- $auth = new \common\components\delivery\platform\shansong\Auth();
- $result = $auth->cancelAuthorization($delivery['accessToken']);
- if ($result['success']) {
- // 授权已取消
- } else {
- if ($result['message'] == '商户未授权,请授权后再次尝试') {
- Yii::info($this->mainId . '--商户未授权,请授权后再次尝试');
- } else {
- util::fail('取消授权失败:' . $result['message']);
- }
- }
- }
- } else {
- util::fail('取消授权失败,数据未找到');
- }
- $ret = DeliveryAuthTokenClass::deleteByCondition(['mainId' => $this->mainId, 'platform' => $platform]);
- if ($ret > 0) {
- util::success([], '取消授权成功');
- } else {
- util::fail('取消授权失败');
- }
- }
- // ----------------------------------------------- 各业务接口 ---------------------------------------------------------------
- /**
- * @deprecated
- *
- * 查询开通城市
- * @return array
- */
- public function actionOpenCitiesLists()
- {
- $platform = Yii::$app->request->get('platform');
- $ds = new DispatchService($this->mainId);
- $cities = $ds->openCitiesLists($platform);
- if ($platform == 'shansong') {
- $newCitiesArr = [];
- $citiesArr = $cities['data'];
- foreach ($citiesArr as $block) {
- foreach ($block['cities'] as $city) {
- $newCitiesArr[$city['name']] = $city;
- }
- }
- return $newCitiesArr;
- } else if ($platform == 'huolala') {
- $citiesArr = $cities['data']['city_list'];
- $newCitiesArr = [
- 'expire' => $cities['data']['expire'],
- ];
- foreach ($citiesArr as $city) {
- $newCitiesArr[$city['name']] = [
- 'city_id' => $city['city_id'],
- 'city_name' => $city['name'],
- ];
- }
- return $newCitiesArr;
- }
- return $cities;
- }
- // 获取发货地址和收货地址
- public function actionAddress()
- {
- $post = Yii::$app->request->post();
- $adminId = $this->adminId;
- util::checkRepeatCommit($adminId, 4);
- $orderId = intval($post['orderId']);
- $order = OrderClass::getById($orderId, false, 'fullAddress, long, lat');
- $shop = ShopClass::getById($this->shopId, false, 'fullAddress, long, lat');
- $ret = [
- "sender" => [
- 'name' => '门店',
- 'address' => $shop['fullAddress'],
- 'long' => $shop['long'],
- 'lat' => $shop['lat'],
- ],
- "receiver" => [
- 'name' => '客户',
- 'address' => $order['fullAddress'],
- 'long' => $order['long'],
- 'lat' => $order['lat'],
- ],
- ];
- util::success($ret, "success");
- }
- // 获取各跑腿平台报价
- public function actionAllDeliveryQuotes()
- {
- util::checkRepeatCommit($this->adminId, 3);
- $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('不是你的订单');
- }
- if (empty($order['address'])) {
- util::fail('客户地址缺失');
- }
- if (empty($order['long']) || empty($order['lat'])) {
- util::fail('客户地址信息缺失');
- }
- $pickupTime = $post['pickupTime'];
- $weight = $post['weight'];
- $remark = $post['remark'] ?? '';
- $order['weight'] = $weight;
- $order['remark'] = $remark;
- $shop = ShopClass::getById($this->shopId);
- $ds = new DispatchService($this->mainId);
- $ds->validateOrder($order); //对 $order 进行验证
- $platformQuotes = $ds->getAllPlatformPrice($order, $shop, $pickupTime);
- if (isset($platformQuotes['error'])) {
- util::fail($platformQuotes['error']);
- }
- // 格式化各平台报价为前端展示格式
- $deliveryList = $ds->formatPlatformQuotesForDisplay($platformQuotes);
- // 按 price 从低到高排序
- yii\helpers\ArrayHelper::multisort($deliveryList, 'price', SORT_ASC);
- $ret['deliveryList'] = $deliveryList;
- util::success($ret, "success");
- }
- // 批发快捷开单时 -- 获取各跑腿平台报价
- public function actionQuickOrderDeliveryQuotes()
- {
- $post = Yii::$app->request->post();
- $orderTime = date('Y-m-d H:i:s');
- // --------- $customId ----------
- $customId = $post['customId'];
- $custom = \bizGhs\custom\classes\CustomClass::getById($customId, true);
- if (empty($custom)) {
- util::fail('获取custom数据失败');
- }
- // 生成随机订单号,不要跟原来的混起来,跑腿-销售单-
- $prefix = 'PT-XSD-' . $this->mainId . '-';
- $orderSn = $prefix . round(microtime(true) * 1000);
- //构建出 Order 数据
- $order = [
- 'orderSn' => $orderSn,
- 'customName' => $custom['name'],
- 'customMobile' => $custom['mobile'],
- 'fullAddress' => $custom['fullAddress'],
- 'floor' => $custom['floor'],
- 'dist' => $custom['dist'],
- 'lat' => $custom['lat'],
- 'long' => $custom['long'],
- 'address' => $custom['address'], //'toAddress' => $order['address'],
- 'city' => $custom['city'],
- 'weight' => $post['weight'] ?? 1,
- 'remark' => $post['remark'] ?? '',
- 'prePrice' => floatval($post['totalPrice'] ?? 0),
- 'actPrice' => floatval($post['totalPrice'] ?? 0),
- ];
- $shop = ShopClass::getById($this->shopId);
- $ds = new DispatchService($this->mainId);
- $ds->validateOrder($order); //对 $order 进行验证
- $platformQuotes = $ds->getAllPlatformPrice($order, $shop, $orderTime);
- if (isset($platformQuotes['error'])) {
- util::fail($platformQuotes['error']);
- }
- // 格式化各平台报价为前端展示格式
- $deliveryList = $ds->formatPlatformQuotesForDisplay($platformQuotes);
- // 按 price 从低到高排序
- yii\helpers\ArrayHelper::multisort($deliveryList, 'price', SORT_ASC);
- $ret['deliveryList'] = $deliveryList;
- util::success($ret, "success");
- }
- // 创建订单(真实下单)
- public function actionCreateOrder()
- {
- $form = new CreateOrderForm();
- $form->loadAndValidate();
- $post = $form->getAttributes();
- $orderId = $post['orderId'] ?? 0; // xhGhsOrder.id
- $params = $post['allParams'] ?? [];
- $platform = $params['en_name'] ?? '';// 平台英文名,$post['platform'] 是中文
- if (empty($platform)) {
- util::fail('请选择跑腿');
- }
- $pickupTime = $post['pickupTime'];
- $params['mainId'] = $this->mainId;
- $params['ip'] = Yii::$app->request->userIP;
- $params['weight'] = $post['weight'];
- $params['remark'] = $post['remark'] ?? '';
- $params['total_price_fen'] = $post['price'];
- $params['pickupTime'] = $pickupTime['value'];
- $ghsOrder = OrderClass::getById($orderId, true);
- if (empty($ghsOrder)) {
- util::fail('没有找到订单');
- }
- if ($ghsOrder->mainId != $this->mainId) {
- util::fail('不是你的订单');
- }
- if (!in_array($ghsOrder['sendStatus'], [-4, -2, -1])) {
- Yii::error('订单已经发过跑腿');
- util::fail('订单已经发过跑腿');
- }
- //避免连续点击的重复提交 ssh
- $adminId = $this->adminId;
- util::checkRepeatCommit($adminId, 3);
- $ds = new DispatchService($this->mainId, $platform);
- $ret = $ds->createOrder($ghsOrder, 'xhGhsOrder', $this->shopId, $params);
- if (isset($ret['code']) && $ret['code'] == 0) {
- $gdo = GhsDeliveryOrderClass::getByCondition(['mainId' => $this->mainId, 'orderId' => $ret['data']['orderId'], 'orderStatus!=' => -1], true);
- if (empty($gdo)) {
- $data = [
- 'mainId' => $this->mainId,
- 'shopId' => $this->shopId,
- 'deliveryId' => $ret['platform'],
- 'ghsOrderId' => $orderId,
- 'orderId' => $ret['data']['orderId'],
- 'distance' => $ret['data']['distance'],
- 'fee' => $ret['data']['fee'],
- 'orderStatus' => 0
- ];
- // createdAt 中保存了滴滴跑腿订单的后半截数据
- if($platform == 'didi'){
- $data['createdAt'] = date('Y-m-d H:i:s', $ret['data']['timeStamp']);
- }
- GhsDeliveryOrderClass::add($data);
- } else {
- Yii::info('重复创建订单');
- noticeUtil::push('重复创建订单: ' . $ret['data']['orderId']);
- $gdo->orderId = $ret['data']['orderId'];
- $gdo->deliveryId = $ret['platform'];
- $gdo->distance = $ret['data']['distance'];
- $gdo->fee = $ret['data']['fee'];
- $gdo->orderStatus = 0;
- $gdo->save();
- }
- //更新订单
- $ghsOrder->sendDistance = $ret['data']['distance'];
- $ghsOrder->sendStatus = 0;
- $ghsOrder->deliveryId = $ret['platform'];
- $ghsOrder->sendType = 2;// 2指跑腿
- $ghsOrder->save();
- //OrderClass::hasSend($ghsOrder);// 更新 status (不正确的,暂留做为对比)
- //发货
- $params = ['fhType' => 0, 'fhWl' => '', 'fhWlNo' => '', 'staffId' => 0, 'staffName' => ''];
- OrderClass::orderSend($ghsOrder, $params);
- util::success($ret, "success");
- } else {
- if (isset($ret['msg'])) {
- util::fail($ret['msg']);
- }
- util::fail('创建跑腿失败');
- }
- }
- /**
- * 查询订单详情
- *
- * 1. 蜂鸟平台 orderId 可以使用 "XSD_CS26322799" (即:表 xhGhsOrder.orderSn)
- */
- public function actionOrderDetail()
- {
- $form = new OrderDetailForm();
- $form->loadAndValidate();
- $post = $form->getAttributes();
- $platform = $post['platform'];
- $orderId = $post['orderId'];
- $orderSn = isset($post['orderSn']) ? $post['orderSn'] : '';
- $ds = new DispatchService($this->mainId, $platform);
- $ret = $ds->selectOrder($orderId, $orderSn);
- $return = isset($ret['ret']) ? $ret['ret'] : $ret['code']; // 各平台兼容处理
- if ($return == 0) {
- util::success($ret, "success");
- }
- util::fail('查询失败');
- }
- // 取消订单
- public function actionCancelOrder()
- {
- $form = new CancelOrderForm();
- $form->loadAndValidate();
- $post = $form->getAttributes();
- $orderId = $post['orderId'] ?? 0; // 平台的orderId,
- $platform = $post['platform'] ?? '';
- $ghsOrderId = $post['ghsOrderId'];
- // 先获取配送订单,确保 $gdo 始终可用
- $gdos = GhsDeliveryOrderClass::getAllByCondition(['mainId' => $this->mainId, 'ghsOrderId' => $ghsOrderId, 'orderStatus!=' => -1], 'id DESC', '*', null, true);
- if (empty($gdos)) {
- util::fail('未找到对应订单: ' . $ghsOrderId);
- }
- if(count($gdos)>=2){
- noticeUtil::push("xhGhsDeliveryOrder ghsOrderId={$ghsOrderId} 有两笔以上是在配送中");
- $gdo = $gdos[0];
- }else{
- $gdo = $gdos[0];
- }
- // 如果没有提供平台和订单ID,从配送订单中获取
- if ($platform == ''){
- $platform = $gdo->deliveryId;
- }
- if($orderId == 0) {
- $orderId = $gdo->orderId;
- }
- $ds = new DispatchService($this->mainId, $platform);
- $cancelCostCent = 0;
- if ($platform == 'fengniao') {
- //请求订单预取消接口,获取是否可取消。如果运单状态不允许取消,则直接返回
- $cancelParams = ['order_id' => $orderId, 'order_cancel_code' => $post['order_cancel_code']];
- $res = $ds->getAdapter()->preCancelOrder($cancelParams);
- if ($res['code'] != 0) {
- util::fail('运单状态不允许取消');
- }
- $cancelCostCent = $res['data']['actual_cancel_cost_cent']; //取消实际需金额(单位:分)
- }
- if ($platform == 'shunfeng') {
- //请求订单预取消接口,获取是否可取消。如果运单状态不允许取消,则直接返回
- $cancelParams = ['order_id' => $orderId, 'order_cancel_code' => $post['order_cancel_code']];
- $res = $ds->getAdapter()->preCancelOrder($cancelParams);
- if ($res['code'] != 0) {
- util::fail('运单状态不允许取消');
- }
- $post['order_type'] = 1; //查询订单ID类型 1、顺丰订单号 2、商家订单号
- }
- if ($platform == 'dada') {
- $order = OrderClass::getById($gdo->ghsOrderId, false, 'id,orderSn');
- $orderId = $order['orderSn'];
- }
- if ($platform == 'didi') {
- $order = OrderClass::getById($gdo->ghsOrderId, false, 'id,orderSn');
- $timeStamp = strtotime($gdo->createdAt);
- $post['outOrderNo'] = \common\components\delivery\platform\didi\Didi::generateUniOroder($order['orderSn'], $timeStamp);
- $post['cancelSource'] = 1; // TODO 要增加取消码判断
- }
- $post['order_cancel_role'] = 1; //1:商户取消, 2:用户取消
- $ret = $ds->cancelOrder($orderId, $post);
- if ($ret['code'] == 0) {
- $ghsOrder = OrderClass::getById($ghsOrderId, true, 'id, sendDistance, sendStatus, deliveryId, purchaseId, status, purchaseId');
- $ghsOrder->sendDistance = 0;
- // 测试发现取消配送没回调的平台,统一在这主动更新配送状态
- if(in_array($platform, ['shunfeng', 'fengniao'])){
- $ghsOrder->sendStatus = -1;
- OrderClass::cancelOrderSend($ghsOrder, ['staffId' => 0, 'staffName' => '']);
- // 更新跑腿订单与批发订单状态
- $gdo->orderStatus = -1;
- OrderClass::cancelOrderSend($ghsOrder, ['staffId' => 0, 'staffName' => '']);
- GhsNotifyClass::ptErrorNotify($ghsOrder->id, '门店主动取消');
- }
- $gdo->cancelCost = $ret['platform'] !== 'fengniao' ? $ret['data']['deductionFee'] : $cancelCostCent; // 由于蜂鸟平台返回的扣费不一样造成
- if (!$gdo->save()) {
- Yii::error('保存配送订单失败: ' . json_encode($gdo->errors));
- util::fail('保存配送订单失败');
- }
- // $ghsOrder->deliveryId = ''; // 为了获取上一次的配送记录,不要置空
- $ghsOrder->sendTip = 0;
- if (!$ghsOrder->save()) {
- Yii::error('保存批发订单失败: ' . json_encode($ghsOrder->errors));
- util::fail('保存批发订单失败');
- }
- util::success($ret['data'], "success");
- }
- util::fail('失败:'.$ret['msg']);
- }
- /**
- * 获取订单取消原因
- */
- public function actionCancelReason()
- {
- $post = Yii::$app->request->post();
- $ghsOrderId = $post['ghsOrderId'];
- $platform = $post['platform'];
- $gdo = GhsDeliveryOrderClass::getByCondition(['mainId' => $this->mainId, 'ghsOrderId' => $ghsOrderId, 'orderStatus!=' => -1], true);
- if (!empty($gdo)) {
- $orderId = $gdo->orderId;
- //$platform = $gdo->deliveryId;
- } else {
- util::fail('未找到对应订单: ' . $ghsOrderId);
- }
- $ds = new DispatchService($this->mainId, $platform);
- $ret = $ds->getCancelReasonList($orderId);
- if ($ret['code'] == 0) {
- util::success($ret['data']);
- } else {
- Yii::error('获取订单取消原因:' . json_encode($ret));
- util::fail($ret['msg']);
- }
- }
- /**
- * 添加小费
- */
- public function actionAddTip()
- {
- $post = Yii::$app->request->post();
- $ghsOrderId = $post['ghsOrderId'];
- $platform = $post['platform'];
- $tips = intval($post['tips']);
- if ($tips < 0) {
- util::fail('小费金额至少为1元');
- }
- $tips *= 100;
- $gdo = GhsDeliveryOrderClass::getByCondition(['mainId' => $this->mainId, 'ghsOrderId' => $ghsOrderId, 'orderStatus' => ['in', [0, 1, 2, 10]]], true);
- if ($gdo == null) {
- util::fail('当前配送状态无法加小费');
- }
- $ds = new DispatchService($this->mainId, $platform);
- $ret = $ds->addTip(['orderId' => $gdo->orderId, 'tips' => $tips]);
- if ($ret['code'] == 0) {
- $gdo->tip = $tips + $gdo->tip;
- $gdo->save();
- $orderObj = OrderClass::getById($gdo->ghsOrderId, true, 'id,sendTip');
- $orderObj->sendTip = $tips / 100 + $orderObj->sendTip;
- $orderObj->save();
- util::success($ret['data']);
- } else {
- Yii::error('添加小费请求失败,请求数据是:' . json_encode($ret));
- util::fail($ret['msg']);
- }
- }
- // ---------------------------------------------------- 普通回调接口 ----------------------------------------------------------
- // 第三方回调入口
- /**
- * 回调接口
- */
- 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('回调请求的数据为空');
- }
- }
- // 记录回调日志
- Yii::info('聚合配送回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'delivery');
- return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
- }
- /**
- * 闪送回调接口
- * 回调返回的格式必须是{"status":200,"msg":"","data":null}格式,当status为200表示回调成功,否则,回调失败。当回调失败时,间隔一分钟重试一次,最多重试五次。
- */
- public function actionShansongCallback()
- {
- $callbackData = Yii::$app->request->post();
- if (empty($callbackData)) {
- $postStr = file_get_contents('php://input');
- $callbackData = json_decode($postStr, true);
- }
- Yii::info('shansong 回调 -- post: ' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
- $obj = new \common\components\delivery\platform\shansong\OrderStatusCallBack();
- $ret = $obj->handle($callbackData);
- if ($ret) {
- return $this->asJson(['status' => 200, 'msg' => 'OK', "data" => null]);
- } else {
- Yii::error('闪送回调失败: ' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
- return $this->asJson(['status' => 200, 'msg' => '回调失败', "data" => null]);
- }
- }
- /**
- * 蜂鸟回调接口
- */
- public function actionFengniaoCallback()
- {
- $callbackData = Yii::$app->request->post();
- Yii::info('fengniao 回调 -- post: ' . json_encode($callbackData, JSON_UNESCAPED_UNICODE));
- // 逆向回调接口结果的加签
- $param = [
- 'app_id' => $callbackData['app_id'],
- 'timestamp' => $callbackData['timestamp'],
- 'business_data' => $callbackData['business_data']
- ];
- $fa = new \common\components\delivery\services\adapter\FengniaoAdapter();
- $paramSign = $fa->generateSignature($param);
- if ($paramSign == $callbackData['signature']) {
- $businessData = isset($callbackData['business_data']) ? $callbackData['business_data'] : '';
- if (empty($businessData)) {
- $this->asJson(['return_code' => -1, 'return_msg' => 'business data is empty']);
- }
- $businessData = json_decode($businessData, true);
- $cbnObj = new \common\components\delivery\platform\fengniao\CallBackNotify();
- $ret = $cbnObj->handle($businessData['callback_business_type'], $businessData['param']);
- return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
- } else {
- Yii::error('蜂鸟回调接口签名出错');
- }
- }
- /**
- * 货拉拉回调接口
- */
- public function actionHuolalaCallback()
- {
- $post = Yii::$app->request->post();
- Yii::info('货拉拉回调接口post:' . json_encode($post, JSON_UNESCAPED_UNICODE), 'delivery');
- $action = $post['action'] ?? '';
- if ($action != 'order_update') {
- Yii::error('当前接口只处理货拉拉订单状态变更事件');
- return $this->asJson(['return_code' => 0, 'msg' => '当前接口只处理货拉拉订单状态变更事件']);
- }
- $param = $post;
- unset($param['signature']);
- $huolala = new \common\components\delivery\platform\huolala\Huolala();
- $paramSign = $huolala->generateSignatureWithoutAppSecret($param); //注意:不用拼接secret,所有的参数都参与计算,包含空值。
- if ($paramSign == $post['signature']) {
- $cbh = new \common\components\delivery\platform\huolala\CallBackHandler();
- $ret = $cbh->handler($post);
- if ($ret) {
- return $this->asJson(['serial_no' => $post['serial_no']]);
- } else {
- Yii::error('货拉拉回调失败: ' . json_encode($post, JSON_UNESCAPED_UNICODE));
- return $this->asJson(['return_code' => -1, 'return_msg' => 'failed']);
- }
- } else {
- Yii::error('蜂鸟回调接口签名出错');
- return $this->asJson(['return_code' => -1, 'return_msg' => 'signature error']);
- }
- }
- /**
- * 达达回调接口
- */
- public function actionDadaCallback()
- {
- $post = Yii::$app->request->post();
- if (empty($post)) {
- $postStr = file_get_contents('php://input');
- $post = json_decode($postStr, true);
- }
- Yii::info('达达回调:' . json_encode($post, JSON_UNESCAPED_UNICODE), 'dada-callback');
- $handler = new \common\components\delivery\platform\dada\CallBackHandler();
- $ret = $handler->handle($post);
- if($ret){
- Yii::info('达达回调业务成功处理', 'dada-callback');
- }
-
- return $this->asJson(['status' => 'ok']);
- }
- /**
- * 顺丰回调接口
- *
- * 授权回调也是在这实现的
- */
- public function actionShunfengCallback()
- {
- $post = Yii::$app->request->post();
- $cbh = new \common\components\delivery\platform\shunfeng\CallBackHandler();
- $ret = $cbh->handle($post);// 各回调处理
- if ($ret) {
- return $this->asJson(['error_code' => 0, 'error_msg' => 'success']);
- } else {
- Yii::error('顺丰回调失败: ' . json_encode($post, JSON_UNESCAPED_UNICODE));
- return $this->asJson(['error_code' => -1, 'error_msg' => 'failed']);
- }
- }
- /**
- * 滴滴回调接口
- */
- public function actionDidiCallback()
- {
- $post = Yii::$app->request->post();
- Yii::info('didi callback: ' . json_encode($post));
- $cbh = new \common\components\delivery\platform\didi\CallBackHandler();
- $ret = $cbh->handle($post);// 各回调处理
- if ($ret) {
- if(is_array($ret)){
- return $this->asJson($ret);
- }
- return $this->asJson(['error_code' => 0, 'error_msg' => 'success']);
- } else {
- Yii::error('滴滴回调失败: ' . json_encode($post, JSON_UNESCAPED_UNICODE));
- return $this->asJson(['error_code' => -1, 'error_msg' => 'failed']);
- }
- }
- // ---------------------------------------------------- 授权回调接口 ----------------------------------------------------------
- /**
- * 闪送授权回调接口
- */
- public function actionShansongAuthCallback()
- {
- $code = Yii::$app->request->get('code');
- $state = Yii::$app->request->get('state');
- $shopId = Yii::$app->request->get('shopId');
- $isAllStoreAuth = Yii::$app->request->get('isAllStoreAuth');
- $thirdStoreId = Yii::$app->request->get('thirdStoreId');
- $storeId = Yii::$app->request->get('storeId');
- // 验证state参数(防止CSRF)
- //if ($state != $yourUserId) {
- //throw new \yii\web\BadRequestHttpException('Invalid state parameter');
- //}
- // 获取AccessToken
- $auth = new \common\components\delivery\platform\shansong\Auth();
- $result = $auth->getAccessToken($code);
- if (!$result['success']) {
- throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
- }
- // 保存授权信息到数据库
- $data = [
- 'mainId' => $state,
- 'shopId' => $shopId, //闪送商户ID
- 'accessToken' => $result['access_token'],
- 'refreshToken' => $result['refresh_token'],
- 'expiresAt' => time() + $result['expires_in'],
- 'authType' => $isAllStoreAuth ? 'all_store' : 'single_store',
- 'platform' => 'shansong'
- ];
- if (!$isAllStoreAuth) {
- $data['third_store_id'] = $thirdStoreId;
- $data['shans_store_id'] = $storeId;
- }
- DeliveryAuthTokenClass::add($data);
- if (false) {
- throw new \yii\web\HttpException(500, '保存授权信息失败');
- }
- $templatePath = Yii::getAlias('@common/components/delivery/html/auth-success-template.html');
- $template = '';
- if (is_file($templatePath) && is_readable($templatePath)) {
- $template = file_get_contents($templatePath);
- }
- if ($template === false || $template === '') {
- throw new \yii\web\HttpException(500, '返回h5页面不存在');
- }
- $content = strtr($template, [
- '{{title}}' => '授权成功',
- '{{heading}}' => '授权成功',
- '{{message}}' => '您的闪送账号已成功完成授权,现在可以返回使用聚合配送服务。',
- ]);
- $response = Yii::$app->response;
- $response->format = Response::FORMAT_HTML;
- $response->content = $content;
- return $response;
- }
- /**
- * 货拉拉授权回调接口
- */
- public function actionHuolalaAuthCallback()
- {
- $get = Yii::$app->request->get();
- $getData = json_encode($get, JSON_UNESCAPED_UNICODE);
- Yii::info($getData);
- $code = $get['code'];
- $mainId = $get['mainId'];
- // 获取AccessToken
- $auth = new \common\components\delivery\platform\huolala\Auth();
- $result = $auth->getAccessToken($code);
- if (!$result['success']) {
- throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
- }
- // 保存授权信息到数据库
- $data = [
- 'mainId' => $mainId,
- 'shopId' => '',
- 'accessToken' => $result['access_token'],
- 'refreshToken' => $result['refresh_token'],
- 'expiresAt' => strtotime($result['auth_end_time']),
- 'authType' => 'all_store',
- 'platform' => 'huolala'
- ];
- DeliveryAuthTokenClass::add($data);
- $templatePath = Yii::getAlias('@common/components/delivery/html/auth-success-template.html');
- $template = '';
- if (is_file($templatePath) && is_readable($templatePath)) {
- $template = file_get_contents($templatePath);
- }
- if ($template === false || $template === '') {
- $template = '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{title}}</title></head><body><h1>{{heading}}</h1><p>{{message}}</p></body></html>';
- }
- $content = strtr($template, [
- '{{title}}' => '授权成功',
- '{{heading}}' => '授权成功',
- '{{message}}' => '您的货拉拉账号已成功完成授权,现在可以返回使用聚合配送服务。',
- ]);
- $response = Yii::$app->response;
- $response->format = Response::FORMAT_HTML;
- $response->content = $content;
- return $response;
- }
- /**
- * 蜂鸟授权回调接口
- */
- public function actionFengniaoAuthCallback()
- {
- $callbackData = Yii::$app->request->post();
- if (empty($callbackData)) {
- Yii::error('回调请求的数据为空');
- }
- Yii::info('蜂鸟授权回调:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'fengniao');
- $get = Yii::$app->request->get();
- if (!isset($get['main_id'])) {
- Yii::error('蜂鸟授权回调的回调地址 authCallbackUrl 中没有带 main_id');
- noticeUtil::push('蜂鸟授权回调的回调地址 authCallbackUrl 中没有带 main_id,回调数据:' . json_encode($callbackData, JSON_UNESCAPED_UNICODE), 'fengniao');
- return;
- }
- $mainId = $get['main_id'];
- $code = $callbackData['code'];
- $merchantId = $callbackData['merchant_id'];
- $scope = $callbackData['scope'];
- $state = $callbackData['state'];
- // 获取AccessToken
- $auth = new \common\components\delivery\platform\fengniao\Auth();
- $result = $auth->getAccessToken($code, $merchantId);
- if (!$result['success']) {
- noticeUtil::push("mainId=" . $mainId . ' 授权时,获取token失败,请让其重新发起授权');
- Yii::error(json_encode($result));
- throw new \yii\web\HttpException(500, '获取授权失败:' . $result['error']);
- }
- $result = $result['data'];
- $exist = DeliveryAuthTokenClass::exists(['mainId' => $mainId, 'platform' => 'fengniao']);
- if ($exist) {
- noticeUtil::push("mainId=" . $mainId . ' 已成功授权了。如果蜂鸟不能正确使用,请查询数据库进行检查。');
- } else {
- // 保存授权信息到数据库
- $data = [
- 'mainId' => $mainId,
- 'merchantId' => $merchantId,
- 'shopId' => '',
- 'accessToken' => $result['access_token'],
- 'refreshToken' => $result['refresh_token'],
- 'expiresAt' => $result['expire_in'] + time(),
- 'authType' => 'all_store', //即 scope='all'
- 'platform' => 'fengniao'
- ];
- DeliveryAuthTokenClass::add($data);
- }
- return $this->asJson(['return_code' => 0, 'return_msg' => 'OK']);
- }
- /**
- * 达达授权回调接口
- */
- public function actionDadaAuthCallback()
- {
- $get = Yii::$app->request->get();
- $getData = $get;
- Yii::info(json_encode($get, JSON_UNESCAPED_UNICODE));
- // {"sourceId":"1003654","ticket":"b8b4e56a86934b73a512ea9994e7774e","state":"huidiao_biaoshi","shopNo":"1003654-88547413"}
- if ($getData['state'] != 'huidiao_biaoshi') {
- Yii::error('达达授权回调 state 参数不对');
- return;
- }
- if (!isset($getData['mainId'])) {
- Yii::error('达达授权回调缺少必要参数 mainId');
- return;
- }
- try {
- // 保存授权信息到数据库
- $data = [
- 'mainId' => $getData['mainId'],
- 'merchantId' => $getData['sourceId'], // 用merchanId 来保存 sourceId
- 'shopId' => $getData['shopNo'],
- 'accessToken' => '',
- 'refreshToken' => '',
- 'expiresAt' => 9997773456,
- 'authType' => 'all_store', //即 scope='all'
- 'platform' => 'dada'
- ];
- DeliveryAuthTokenClass::add($data);
- $templatePath = Yii::getAlias('@common/components/delivery/html/auth-success-template.html');
- $template = '';
- if (is_file($templatePath) && is_readable($templatePath)) {
- $template = file_get_contents($templatePath);
- }
- if ($template === false || $template === '') {
- $template = '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{title}}</title></head><body><h1>{{heading}}</h1><p>{{message}}</p></body></html>';
- }
- $content = strtr($template, [
- '{{title}}' => '授权成功',
- '{{heading}}' => '授权成功',
- '{{message}}' => '您的达达账号已成功完成授权,现在可以返回使用聚合配送服务。',
- ]);
- $response = Yii::$app->response;
- $response->format = Response::FORMAT_HTML;
- $response->content = $content;
- Yii::info('达达授权回调保存成功', 'dada');
- return $response;
- } catch (\Exception $e) {
- Yii::error('达达授权回调保存失败' . $e->getMessage(), 'dada');
- }
- }
- public function actionDidiAuthCallback()
- {
- $callbackData = Yii::$app->request->post();
- if (empty($callbackData)) {
- Yii::error('回调请求的数据为空');
- }
- Yii::info('滴滴授权回调:' . json_encode($callbackData), 'didi');
- try {
- $param = json_decode($callbackData['logisticsParam'], true);
- // 保存授权信息到数据库
- $data = [
- 'mainId' => $param['thirdUid'],
- 'merchantId' => '',
- 'shopId' => '',
- 'accessToken' => $param['token'],
- 'refreshToken' => '',
- 'expiresAt' => 9997773456,
- 'authType' => 'all_store', //即 scope='all'
- 'platform' => 'didi'
- ];
- DeliveryAuthTokenClass::add($data);
- Yii::info('滴滴授权回调保存成功', 'didi');
- return $this->asJson(['code' => 200, 'msg' => 'auth success', 'data' => ['msg'=>'success']]);
- } catch (\Exception $e) {
- Yii::error('滴滴授权回调保存失败' . $e->getMessage(), 'didi');
- }
- }
- }
|