Просмотр исходного кода

Merge branch 'wx-kw' into feature-wechat

zqwang 1 год назад
Родитель
Сommit
cf85be4af4

+ 36 - 33
modules/Channel/Http/Controllers/WechatOpenPlatformController.php

@@ -34,7 +34,8 @@ class WechatOpenPlatformController extends CatchController
      * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
      * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
      */
-    public function preauth(Request $request) {
+    public function preauth(Request $request)
+    {
         $this->validate($request, [
             'user_id' => 'required'
         ]);
@@ -42,7 +43,7 @@ class WechatOpenPlatformController extends CatchController
         $componentInfo = WechatOpenPlatformService::getComponentInfoByCompanyUid($currentUser->id);
         $app = WechatOpenPlatformService::buildApplication($componentInfo);
         $user_id = $request->input('user_id');
-        $url = $app->getPreAuthorizationUrl(sprintf('%s/api/channel/openPlatform/auth/%s/%s',config('app.url'), $componentInfo->app_id, $user_id), []);
+        $url = $app->getPreAuthorizationUrl(sprintf('%s/api/channel/openPlatform/auth/%s/%s', config('app.url'), $componentInfo->app_id, $user_id), []);
         return $url;
     }
 
@@ -58,7 +59,8 @@ class WechatOpenPlatformController extends CatchController
      * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
      * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
      */
-    public function auth(Request $request, $component_appid, $user_id) {
+    public function auth(Request $request, $component_appid, $user_id)
+    {
         $auth_code = $request->input('auth_code');
         $auth_user = DB::table('users')
             ->where([
@@ -66,7 +68,7 @@ class WechatOpenPlatformController extends CatchController
             ])
             ->where('pid', '<>', 0)
             ->select('pid', 'id')->first();
-        if(!$auth_user) {
+        if (!$auth_user) {
             CommonBusinessException::throwError(Errors::OPENPLATFORM_OPTIMIZER_INFO_ERROR);
         }
         $componentInfo = WechatOpenPlatformService::getComponentInfoByAppid($component_appid);
@@ -84,11 +86,13 @@ class WechatOpenPlatformController extends CatchController
         ])->update([
             'is_enabled' => 0,
         ]);
-        WechatAuthorizationInfo::create([
+        WechatAuthorizationInfo::updateOrCreate([
             'authorizer_appid' => $authorizer_appid,
             'component_appid' => $component_appid,
             'user_id' => $user_id,
             'puser_id' => $auth_user->pid,
+        ], [
+            'is_enabled' => 1,
             'authorizer_refresh_token' => $authorizer_refresh_token,
             'nick_name' => $gzhBaseInfo['authorizer_info']['nick_name'],
         ]);
@@ -101,7 +105,8 @@ class WechatOpenPlatformController extends CatchController
      * @param Request $request
      * @param $component_appid
      */
-    public function authorCommand(Request $request, $component_appid) {
+    public function authorCommand(Request $request, $component_appid)
+    {
         $componentInfo = WechatOpenPlatformService::getComponentInfoByAppid($component_appid);
         $app = WechatOpenPlatformService::buildApplication($componentInfo);
 
@@ -117,36 +122,34 @@ class WechatOpenPlatformController extends CatchController
         return $server->serve();
     }
 
-    public function infoCommand(Request $request, $authorizer_appid, $component_appid) {
+    public function infoCommand(Request $request, $authorizer_appid, $component_appid)
+    {
 
         $componentInfo = WechatOpenPlatformService::getComponentInfoByAppid($component_appid);
-        $app = WechatOpenPlatformService::buildApplication($componentInfo);
-        myLog("wx-xiaoxi")->info('-------开始处理---'.get_date());
-        $server = $app->server;
+        $openPlatform = WechatOpenPlatformService::buildApplication($componentInfo);
+
+        $server = $openPlatform->server;
         $message = $server->getMessage();
-        myLog("wx-xiaoxi")->info([
-            'authorizer_appid' => $authorizer_appid,
-            'component_appid' => $component_appid,
-            'param' => $request->all(),
-            'msg' => $message,
-        ]);
-        $refreshToken = WechatOpenPlatformService::getRefreshToken($authorizer_appid,$component_appid);
-        $server = $app->officialAccount($authorizer_appid, $refreshToken);
-        // $server->addMessageListener('text', function($message) {
-        //       myLog("wx-xiaoxi")->info('----文本消息---');
-        //     if ($message->Content == "pk"){
-        //         return  $message->FromUserName;
-        //     }
-        // });
-
-        $server->server->push(function ($message) use($authorizer_appid,$component_appid) {
-            myLog("wx-xiaoxi")->info("----文本消息---");
-            myLog("wx-xiaoxi")->info("体消息:");
-            myLog("wx-xiaoxi")->info($message);
-            return WechatCommonService::handleMessage($authorizer_appid,$message);
+        // myLog("wx-xiaoxi")->info('-------开始处理---'.get_date());
+        // myLog("wx-xiaoxi")->info([
+        //     'authorizer_appid' => $authorizer_appid,
+        //     'component_appid' => $component_appid,
+        //     'param' => $request->all(),
+        //     'msg' => $message,
+        // ]);
+        $appInfo = WechatOpenPlatformService::getRefreshToken($authorizer_appid,$component_appid);
+        $wechatAppId = getProp($appInfo,'id');
+
+        $app = $openPlatform->officialAccount($authorizer_appid, getProp($appInfo,'authorizer_refresh_token'));
+        unset($appInfo);
+
+        $app->server->push(function ($message) use($app,$authorizer_appid,$wechatAppId) {
+            // myLog("wx-xiaoxi")->info("----文本消息---");
+            // myLog("wx-xiaoxi")->info("体消息:");
+            // myLog("wx-xiaoxi")->info($message);
+            return WechatCommonService::handleMessage($app,$wechatAppId ,$authorizer_appid,$message);
         });
-
-        myLog("wx-xiaoxi")->info('-------结束处理---'.get_date());
-        return $server->serve();
+        // myLog("wx-xiaoxi")->info('-------结束处理---'.get_date());
+        return $app->server->serve()->send();
     }
 }

+ 25 - 2
modules/Channel/Services/WechatOpenPlatform/WechatOpenPlatformService.php

@@ -5,13 +5,16 @@ namespace Modules\Channel\Services\WechatOpenPlatform;
 use EasyWeChat\Factory;
 use EasyWeChat\OpenPlatform\Application;
 use EasyWeChat\OpenPlatform\Message;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Query\Builder;
 use Illuminate\Support\Facades\Cache;
 use Illuminate\Support\Facades\DB;
 use Modules\Channel\Models\WechatAuthorizationInfo;
 use Modules\Common\Errors\Errors;
 use Modules\Common\Exceptions\CommonBusinessException;
+use Modules\Common\Services\BaseService;
 
-class WechatOpenPlatformService
+class WechatOpenPlatformService extends BaseService
 {
     public static function getComponentInfoByCompanyUid($companyUid) {
         $componentInfo = DB::table('wechat_open_platform_infos')
@@ -87,6 +90,26 @@ class WechatOpenPlatformService
             'component_appid' => $component_appid,
             'authorizer_appid' => $authorizer_appid,
             'is_enabled'  =>  1,
-        ])->value('authorizer_refresh_token');
+        ])->first();
+    }
+
+    /**
+     *  获取公众号的refreshToken
+     * name:getAppInfoById
+     * @param $id 公众号授权id
+     * @return Model|Builder|object|null
+     */
+    public static function getAppInfoById($id)
+    {
+        $info =   DB::table('wechat_authorization_infos')
+            ->where([
+                'id' =>  $id,
+                'is_enabled'  =>  1,
+            ])->first();
+        if (is_empty($info)){
+            self::throwErrMsg("公众号不存在或已取消授权");
+        }
+        return  $info;
+
     }
 }

+ 14 - 0
modules/Common/Services/BaseService.php

@@ -49,4 +49,18 @@ class BaseService
             ['value' => 'miniprogram', 'name' => "小程序"],
         ];
     }
+
+    /**
+     * 微信公众号菜菜单系统类型
+     * name: getWechatMenuSystemType
+     * @return \string[][]
+     * date 2023/07/11 11:00
+     */
+    public static  function  getWechatMenuSystemType(): array
+    {
+        return [
+            ['value' => 'android', 'name' => "安卓"],
+            ['value' => 'ios', 'name' => "苹果"],
+        ];
+    }
 }

