Browse Source

社媒对facebook

moshaorui 1 day ago
parent
commit
3cb2cf409b

+ 42 - 24
app/Distributor/Actions/SmmAddAccount.php

@@ -2,44 +2,62 @@
 namespace App\Distributor\Actions;
 
 use App\Distributor\Forms\ImportProduct;
+use App\Services\SmmService;
+use Dcat\Admin\Grid\RowAction;
 use Dcat\Admin\Grid\Tools\AbstractTool;
 use Dcat\Admin\Widgets\Modal;
 use App\Distributor\Forms\SmmAddAccount as SmmAddAccountForm;
+use Illuminate\Http\Request;
 
-class SmmAddAccount extends AbstractTool
+class SmmAddAccount extends RowAction
 {
-    protected $style = 'btn btn-primary';
-
-    protected $title = 'add_platform_account';
 
+    /**
+     * 返回字段标题
+     *
+     * @return string
+     */
     public function title()
     {
-        return '<i class="feather icon-user-plus"></i> &nbsp;'.admin_trans('admin.add_platform_account');
+        return admin_trans_label('add_platform_account');
     }
 
-    public function render()
+    /**
+     * 处理请求
+     *
+     */
+    public function handle(Request $request)
     {
-        // 实例化表单类
-        $form = SmmAddAccountForm::make();
-
-        return Modal::make()
-            ->lg()
-            ->title(admin_trans_label($this->title))
-            ->body($form)
-            // 因为此处使用了表单异步加载功能,所以一定要用 onLoad 方法
-            // 如果是非异步方式加载表单,则需要改成 onShow 方法
-            ->button($this->getButtonHTML());
+        // 获取 parameters 方法传递的参数
+        $title = $request->get('title');
+        if ($title) {
+            //跳转到媒体受权页面
+            $ssmService = new SmmService($title);
+            $result = $ssmService->login();
+            if ($result['status']) {
+                // 返回 JS 代码触发新窗口打开
+                $url = $result['data']['url'];
+
+                return $this->response()->script(
+                    "window.open('{$url}', '_blank')"
+                );
+            }
+            return $this
+                ->response()
+                ->error('获取授权失败,请检查媒体名称是否正确!');
+        } else {
+            return $this
+                ->response()
+                ->error('媒体名称不能为空');
+        }
     }
 
-    protected function getButtonHTML()
+    public function parameters()
     {
-        $title= $this->title();
-        return <<<HTML
-        <button class="btn btn-success">
-            <i class="feather"></i> {$title}
-        </button>
-        HTML;
+        return [
+            // 发送当前行 username 字段数据到接口
+            'title' => $this->row->title,
+        ];
     }
 
-
 }

+ 43 - 5
app/Distributor/Controllers/SmmUserAccountController.php

@@ -4,12 +4,14 @@ namespace App\Distributor\Controllers;
 
 use App\Distributor\Actions\SmmAddAccount;
 use App\Distributor\Repositories\SmmUserAccount;
+use App\Services\SmmService;
 use Dcat\Admin\Form;
 use Dcat\Admin\Grid;
 use Dcat\Admin\Show;
 use Dcat\Admin\Http\Controllers\AdminController;
 use Dcat\Admin\Layout\Content;
 use Dcat\Admin\Admin;
