db->beginTransaction(); try { $configModel->menu_setting = json_encode($data); if (!$configModel->save()) { throw new Exception(self::dealSaveErrorsString($configModel->errors)); } $button = self::dealData($data, []); $res = self::$openPlatform->menu->delete(); if ($res['errcode'] != 0) { throw new Exception($res['errmsg']); } if ($button) { $res = self::$openPlatform->menu->create($button); if ($res['errcode'] != 0) { throw new Exception($res['errmsg']); } } $tra->commit(); return ['status' => true]; } catch (Exception $e) { $tra->rollBack(); return ['status' => false, 'info' => $e->getMessage()]; } } /** * 处理数据模型保存的报错信息 * @param $arr * @return string */ public static function dealSaveErrorsString($arr): string { $data = []; foreach ($arr as $k => $v) { $data[] = implode(' ', $v); } return implode(' ', $data); } /** * 处理前端数据,递归处理 * @param $data * @param $ret * @return mixed */ private static function dealData($data, $ret) { foreach ($data as $k => $button) { $name = $button['title']; $type = $button['content']['type']; $value = $button['content']['value']; $children = $button['children'] ?? []; $ret[$k] = self::spliceData($type, $value, $name); if ($children) { $ret[$k]['sub_button'] = []; $ret[$k]['sub_button'] = self::dealData($children, $ret[$k]['sub_button']); } } return $ret; } /** * 拼接数据为微信菜单格式 * @param $type * @param $value * @param $name * @return mixed */ private static function spliceData($type, $value, $name) { $ret['name'] = $name; if ($type) { $ret['type'] = $type; if ($type == self::TYPE_VIEW) { $ret['url'] = $value; } elseif ($type == self::TYPE_MINI_PROGRAM) { $ret['appid'] = $value['appId']; $ret['pagepath'] = $value['url']; $ret['url'] = $value['spareWebUrl']; } elseif ($type == self::TYPE_CUSTOM_PAGE) { // $ret['type'] = self::TYPE_MINI_PROGRAM; // $page = PageLayout::findOne($value); // $ret['appid'] = Yii::$app->config->getConfig()->mini_program_appId; // if ($page->is_home) { // $ret['pagepath'] = Yii::$app->params['pageIndex']; // } else { // $ret['pagepath'] = Yii::$app->params['pageOther'] . $value; // } // $ret['url'] = Yii::$app->config->getConfig()->wx_domain_name . '#/' . $ret['pagepath']; } } return $ret; } }