+ 2 - 2
modules/Video/Http/Controllers/EpisodeController.php

@@ -30,11 +30,11 @@ class EpisodeController extends CatchController
             ->where([
                 'video_id' => $request->integer('video_id'),
                 'is_enabled' => 1
-            ])->select('series_name', 'series_sequence', 'video_key', 'duration', 'id', 'video_id');
+            ]);
         if ($isFee == 1){
             $videoSeries->where('series_sequence',"<",$video->charge_sequence);
         }
-        $videoSeries->orderBy('series_sequence', 'asc')
+        $videoSeries =   $videoSeries->select('series_name', 'series_sequence', 'video_key', 'duration', 'id', 'video_id')->orderBy('series_sequence', 'asc')
             ->paginate($request->integer('limit', 15));
         /**
          * 增加微信审核状态

+ 153 - 1
modules/WechatPlatform/Http/Controllers/WechatMenuController.php

@@ -11,7 +11,12 @@ namespace Modules\WechatPlatform\Http\Controllers;
 
 use Catch\Base\CatchController;
 use Illuminate\Http\Request;
+use Illuminate\Support\Facades\DB;
+use Modules\Channel\Services\WechatOpenPlatform\WechatOpenPlatformService;
+use Modules\Manage\Enmus\MiniprogramType;
 use Modules\User\Http\Controllers\UserTrait;
+use Modules\WechatPlatform\Http\Requests\WechatMenuRequest;
+use Modules\WechatPlatform\Services\WechatMenuService;
 
 
 class WechatMenuController extends CatchController
@@ -29,10 +34,157 @@ class WechatMenuController extends CatchController
         $userContext = $this->getUserContext(null);
         $param['user_id'] = $userContext['loginUser']->id;
         $param['puser_id'] = $userContext['loginUser']->pid;
+        return WechatMenuService::list($param);
     }
 
 
-    public function add(){
+    public function add(WechatMenuRequest $request)
+    {
+        $param = $request->validated();
+        $param['msg_content'] = $request->input('msg_content');
+        $param  = $this->handleParam($param);
+        $userContext = $this->getUserContext(null);
+        $param['user_id'] = $userContext['loginUser']->id;
+        $param['puser_id'] = $userContext['loginUser']->pid;
+        $param['wechat_accounts'] = [];
+        return WechatMenuService::addMenu($param);
+    }
+
+    public function edit($id,WechatMenuRequest $request)
+    {
+        $param = $request->validated();
+        $param['msg_content'] = $request->input('msg_content');
+        $param  = $this->handleParam($param);
+        return WechatMenuService::updateMenu($id,$param);
+    }
+
+    public function detail($id){
+        return WechatMenuService::detail($id);
+    }
+
+    public function authList($id){
+        $userId = $this->getLoginUserId();
+        return WechatMenuService::authList($id, $userId);
+    }
+
+    public function del(Request $request)
+    {
+        $ids = $request->input('ids');
+        if (empty($ids)) {
+            WechatMenuService::throwErrMsg('要删除的数据参数错误');
+        }
+
+        $ids = explode(',', $ids);
+        return WechatMenuService::del($ids);
+    }
+
+    /**
+     *  分配
+     * name: allocation
+     * @param $id
+     * date 2023/07/12 07:18
+     */
+    public function  allocation($id,Request $request)
+    {
+        if (!$request->has('wx_auth_ids')) {
+            WechatMenuService::throwErrMsg("参数错误");
+        }
+        if (!empty($request->input('wx_auth_ids'))) {
+            $wxAuthIds = explode(',', $request->input('wx_auth_ids'));
+        } else {
+            $wxAuthIds = [];
+        }
+        return WechatMenuService::allocation($id,$wxAuthIds);
+    }
+        // 处理参数
+    private function handleParam($param)
+    {
+        $info = DB::table('miniprogram')->where('id', $param['miniprogram_id'])->first();
+        if (empty($info)) {
+            WechatMenuService::throwErrMsg("小程序不正确");
+        }
+        if ($info->status != 1) {
+            WechatMenuService::throwErrMsg("此小程序暂不提供使用");
+        }
+        if ($info->type != MiniprogramType::WEIXIN->value()) {
+            WechatMenuService::throwErrMsg("关键词回复设置仅支持微信小程序");
+        }
+        $param['miniprogram_appid'] = $info->appid;
+        $info = DB::table('user_has_miniprograms')->where('uid', $this->getLoginUserId())->where('miniprogram_id', $param['miniprogram_id'])->where('is_enabled', 1)->value('id');
+        if (empty($info)) {
+            WechatMenuService::throwErrMsg("没有此小程序的使用权限");
+        }
+        if (count($param['content']) >3){
+            WechatMenuService::throwErrMsg("底部菜单不能超过3个");
+        }
+        // $clicks = [];
+        $msgContent = [];
+        foreach ($param['content'] as  &$val){
+            if (!empty(getProp($val,'sub_button'))){
+                foreach ($val['sub_button'] as &$sub){
+                    if (getProp($sub,'type') == 'miniprogram'){
+                        $sub['appid'] = $param['miniprogram_appid'];
+                        $sub['pagepath'] = $sub['url'];
+                    }
+                    if (getProp($sub,'type') == 'click'){
+                        // $clicks[] = $sub['key'];
+                        $msgContent[] =[$sub['key'] =>  $sub['content']];
+                    }
+                }
+            }else{
+                if (getProp($val,'type') == 'miniprogram'){
+                    $val['appid'] = $param['miniprogram_appid'];
+                    $val['pagepath'] = $val['url'];
+                }
+                if (getProp($val,'type') == 'click'){
+                    // $clicks[] = $val['key'];
+                    $msgContent[] =[$val['key'] =>  $val['content']];
+                }
+            }
+        }
+        $param['msg_content']= $msgContent;
+        // unset($val,$sub,$info);
+        // // 有点击事件
+        // if (!empty($clicks)){
+        //     $msgContent = [];
+        //     $msg = getProp($param,'msg_content');
+        //     if (empty($msg) || !is_array($msg)){
+        //         WechatMenuService::throwErrMsg("发送的文本信息不能为空");
+        //     }
+        //     foreach ($clicks as $val){
+        //         $temp = getProp($msg,$val);
+        //         if (empty($temp) || !is_array($temp)){
+        //             WechatMenuService::throwErrMsg("发送的文本信息格式不正确");
+        //         }
+        //         $contents = "";
+        //         foreach ($temp as  & $item){
+        //             if (getProp($item,'url')){
+        //                 $item['content'] = "<a href=\"\" data-miniprogram-appid=\"{$param['miniprogram_appid']}\" data-miniprogram-path=\"{$item['url']}\">{$item['title']}</a>";
+        //             }else{
+        //                 $item['content'] = $item['title'];
+        //             }
+        //             $contents =  $contents.$item['content']."\n";
+        //         }
+        //
+        //         rtrim($contents, "\n");
+        //         $temp['content'] = $contents;
+        //         $msgContent = [$val => $temp];
+        //     }
+        //     $param['msg_content'] = $msgContent;
+        //     unset($msgContent);
+        //     unset($temp,$val,$item);
+        // }else{
+        //     $param['msg_content']= [];
+        // }
+        return $param;
+    }
 