+use Illuminate\Http\Request;
 
 class SmmUserAccountController extends AdminController
 {
@@ -33,9 +35,8 @@ class SmmUserAccountController extends AdminController
     {
         return Grid::make(new SmmUserAccount(), function (Grid $grid) {
             $grid->column('id')->sortable();
-            $grid->column('user_name');
+            $grid->column('title')->tree();
             $grid->column('access_token');
-            $grid->column('media_name');
             $grid->column('created_at');
             $grid->column('updated_at')->sortable();
             $grid->filter(function (Grid\Filter $filter) {
@@ -43,16 +44,53 @@ class SmmUserAccountController extends AdminController
                 $filter->expand();
                 $filter->like('user_name')->width(2);
             });
-            //授权按钮
             // 传入数组
             $grid->rightTools([
-                new SmmAddAccount(),
+            //    new SmmAddAccount(),
             ]);
 
+            $grid->actions(function (Grid\Displayers\Actions $actions) {
+                $actions->disableEdit();
+                $actions->disableQuickEdit();
+                $actions->disableView();
+                $dist_id = $actions->row->dist_id;
+                if ($dist_id == 0) {
+                    $actions->append(new SmmAddAccount());
+                    $actions->disableDelete();
+                }
+            });
+
             $grid->disableCreateButton();
             $grid->disableEditButton();
-            $grid->model()->where('dist_id', getDistributorId())->orderBy('media_name', 'asc')->orderBy('id', 'desc');
+            $grid->disableViewButton();
+            $grid->model()->whereIn('dist_id', [0,getDistributorId()])->orderBy('title', 'asc')->orderBy('id', 'desc');
         });
     }
 
+
+    /*
+     * 社媒回调接口
+     */
+    public function callback($mediaName,Request $request)
+    {
+        try {
+            $ssmService = new SmmService($mediaName);
+            $result = $ssmService->loginCallback($request);
+            dd($result);
+            if ($result['status']) {
+                $accessToken = $result['data']['access_token'];
+                $userName = $result['data']['user_name'];
+                $userId = $result['data']['user_id'];
+                SmmUserAccount::createAccountIfMediaExists($mediaName, $userId,$userName, $accessToken);
+                return response()->json(['code' => 1, 'msg' => 'success']);
+            } else {
+                return response()->json(['code' => 0,'msg' => $result['data']]);
+            }
+        } catch (\Exception $e) {
+            return response()->json(['code' => 0,'msg' => 'error'.$e->getMessage()]);
+        }
+    }
+
+
+
 }

+ 0 - 62
app/Distributor/Forms/SmmAddAccount.php

@@ -1,62 +0,0 @@
-<?php
-
-namespace App\Distributor\Forms;
-use App\Distributor\Repositories\DistProductCategory;
-use App\Distributor\Repositories\RpcAlbum;
-use App\Libraries\CommonHelper;
-use App\Models\DistProduct;
-use App\Models\DistProductImage;
-use App\Services\SmmService;
-use Dcat\Admin\Widgets\Form;
-
-
-class SmmAddAccount extends Form
-{
-    public function handle(array $input)
-    {
-        // 处理表单提交逻辑
-        $mediaName = $input['media_name'];
-        if ($mediaName) {
-            //跳转到媒体受权页面
-            $ssmService = new SmmService($mediaName);
-            $result = $ssmService->login();
-            if ($result['status']) {
-                // 返回 JS 代码触发新窗口打开
-                $url = $result['data']['url'];
-
-                return $this->response()->script(
-                    "window.open('{$url}', '_blank')"
-                );
-            }
-            return $this
-                ->response()
-                ->error('获取授权失败,请检查媒体名称是否正确!');
-        } else {
-            return $this
-                ->response()
-                ->error('媒体名称不能为空');
-        }
-    }
-
-
-    /**
-     * Build a form here.
-     */
-    public function form()
-    {
-        // 设置隐藏表单,传递用户id
-        $this->select('media_name')
-            ->options(config('dictionary.media_list'))
-            ->required();
-    }
-
-    /**
-     * The data of the form.
-     *
-     * @return array
-     */
-    public function default()
-    {
-        return [];
-    }
-}

+ 30 - 0
app/Distributor/Repositories/SmmUserAccount.php

@@ -3,6 +3,7 @@
 namespace App\Distributor\Repositories;
 
 use App\Models\SmmUserAccount as Model;
+use Carbon\Carbon;
 use Dcat\Admin\Repositories\EloquentRepository;
 
 class SmmUserAccount extends EloquentRepository
@@ -13,4 +14,33 @@ class SmmUserAccount extends EloquentRepository
      * @var string
      */
     protected $eloquentClass = Model::class;
+
+    /**
+     * 插入新的社媒账号(仅在找到对应社媒时插入)
+     *
+     * @param string $mediaName    要查找的社媒名称
+     * @param string $accountName 要插入的账号名称
+     * @param string $accessToken 访问令牌
+     * @return Model|null         新创建的模型实例或null
+     */
+    public static function createAccountIfMediaExists($mediaName, $accountId,$accountName, $accessToken)
+    {
+        $model = new Model();
+        // 查找匹配的社媒记录
+        $mediaRecord = $model->where('title', $mediaName)->first();
+        if (!$mediaRecord) {
+            return null;
+        }
+        // 创建新账号并关联父级
+        $data = [
+            'account_id'   => $accountId,
+            'title'        => $accountName,
+            'access_token' => $accessToken,
+            'parent_id'    => $mediaRecord->id,
+            'created_at'   => Carbon::now(),  // 自动生成时间戳
+            'updated_at'   => Carbon::now(),
+        ];
+        return $model->insert($data);
+    }
+
 }