+    public function test(){
+        $info = WechatOpenPlatformService::getAppInfoById(8);
+        $componentInfo = WechatOpenPlatformService::getComponentInfoByAppid($info->component_appid);
+        $openPlatform = WechatOpenPlatformService::buildApplication($componentInfo);
+        $app = $openPlatform->officialAccount($info->authorizer_appid, getProp($info,'authorizer_refresh_token'));
+        unset($appInfo);
+        return $app->menu->list();
     }
 }

+ 65 - 0
modules/WechatPlatform/Http/Requests/WechatMenuRequest.php

@@ -0,0 +1,65 @@
+<?php
+/**
+ *
+ * @file:WechatMenuRequest.php
+ * @Date: 2023/7/11
+ * @Time: 10:49
+ */
+
+
+namespace Modules\WechatPlatform\Http\Requests;
+
+
+use Illuminate\Foundation\Http\FormRequest;
+use Modules\WechatPlatform\Services\WechatMenuService;
+
+class WechatMenuRequest extends FormRequest
+{
+
+    /**
+     * rules
+     *
+     * @return array
+     */
+    public function rules(): array
+    {
+        return [
+            'title' => "required",
+            'type' => [
+                "required",
+                function ($attribute, $value, $fail) {
+                    $types = array_column(WechatMenuService::getWechatMenuSystemType(), 'value');
+                    if (!in_array($value, $types)) {
+                        $fail("关键词类型不正确!");
+                    }
+                }
+            ],
+            'miniprogram_id' => [
+                'required',
+                'Integer',
+                "gt:0",
+            ],
+            "content" => "required|array",
+        ];
+    }
+
+
+    /**
+     * messages
+     *
+     * @return string[]
+     */
+    public function messages(): array
+    {
+        return [
+            'title.required' => '菜单名称必须填写',
+            'type.required' => '系统类型必须填写',
+            "miniprogram_id.required" => "小程序必须填写",
+            "content.required" => "菜单必须填写",
+            "content.array" => "菜单格式不正确",
+        ];
+    }
+}
+
+
+

+ 0 - 1
modules/WechatPlatform/Models/WechatAccountKeywordLog.php

@@ -12,5 +12,4 @@ class WechatAccountKeywordLog extends BaseModel
     protected $fillable = [
         'id','user_id', 'puser_id',  'weacht_keyworld_id',"miniprogram_id", 'appid',"wechat_authorization_info_id", 'nick_name', 'keyword', 'content', 'status', 'send_total', 'updated_at', 'created_at',
     ];
-
 }

+ 16 - 0
modules/WechatPlatform/Models/WechatAccountMenuDetail.php

@@ -0,0 +1,16 @@
+<?php
+
+namespace Modules\WechatPlatform\Models;
+
+use Modules\Common\Models\BaseModel;
+
+
+class WechatAccountMenuDetail extends BaseModel
+{
+    protected $table = 'wechat_account_menu_detail';
+
+    protected $fillable = [
+        'id', 'user_id', 'puser_id','wx_menuid','type', 'menu_id','msg_content', 'appid', 'wechat_authorization_info_id', 'miniprogram_id', 'nick_name', 'content', 'status', 'updated_at', 'created_at',
+    ];
+    protected $casts = ['content' => 'array','msg_content' => 'array'];
+}

+ 0 - 1
modules/WechatPlatform/Models/WechatAccountSubscribeDetail.php

@@ -11,5 +11,4 @@ class WechatAccountSubscribeDetail extends BaseModel
     protected $fillable = [
         'id', 'user_id', 'puser_id', 'subscribe_id', 'appid', 'wechat_authorization_info_id', 'miniprogram_id', 'nick_name', 'content', 'status', 'send_total', 'updated_at', 'created_at',
     ];
-
 }

+ 18 - 0
modules/WechatPlatform/Models/WechatMenu.php

@@ -0,0 +1,18 @@
+<?php
+
+namespace Modules\WechatPlatform\Models;
+
+
+use Modules\Common\Models\BaseModel;
+
+
+class WechatMenu extends BaseModel
+{
+    protected $table = 'wechat_menu';
+
+    protected $fillable = [
+        'id', 'user_id', 'puser_id', 'title', 'miniprogram_id', 'msg_content','type', 'miniprogram_appid', 'content', 'wechat_accounts', 'is_del', 'del_at', 'updated_at', 'created_at',
+    ];
+
+    protected $casts = ['content' => 'array','wechat_accounts' => 'array','msg_content' => 'array'];
+}

+ 16 - 0
modules/WechatPlatform/Models/WechatOfficialUserInfo.php

@@ -0,0 +1,16 @@
+<?php
+
+namespace Modules\WechatPlatform\Models;
+
+use Modules\Common\Models\BaseModel;
+
+
+class WechatOfficialUserInfo extends BaseModel
+{
+    protected $table = 'wechat_official_user_info';
+
+    protected $fillable = [
+        'id', 'uid', 'gzh_appid', "gzh_id", "active_at", "unsubscribe_at", 'user_id', 'puser_id', 'mp_openid', 'unionid', 'is_subscribe', 'subscribe_time', 'subscribe_time_str', 'active_end', 'updated_at', 'created_at',
+    ];
+
+}