+ 13 - 0
app/Distributor/routes.php

@@ -93,3 +93,16 @@ app('router')->group($attributes, function ($router) {
     $router->post('editor-md/upload', function () {exit;})->name('editor-md.upload');
     $router->post('tinymce/upload', 'App\Http\Controllers\TinymceController@upload')->name('tinymce.upload');
 });
+
+
+
+/*
+ * 对外开放的接口
+ */
+Route::group([
+    'prefix'     => 'open',
+    'namespace'  => config('admin.route.namespace'),
+], function (Router $router) {
+    //社媒回调
+    $router->get('callback/{name}', 'SmmUserAccountController@callback');
+});

+ 6 - 1
app/Models/SmmUserAccount.php

@@ -4,11 +4,16 @@ namespace App\Models;
 
 use Dcat\Admin\Traits\HasDateTimeFormatter;
 
+use Dcat\Admin\Traits\ModelTree;
 use Illuminate\Database\Eloquent\Model;
 
 class SmmUserAccount extends Model
 {
 	use HasDateTimeFormatter;
+    use ModelTree;
+
     protected $table = 'smm_user_account';
-    
+
+
+
 }

+ 53 - 2
app/Services/Smm/FacebookService.php

@@ -30,7 +30,7 @@ class FacebookService implements SmmPlatformInterface
         $helper = $this->fb->getRedirectLoginHelper();
         $permissions = ['public_profile','email'];
         $distSiteUrl = env('DIST_SITE_URL');
-        $loginUrl = $helper->getLoginUrl('https://internal-dist.mietubl.com.cn/callback/facebook', $permissions);
+        $loginUrl = $helper->getLoginUrl(env('DIST_SITE_URL').'/open/callback/facebook', $permissions);
         return ['status'=>true, 'data' => ['url'=>$loginUrl]];
     }
 
@@ -54,7 +54,8 @@ class FacebookService implements SmmPlatformInterface
             // 可选:将短期令牌转换为长期令牌(有效期约60天)
             $oAuth2Client = $this->fb->getOAuth2Client();
             $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
-            return ['status' => true, 'data' => ['access_token' => $longLivedAccessToken]];
+            $useriInfo = $this->getFacebookUser($longLivedAccessToken);
+            return ['status' => true, 'data' => ['access_token' => $longLivedAccessToken,'user_name'=>$useriInfo['name'],'user_id'=>$useriInfo['id']]];
         } else {
             return ['status' => false, 'data' => '无法获取访问令牌'];
         }
@@ -115,4 +116,54 @@ class FacebookService implements SmmPlatformInterface
     }
 
 
+    /**
+     * 获取Facebook用户信息
+     * @param string $accessToken
+     * @return array [
+     *     'name' => string,
+     *     'id' => string,
+     *     'error' => string|null
+     * ]
+     */
+    public function getFacebookUser($accessToken)
+    {
+        try {
+            // 验证并设置访问令牌
+            $this->fb->setDefaultAccessToken($accessToken);
+
+            // 发送请求获取用户信息
+            $response = $this->fb->get('/me?fields=name,id');
+            $userNode = $response->getGraphUser();
+
+            return [
+                'name' => $userNode->getName(),
+                'id' => $userNode->getId(),
+                'error' => null
+            ];
+
+        } catch (FacebookResponseException $e) {
+            // API 响应错误处理
+            return [
+                'name' => null,
+                'id' => null,
+                'error' => 'Graph API Error: ' . $e->getMessage()
+            ];
+        } catch (FacebookSDKException $e) {
+            // SDK 错误处理
+            return [
+                'name' => null,
+                'id' => null,
+                'error' => 'SDK Error: ' . $e->getMessage()
+            ];
+        } catch (Exception $e) {
+            // 其他错误处理
+            return [
+                'name' => null,
+                'id' => null,
+                'error' => 'General Error: ' . $e->getMessage()
+            ];
+        }
+    }
+
+
 }

+ 1 - 0
lang/zh_CN/global.php

@@ -218,6 +218,7 @@ return [
         'audit_success'      => '审核成功',
         'product_audit'      => '产品审核',
         'add_platform_account' => '添加平台账号',
+
     ],
     'options' => [
         //