+ 159 - 32
modules/WechatPlatform/Services/WechatCommonService.php

@@ -9,7 +9,9 @@
 
 namespace Modules\WechatPlatform\Services;
 
+use Illuminate\Support\Facades\DB;
 use Modules\Common\Services\BaseService;
+use Modules\WechatPlatform\Models\WechatOfficialUserInfo;
 
 class WechatCommonService extends BaseService
 {
@@ -22,48 +24,47 @@ class WechatCommonService extends BaseService
      * @param $sequence
      * date 2023/07/07 11:52
      */
-    public static function getPlayPageUrl($videoId,$sequence)
+    public static function getPlayPageUrl($videoId, $sequence)
     {
-        return ['url' =>  "/pages/video/index?video_id={$videoId}&sequence={$sequence}"];
+        return ['url' => "/pages/video/index?video_id={$videoId}&sequence={$sequence}"];
     }
 
     /**
-     *  微信消息推送处理
-     * name: handelMessage
-     * @param $authorizer_appid
+     *   微信消息推送处理
+     * name: handleMessage
+     * @param $app
+     * @param $wechatInfoId 公众号授权信息id
+     * @param $appid 公众号APPID
      * @param $message
-     * date 2023/07/10 14:53
+     * @return string|void
+     * date 2023/07/10 16:04
      */
-    public static function handleMessage($appid, $message)
+    public static function handleMessage($app, $wechatInfoId, $appid, $message)
     {
         switch ($message['MsgType']) {
             case 'event':
-                return '收到事件消息';
-                break;
+                return self::handleEvent($app, $wechatInfoId, $appid, $message);
             case 'text':
-                return self::handleTextMessage($appid,$message);
-                break;
-            case 'image':
-                return '收到图片消息';
-                break;
-            case 'voice':
-                return '收到语音消息';
-                break;
-            case 'video':
-                return '收到视频消息';
-                break;
-            case 'location':
-                return '收到坐标消息';
-                break;
-            case 'link':
-                return '收到链接消息';
-                break;
-            case 'file':
-                return '收到文件消息';
+                // 更新用户活跃时间
+                self::updateUserActivityTime($app,$appid, $message['FromUserName'],$wechatInfoId );
+                return self::handleTextMessage($wechatInfoId, $message);
+            // case 'image':
+            //     return '收到图片消息';
+            // case 'voice':
+            //     return '收到语音消息';
+            // case 'video':
+            //     return '收到视频消息';
+            // case 'location':
+            //     return '收到坐标消息';
+            // case 'link':
+            //     return '收到链接消息';
+            // case 'file':
+            //     return '收到文件消息';
             default:
+                self::updateUserActivityTime($app, $appid, $message['FromUserName'],$wechatInfoId);
                 return '收到其它消息';
-                break;
         }
+        return "";
     }
 
     /**
@@ -73,11 +74,137 @@ class WechatCommonService extends BaseService
      * @param $content
      * date 2023/07/10 15:03
      */
-    private static function handleTextMessage($appid, $msg)
+    private static function handleTextMessage($wechatAppId, $msg)
     {
         $content = $msg['Content'];
-        if ($content == "pk"){
-            return $msg['FromUserName'] ;
+        if ($content == "pk") {
+            return $msg['FromUserName'];
         }
+        $back = WechatKeywordsService::getKeywordsByWords($content, $wechatAppId);
+        return $back ?: "";
     }
+
+    /**
+     *  更新用户活跃时间
+     * name: updateUserActivityTime
+     * @param $app
+     * @param $appid
+     * @param $openId
+     * date 2023/07/10 18:30
+     */
+    private static function updateUserActivityTime($app, $appid, $openId, $wechatInfoId)
+    {
+
+        $info = WechatOfficialUserInfo::query()->where('mp_openid', $openId)->where('gzh_appid', $appid)->first();
+        $data = [
+            'mp_openid' => $openId,
+            'gzh_appid' => $appid,
+            'gzh_id' =>  $wechatInfoId,
+            'active_at' => time(),
+        ];
+        if (is_empty($info)) {
+            $data = self::getUserInfo($app,$appid,$openId,$wechatInfoId);
+            $data['active_at'] = time();
+        }else{
+            if ($info->uid == 0 && !empty($info->unionid)){
+                $data['uid'] = intval(DB::table('wechat_miniprogram_users')->where('unionid', $info->unionid)->value('id'));
+            }
+        }
+
+        WechatOfficialUserInfo::updateOrCreate(['mp_openid' => $data['mp_openid'], 'gzh_appid' => $data['gzh_appid']], $data);
+    }
+
+    /**
+     *  关注取消关注更新用户信息
+     * name: updateUserInfo
+     * @param $app
+     * @param $appid
+     * @param $openId
+     * @param $is_gz
+     * date 2023/07/10 18:31
+     */
+    private static function updateUserInfo($app, $appid, $openId, $wechatInfoId, $is_gz)
+    {
+
+        if (!$is_gz) {
+            $data = [
+                'mp_openid' => $openId,
+                'gzh_appid' => $appid,
+                'gzh_id' => $wechatInfoId,
+                'active_at' => time(),
+                'is_subscribe' => 0,
+                'unsubscribe_at' => get_date(),
+            ];
+        } else {
+            $data = [
+                'mp_openid' => $openId,
+                'gzh_appid' => $appid,
+                'gzh_id' => $wechatInfoId,
+                'is_subscribe' => 1,
+                'subscribe_time' => time(),
+                'subscribe_time_str' => get_date(),
+            ];
+        }
+        $info = WechatOfficialUserInfo::query()->where('mp_openid', $openId)->where('gzh_appid', $appid)->first();
+        if ($is_gz == true && is_empty($info)) {
+            $data = self::getUserInfo($app,$appid,$openId,$wechatInfoId);
+            WechatOfficialUserInfo::updateOrCreate(['mp_openid' => $data['mp_openid'], 'gzh_appid' => $data['gzh_appid']], $data);
+        }else{
+            if (!is_empty($info)){
+                if ($info->uid == 0 && !empty($info->unionid)){
+                    $data['uid'] = intval(DB::table('wechat_miniprogram_users')->where('unionid', $info->unionid)->value('id'));
+                }
+                WechatOfficialUserInfo::updateOrCreate(['mp_openid' => $data['mp_openid'], 'gzh_appid' => $data['gzh_appid']], $data);
+            }
+        }
+    }
+
+    /**3
+     *  构建用户数据
+     * name: getUserInfo
+     * @param $app
+     * @param $appid
+     * @param $openId
+     * date 2023/07/10 18:31
+     */
+    protected  static  function getUserInfo($app,$appid,$openId, $wechatInfoId){
+        $user = $app->user->get($openId);
+        return [
+            'mp_openid' => $openId,
+            'gzh_appid' => $appid,
+            'gzh_id' => $wechatInfoId,
+            'unionid' => $user['unionid'],
+            'is_subscribe' => $user['subscribe'],
+            'subscribe_time' => $user['subscribe_time'],
+            'subscribe_time_str' => get_date($user['subscribe_time']),
+            'uid' => !is_empty($user['unionid']) ? intval(DB::table('wechat_miniprogram_users')->where('unionid', $user['unionid'])->value('id')) : 0,
+        ];
+    }
+
+    /**
+     *  处理事件消息
+     * name: handleEvent
+     * @param $app
+     * @param $wechatInfoId
+     * @param $appid
+     * @param $message
+     * @return mixed|string
+     * date 2023/07/11 09:15
+     */
+    private static function handleEvent($app,  $wechatInfoId, $appid, $message)
+    {
+        switch ($message['Event']) {
+            case 'unsubscribe':
+                self::updateUserInfo($app, $appid, $message['FromUserName'], $wechatInfoId,false);
+                return '取消关注';
+            case 'subscribe':
+                self::updateUserInfo($app, $appid, $message['FromUserName'],$wechatInfoId, true);
+                return WechatSubscribeService::getContent($wechatInfoId);
+            default:
+                return '收到其它消息';
+        }
+        return  '';
+    }
+
+
 }

+ 83 - 55
modules/WechatPlatform/Services/WechatKeywordsService.php

@@ -44,12 +44,12 @@ class WechatKeywordsService extends BaseService
      */
     public static function getKeywordsList(array $param)
     {
-        $sql = self::getQuery($param)->orderBy('id','desc');
-        $isAll = getProp($param,'is_all',false);
-        if($isAll){
+        $sql = self::getQuery($param)->orderBy('id', 'desc');
+        $isAll = getProp($param, 'is_all', false);
+        if ($isAll) {
             $list = $sql->get();
-        }else{
-            $list = $sql->paginate(getProp($param,'limit',10));
+        } else {
+            $list = $sql->paginate(getProp($param, 'limit', 10));
         }
         $list->makeHidden(self::$hideField);
         return $list;
@@ -57,7 +57,7 @@ class WechatKeywordsService extends BaseService
 
     private static function getQuery(array $param)
     {
-        $sql = WechatKeywords::query()->where('is_del',0);
+        $sql = WechatKeywords::query()->where('is_del', 0);
         if (getProp($param, 'puser_id')) {
             $sql->where('puser_id', $param['puser_id']);
         }
@@ -67,11 +67,11 @@ class WechatKeywordsService extends BaseService
         if (getProp($param, 'keyword')) {
             $sql->where('keyword', "like", "%" . $param['keyword'] . "%");
         }
-        if(getProp($param,'miniprogram_id')){
-            $sql->where('miniprogram_id',  $param['miniprogram_id']);
+        if (getProp($param, 'miniprogram_id')) {
+            $sql->where('miniprogram_id', $param['miniprogram_id']);
         }
-        if(getProp($param,'wechat_authorization_info_id')){
-            $sql->whereJsonContains('wechat_accounts->id',$param['wechat_authorization_info_id']);
+        if (getProp($param, 'wechat_authorization_info_id')) {
+            $sql->whereJsonContains('wechat_accounts->id', $param['wechat_authorization_info_id']);
         }
         return $sql;
     }
@@ -84,7 +84,7 @@ class WechatKeywordsService extends BaseService
      */
     public static function detail($id)
     {
-        return WechatKeywords::where('id', $id)->where('is_del', 0)->first()->makeHidden(array_merge(self::$hideField,['wechat_accounts']));
+        return WechatKeywords::where('id', $id)->where('is_del', 0)->first()->makeHidden(array_merge(self::$hideField, ['wechat_accounts']));
     }
 
     /**
@@ -106,10 +106,10 @@ class WechatKeywordsService extends BaseService
             // 修改关键词,需要查询词关键词是否已配置
             $appIds = WechatAccountKeywordLog::where('weacht_keyworld_id', $info->id)->where('status', 1)->pluck('wechat_authorization_info_id')->toArray();
         }
-        WechatKeywords::query()->where('id',$id)->update($param);
-        if ($appIds){
-            WechatAccountKeywordLog::where('weacht_keyworld_id',$info->id)->update(['status' => 0]);
-            self::allocation($info->id,$appIds);
+        WechatKeywords::query()->where('id', $id)->update($param);
+        if ($appIds) {
+            WechatAccountKeywordLog::where('weacht_keyworld_id', $info->id)->update(['status' => 0]);
+            self::allocation($info->id, $appIds);
         }
         return "操作成功";
     }
@@ -163,7 +163,7 @@ class WechatKeywordsService extends BaseService
             DB::rollBack();
             self::throwErrMsg('删除失败');
         }
-        return "操作成功";
+        return ['msg' => "操作成功"];
     }
 
     public static function allocation($id, $wxAuthIds)
@@ -175,49 +175,49 @@ class WechatKeywordsService extends BaseService
         $data = [];
         $list = [];
         $errMsg = "";
-        if (empty($wxAuthIds)){
+        if (empty($wxAuthIds)) {
             $data['wechat_accounts'] = [];
-        }else{
+        } else {
             $wechatAccountInfos = DB::table('wechat_authorization_infos')
-                ->whereIn('id',$wxAuthIds)
-                ->where('is_enabled',1)
-                ->where('user_id',$info->user_id)
+                ->whereIn('id', $wxAuthIds)
+                ->where('is_enabled', 1)
+                ->where('user_id', $info->user_id)
                 ->get();
-            if($wechatAccountInfos->isEmpty()){
+            if ($wechatAccountInfos->isEmpty()) {
                 self::throwErrMsg("优化师对提交的公众号没有使用权限");
             }
 
             $canNotUsed = $wechatAccountInfos->pluck('id')->toArray();
-            $canNotUsed = array_diff($wxAuthIds,$canNotUsed);
-            if (count($canNotUsed) > 0){
-                self::throwErrMsg("优化师对id:为:".implode(',',$canNotUsed)."的公众号没有使用权限");
+            $canNotUsed = array_diff($wxAuthIds, $canNotUsed);
+            if (count($canNotUsed) > 0) {
+                self::throwErrMsg("优化师对id:为:" . implode(',', $canNotUsed) . "的公众号没有使用权限");
             }
-            $keywords = explode(',',$info->keyword);
+            $keywords = explode(',', $info->keyword);
 
-            $allSet =   WechatAccountKeywordLog::where('user_id',$info->user_id)->get();
+            $allSet = WechatAccountKeywordLog::where('user_id', $info->user_id)->get();
 
-            foreach ($wechatAccountInfos as  $val){
+            foreach ($wechatAccountInfos as $val) {
                 $data['wechat_accounts'][] = [
-                    'id' =>  $val->id,
-                    'appid' =>$val->authorizer_appid,
+                    'id' => $val->id,
+                    'appid' => $val->authorizer_appid,
                     'nick_name' => $val->nick_name,
                     'component_appid' => $val->component_appid
                 ];
-                foreach ($keywords as  $kval){
-                    $has  = $allSet->where( 'keyword',$kval)
-                        ->where( 'wechat_authorization_info_id', $val->id)
-                    ->where( 'status', 1)
-                        ->where('weacht_keyworld_id','<>',$info->id)->first();
-                    if ($has){
-                        $errMsg .=  "{$val->nick_name}已重新配置关键词{$kval};";
+                foreach ($keywords as $kval) {
+                    $has = $allSet->where('keyword', $kval)
+                        ->where('wechat_authorization_info_id', $val->id)
+                        ->where('status', 1)
+                        ->where('weacht_keyworld_id', '<>', $info->id)->first();
+                    if ($has) {
+                        $errMsg .= "{$val->nick_name}已重新配置关键词{$kval};";
                     }
                     $list[] = [
                         'weacht_keyworld_id' => $info->id,
                         'user_id' => $info->user_id,
                         'puser_id' => $info->puser_id,
-                        'miniprogram_id' =>  $info->miniprogram_id,
+                        'miniprogram_id' => $info->miniprogram_id,
                         'appid' => $val->authorizer_appid,
-                        'wechat_authorization_info_id'=> $val->id,
+                        'wechat_authorization_info_id' => $val->id,
                         'nick_name' => $val->nick_name,
                         'keyword' => $kval,
                         'content' => $info->send_content,
@@ -225,43 +225,71 @@ class WechatKeywordsService extends BaseService
                     ];
                 }
             }
-            unset($wechatAccountInfos,$allSet);
+            unset($wechatAccountInfos, $allSet);
         }
         DB::beginTransaction();
         try {
-            WechatAccountKeywordLog::where('weacht_keyworld_id',$id)->update(['status' => 0]);
-            if (!empty($list)){
-                WechatAccountKeywordLog::where('user_id',$info->user_id)
-                    ->whereIn("keyword",$keywords)->whereIn('wechat_authorization_info_id',$wxAuthIds)->update(['status' => 0]);
-                foreach ($list as $val){
-                    WechatAccountKeywordLog::updateOrCreate(['weacht_keyworld_id' => $val['weacht_keyworld_id'],'keyword' => $val['keyword'],'wechat_authorization_info_id' => $val['wechat_authorization_info_id']],$val);
+            WechatAccountKeywordLog::where('weacht_keyworld_id', $id)->update(['status' => 0]);
+            if (!empty($list)) {
+                WechatAccountKeywordLog::where('user_id', $info->user_id)
+                    ->whereIn("keyword", $keywords)->whereIn('wechat_authorization_info_id', $wxAuthIds)->update(['status' => 0]);
+                foreach ($list as $val) {
+                    WechatAccountKeywordLog::updateOrCreate(['weacht_keyworld_id' => $val['weacht_keyworld_id'], 'keyword' => $val['keyword'], 'wechat_authorization_info_id' => $val['wechat_authorization_info_id']], $val);
                 }
             }
-            WechatKeywords::where('id',$id)->update($data);
+            WechatKeywords::where('id', $id)->update($data);
             DB::commit();
-        }catch (\Exception $exception){
+        } catch (\Exception $exception) {
             self::throwErrMsg('操作失败');
         }
-        return "操作成功".$errMsg;
+        return "操作成功" . $errMsg;
     }
 
     public static function getConfig($userId, $puserId, $miniprogramId)
     {
-        $set = MiniprogramWechatGlobalConfig::where(['user_id' =>  $userId,'puser_id' =>  $puserId,'miniprogram_id' =>  $miniprogramId])
-                ->where('type',self::KEYWORD_SET_KEY)->value('value');
-        return $set == 1 ? 1 :0;
+        $set = MiniprogramWechatGlobalConfig::where(['user_id' => $userId, 'puser_id' => $puserId, 'miniprogram_id' => $miniprogramId])
+            ->where('type', self::KEYWORD_SET_KEY)->value('value');
+        return ['data' => $set == 1 ? 1 : 0];
     }
 
     public static function setConfig($param)
     {
         $param['type'] = self::KEYWORD_SET_KEY;
         $res = MiniprogramWechatGlobalConfig::updateOrCreate(
-            ['user_id' =>  $param['user_id'],'puser_id' => $param['puser_id'],'miniprogram_id' =>  $param['miniprogram_id'],'type' => self::KEYWORD_SET_KEY],
+            ['user_id' => $param['user_id'], 'puser_id' => $param['puser_id'], 'miniprogram_id' => $param['miniprogram_id'], 'type' => self::KEYWORD_SET_KEY],
             $param
         );
-        if($res){
-            return "操作成功";
+        if ($res) {
+            return ['msg' => "操作成功"];
         }
         return "操作失败";
     }
+
+    /**
+     *  更新关键词,授权公众号id匹配关键词
+     * name: getKeywordsByWords
+     * @param $keyword
+     * @param $wechatAppId
+     * @return mixed|string
+     * date 2023/07/10 16:31
+     */
+    public static function getKeywordsByWords($keyword, $wechatAppId)
+    {
+        // 匹配关键词
+        $info = WechatAccountKeywordLog::where([
+            "keyword" => $keyword,
+            'status' => 1,
+            'wechat_authorization_info_id' => $wechatAppId,
+        ])->first();
+        if (is_empty($info)) {
+            return "";
+        }
+        $set = self::getConfig($info->user_id,$info->puser_id,$info->miniprogram_id);
+        if (getProp($set,'data') == 0){
+            return  '';
+        }
+        WechatAccountKeywordLog::where('id', $info->id)->increment('send_total', 1);
+        WechatKeywords::where('id', $info->weacht_keyworld_id)->increment('send_total', 1);
+        return $info->content;
+    }
 }

+ 326 - 0
modules/WechatPlatform/Services/WechatMenuService.php

@@ -0,0 +1,326 @@
+<?php
+/**
+ * 公众号菜单
+ * @file:WechatMenuService.php
+ * @Date: 2023/7/11
+ * @Time: 10:53
+ */
+
+
+namespace Modules\WechatPlatform\Services;
+
+use Illuminate\Support\Facades\DB;
+use Modules\Channel\Services\WechatOpenPlatform\WechatOpenPlatformService;
+use Modules\Common\Services\BaseService;
+use Modules\WechatPlatform\Models\WechatAccountMenuDetail;
+use Modules\WechatPlatform\Models\WechatMenu;
+use function PHPUnit\Framework\isNan;
+
+class WechatMenuService extends BaseService
+{
+
+
+    /**
+     *  添加菜单
+     * name: addMenu
+     * @param $param
+     * date 2023/07/11 11:38
+     */
+    public static function addMenu($param)
+    {
+        $res = WechatMenu::create($param);
+        if ($res) {
+            return ['msg' => '操作成功'];
+        }
+        self::throwErrMsg('操作失败');
+    }
+
+    /**
+     *  更新菜单
+     * name: updateMenu
+     * @param $id
+     * @param $param
+     * @return string[]
+     * date 2023/07/12 07:17
+     */
+    public static function updateMenu($id, $param)
+    {
+        $info = WechatMenu::where('id', $id)->where('is_del', 0)->first();
+        if (is_empty($info)) {
+            self::throwErrMsg('该菜单不存在或已删除');
+        }
+        $appIds = WechatAccountMenuDetail::where(['status' => 1, 'menu_id' => $info->id])->pluck('id')->toArray();
+        WechatMenu::where('id', $id)->update($param);
+        $data = [
+            'type' => $param['type'],
+            'content' => $param['content'],
+            'msg_content' => $param['msg_content']
+        ];
+        WechatAccountMenuDetail::where('menu_id', $id)->update($data);
+        // 更新公众号菜单
+        self::createWechatMenus($appIds);
+        return ['msg' => '操作成功'];
+    }
+
+    /**
+     *  创建微信菜单
+     * name: createWechatMenus
+     * @param array $appIds
+     * @return bool
+     * date 2023/07/12 07:16
+     */
+    private static function createWechatMenus(array $appIds)
+    {
+        if (empty($appIds)) {
+            return true;
+        }
+        $info = WechatAccountMenuDetail::query()->whereIn('id', $appIds)->get();
+        foreach ($info as $val) {
+            $app = self::getofficialAccount($info->wechat_authorization_info_id);
+            if ($val->wx_menuid) {
+                // 有菜单则删除菜单
+                $app->menu->delete($info->wx_menuid);
+            }
+            $matchRule = [
+                "client_platform_type" => $info->type == "iso" ? "1" : "2",
+            ];
+            $res = $app->menu->create($info->content, $matchRule);
+            $wxMenuId = getProp($res, 'menuid', "");
+            if ($wxMenuId) {
+                WechatAccountMenuDetail::query()->where('id', $val->id)->update(['wx_menuid' => $wxMenuId]);
+            }
+        }
+        return true;
+    }
+
+    public static function getofficialAccount($id)
+    {
+        $info = WechatOpenPlatformService::getAppInfoById($id);
+        $componentInfo = WechatOpenPlatformService::getComponentInfoByAppid($info->component_appid);
+        $openPlatform = WechatOpenPlatformService::buildApplication($componentInfo);
+        $app = $openPlatform->officialAccount($info->authorizer_appid, getProp($info, 'authorizer_refresh_token'));
+        unset($appInfo);
+        return $app;
+    }
+
+
+    /**
+     * 菜单详情
+     * name: detail
+     * @param $id
+     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
+     * date 2023/07/12 07:17
+     */
+    public static function detail($id)
+    {
+        return WechatMenu::query()->where('id', $id)->first();
+    }
+
+    /**
+     *  公众号列表
+     * name: authList
+     * @param $id
+     * @param $userId
+     * @return mixed
+     * date 2023/07/12 07:16
+     */
+    public static function authList($id, $userId)
+    {
+        $list = DB::table('wechat_authorization_infos')
+            ->where('user_id', $userId)
+            ->select('id', 'nick_name', 'is_enabled')->get();
+        $authList = WechatAccountMenuDetail::where('menu_id', $id)->get();
+        if (!$list->isEmpty()) {
+            foreach ($list as $val) {
+                $val->is_auth = 0;
+                $info = $authList->where('wechat_authorization_info_id', $val->id)->first();
+                if (getProp($info, 'status') == 1) {
+                    $val->is_auth = 1;
+                }
+                if ($val->is_enabled != 1) {
+                    $val->nick_name .= "(取消授权)";
+                }
+                unset($val->is_enabled);
+            }
+        }
+        return $list;
+    }
+
+    /**
+     *   删除
+     * name: del
+     * @param $ids
+     * @return string[]
+     * date 2023/07/12 07:14
+     */
+    public static function del($ids)
+    {
+        WechatMenu::query()->whereIn('id', $ids)->update(['is_del' => 1, 'del_at' => get_date()]);
+        $applyIds = WechatAccountMenuDetail::query()->whereIn('menu_id', $ids)->where('status', 1)->pluck('id')->toArray();
+        if ($applyIds) {
+            WechatAccountMenuDetail::query()->whereIn('menu_id', $ids)->update(['status' => 0]);
+            // 删除菜单
+            self::delWechatAccountMenu($applyIds);
+        }
+        return ['msg' => "操作成功"];
+
+    }
+
+    private static function delWechatAccountMenu(array $applyIds)
+    {
+        $info = WechatAccountMenuDetail::query()->whereIn('id', $applyIds)->get();
+        foreach ($info as $val) {
+
+            if ($val->wx_menuid) {
+                // 有菜单则删除菜单
+                $app = self::getofficialAccount($info->wechat_authorization_info_id);
+                $app->menu->delete($info->wx_menuid);
+            }
+
+            WechatAccountMenuDetail::query()->where('id', $val->id)->update(['wx_menuid' => ""]);
+        }
+        return "操作成功";
+    }
+
+    /**
+     *  分配公众号
+     * name: allocation
+     * @param $id
+     * @param array $wxAuthIds
+     * date 2023/07/12 07:20
+     */
+    public static function allocation($id, $wxAuthIds)
+    {
+        $info = WechatMenu::query()->where('id', $id)->where('is_del', 0)->first();
+        if (is_empty($info)) {
+            self::throwErrMsg('该菜单不存在或已删除');
+        }
+        // 已分配的
+        $appIds = WechatAccountMenuDetail::where(['status' => 1, 'menu_id' => $info->id])->pluck('id')->toArray();
+        $list = [];
+        $delAppId = [];
+        $createAddIp = [];
+
+        if (empty($wxAuthIds)) {
+            $data['wechat_accounts'] = [];
+            $delAppId = $appIds;
+        } else {
+            $wechatAccountInfos = DB::table('wechat_authorization_infos')
+                ->whereIn('id', $wxAuthIds)
+                ->where('is_enabled', 1)
+                ->where('user_id', $info->user_id)
+                ->get();
+            if ($wechatAccountInfos->isEmpty()) {
+                self::throwErrMsg("优化师对提交的公众号没有使用权限");
+            }
+
+            $canNotUsed = $wechatAccountInfos->pluck('id')->toArray();
+            $canNotUsed = array_diff($wxAuthIds, $canNotUsed);
+            if (count($canNotUsed) > 0) {
+                self::throwErrMsg("优化师对id:为:" . implode(',', $canNotUsed) . "的公众号没有使用权限");
+            }
+            foreach ($appIds as $val) {
+                if (!in_array($val, $wxAuthIds)) {
+                    $delAppId[] = $val;
+                }
+            }
+            // $allSet = WechatAccountMenuDetail::query()->where('user_id', $info->user_id)->get();
+
+            foreach ($wechatAccountInfos as $val) {
+                if (!in_array($val->id, $appIds)) {
+                    $createAddIp[] = $val->id;
+                }
+
+                $data['wechat_accounts'][] = [
+                    'id' => $val->id,
+                    'appid' => $val->authorizer_appid,
+                    'nick_name' => $val->nick_name,
+                    'component_appid' => $val->component_appid
+                ];
+                $appIds[] = $val->authorizer_appid;
+                $list[] = [
+                    'menu_id' => $info->id,
+                    'user_id' => $info->user_id,
+                    'puser_id' => $info->puser_id,
+                    'miniprogram_id' => $info->miniprogram_id,
+                    'appid' => $val->authorizer_appid,
+                    'wechat_authorization_info_id' => $val->id,
+                    'nick_name' => $val->nick_name,
+                    'content' => $info->content,
+                    'msg_content' => $info->msg_content,
+                    'status' => 1,
+                ];
+            }
+            unset($wechatAccountInfos, $appIds, $val, $canNotUsed);
+        }
+        DB::beginTransaction();
+        try {
+            if (!empty($list)) {
+                foreach ($list as $val) {
+                    WechatAccountMenuDetail::updateOrCreate(
+                        [
+                            'menu_id' => $val['menu_id'],
+                            'miniprogram_id' => $val['miniprogram_id'],
+                            'wechat_authorization_info_id' => $val['wechat_authorization_info_id']
+                        ], $val);
+                }
+            } else {
+                WechatAccountMenuDetail::where('menu_id', $id)->update(['status' => 0]);
+            }
+            if (!empty($delAppId)) {
+                WechatAccountMenuDetail::whereIn('id', $delAppId)->update(['status' => 0]);
+            }
+            WechatMenu::query()->where('id', $id)->update($data);
+            DB::commit();
+        } catch (\Exception $exception) {
+            self::throwErrMsg('操作失败');
+        }
+        if (!empty($createAddIp)) {
+            self::createWechatMenus($createAddIp);
+        }
+        if (!empty($delAppId)) {
+            self::delWechatAccountMenu($delAppId);
+        }
+        return ['msg' => "操作成功"];
+    }
+
+    /**
+     * 列表
+     * name: list
+     * @param array $param
+     * date 2023/07/12 07:43
+     */
+    public static function list(array $param)
+    {
+        $sql = self::getQuery($param)->orderBy('id', 'desc');
+        $isAll = getProp($param, 'is_all', false);
+        if ($isAll) {
+            $list = $sql->get();
+        } else {
+            $list = $sql->paginate(getProp($param, 'limit', 10));
+        }
+        return $list;
+    }
+
+    private static function getQuery(array $param)
+    {
+        $sql = WechatMenu::query()->where('is_del', 0);
+        if (getProp($param, 'puser_id')) {
+            $sql->where('puser_id', $param['puser_id']);
+        }
+        if (getProp($param, 'user_id')) {
+            $sql->where('user_id', $param['user_id']);
+        }
+        if (getProp($param, 'keyword')) {
+            $sql->where('keyword', "like", "%" . $param['keyword'] . "%");
+        }
+        if (getProp($param, 'miniprogram_id')) {
+            $sql->where('miniprogram_id', $param['miniprogram_id']);
+        }
+        if (getProp($param, 'wechat_authorization_info_id')) {
+            $sql->whereJsonContains('wechat_accounts->id', $param['wechat_authorization_info_id']);
+        }
+        return $sql;
+    }
+
+}

+ 29 - 3
modules/WechatPlatform/Services/WechatSubscribeService.php

@@ -35,7 +35,7 @@ class WechatSubscribeService extends BaseService
     {
         $set = MiniprogramWechatGlobalConfig::where(['user_id' =>  $userId,'puser_id' =>  $puserId,'miniprogram_id' =>  $miniprogramId])
             ->where('type',self::KEYWORD_SET_KEY)->value('value');
-        return $set == 1 ? 1 :0;
+        return ['data' => $set == 1 ? 1 : 0];
     }
 
     /**
@@ -53,7 +53,7 @@ class WechatSubscribeService extends BaseService
             $param
         );
         if($res){
-            return "操作成功";
+            return ['msg' => "操作成功"];
         }
         self::throwErrMsg("操作失败");
     }
@@ -62,7 +62,7 @@ class WechatSubscribeService extends BaseService
     {
         $res = WechatSubscribeMsg::create($param);
         if ($res) {
-            return "操作成功";
+            return ['msg' => "操作成功"];
         }
         self::throwErrMsg("操作失败");
     }
@@ -265,4 +265,30 @@ class WechatSubscribeService extends BaseService
         return $sql;
     }
 
+    /**
+     * 获取关注回复内容
+     * name: getContent
+     * @param $wechatAppId
+     * @return mixed|string
+     * date 2023/07/10 18:37
+     */
+    public static function getContent($wechatAppId)
+    {
+        $info = WechatAccountSubscribeDetail::where([
+            'status' => 1,
+            'wechat_authorization_info_id' => $wechatAppId,
+        ])->first();
+        if (is_empty($info)) {
+            return "";
+        }
+        $set = self::getConfig($info->user_id,$info->puser_id,$info->miniprogram_id);
+        if (getProp($set,'data') == 0){
+            return  '';
+        }
+        WechatAccountSubscribeDetail::where('id', $info->id)->increment('send_total', 1);
+        WechatSubscribeMsg::where('id', $info->weacht_keyworld_id)->increment('send_total', 1);
+
+        return $info->content;
+    }
+
 }

+ 21 - 0
modules/WechatPlatform/routes/route.php

@@ -5,6 +5,7 @@ use Illuminate\Support\Facades\Route;
 use Modules\WechatPlatform\Http\Controllers\KFMessageController;
 use Modules\WechatPlatform\Http\Controllers\WechatAuthorizationInfoController;
 use Modules\WechatPlatform\Http\Controllers\CommonController;
+use Modules\WechatPlatform\Http\Controllers\WechatMenuController;
 use Modules\WechatPlatform\Http\Controllers\WechatSubscribeController;
 use Modules\WechatPlatform\Http\Controllers\WechatKeywordsController;
 
@@ -75,4 +76,24 @@ Route::prefix('wechatPlatform')->group(function(){
         Route::any("auth_list/{id}",[WechatSubscribeController::class,'authList']);
     });
 
+    // 公众号菜单
+    Route::prefix('menu')->group(function (){
+      // 列表
+        Route::any("list",[WechatMenuController::class,'list']);
+        // 添加
+        Route::post('add',[WechatMenuController::class,'add']);
+        // 编辑
+        Route::post('edit/{id}',[WechatMenuController::class,'edit']);
+        // 详情
+        Route::any('detail/{id}',[WechatMenuController::class,'detail']);
+        // 删除
+        Route::any('del',[WechatMenuController::class,'del']);
+        // 配置公众号
+        Route::post('allocation/{id}',[WechatMenuController::class,'allocation']);
+        // 公众号配置选择项
+        Route::any("auth_list/{id}",[WechatMenuController::class,'authList']);
+        // 测试
+        Route::any("test",[WechatMenuController::class,'test']);
+    });
+
 });

+ 0 - 2
storage/logs/.gitignore

@@ -1,2 +0,0 @@
-*
-!.gitignore