123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365 |
- <?php
- namespace App\Services;
- use App\Console\Commands\AssignJuxingAdToRds;
- use App\Models\JinniuAccountInfo;
- use App\Models\JinniuAdAccount;
- use App\Models\JuxingAccountInfo;
- use App\Models\JuxingAdAccount;
- use App\Models\Sys\SysCustomerAdver;
- use App\Models\Sys\SysUserAdver;
- use App\Models\Sys\SysUsers;
- use App\Support\EmailQueue;
- use App\Support\Log;
- use Illuminate\Support\Facades\DB;
- use kwaiSDK\JinNiu;
- use kwaiSDK\PubUse;
- class CallbackService
- {
- public static function jinniuAccountAuth($authCode, $adminId)
- {
- $jinniuConf = config('kwai')['jinniu'];
- $pubuse = new PubUse($jinniuConf['app_id'], $jinniuConf['secret']);
- /**
- {
- "code":0,
- "message":"OK",
- "data":{
- "access_token":"1221fde0c81fb825d7af04ac0f8f96b3",
- "refresh_token_expires_in":2591999,
- "refresh_token":"9adfcc6450e94872d133aa20b84cbde6",
- "advertiser_ids":[
- 10497747,
- 10497748,
- 10497749,
- 10497750,
- 10497751,
- 11349879
- ],
- "access_token_expires_in":86399,
- "advertiser_id":0
- },
- "request_id":"73a289a10c49411a85ec0b61be97ae1e"
- }
- */
- // 获取accessToken
- $userAuthorize = $pubuse->authorize()->accessToken(['auth_code' => $authCode]);
- if (!isset($userAuthorize['code']) || $userAuthorize['code'] !== 0) {
- Log::info('磁力金牛授权失败', $userAuthorize, 'CallbackService');
- return false;
- }
- return self::saveJinniuAccount($adminId, $userAuthorize, 1);
- }
- public static function saveJinniuAccount($adminId, $userAuthorize, $type)
- {
- $data = $userAuthorize['data'] ?? [];
- if (empty($data)) {
- Log::info('磁力金牛存储授权信息为空', $userAuthorize, 'CallbackService');
- return false;
- }
- // 存储accountInfo
- $accountInfo = self::saveJinniuAccountInfo($adminId, $data, $type);
- if (empty($accountInfo)) {
- Log::error('磁力金牛存储授权信息失败', $data, 'CallbackService');
- return false;
- }
- // 存储adAccount
- $advertiserIds = isset($accountInfo->advertiser_ids) ?
- explode('|', trim($accountInfo->advertiser_ids, '|')) : [];
- if (empty($accountInfo->advertiser_id)) {
- array_unshift($advertiserIds, $accountInfo->advertiser_id);
- $advertiserIds = array_unique($advertiserIds);
- }
- if (empty($advertiserIds)) return false;
- foreach ($advertiserIds as $advertiserId) {
- $tokenId = $accountInfo->id;
- $accessToken = $accountInfo->access_token;
- self::saveJinniuAdAccount($advertiserId, $tokenId, $accessToken, $type);
- }
- return true;
- }
- public static function juxingAccountAuth($authCode, $state)
- {
- $juxingConf = config('kwai')['juxing'];
- $pubuse = new PubUse($juxingConf['app_id'], $juxingConf['secret']);
- // 获取accessToken
- $userAuthorize = $pubuse->authorize()->accessToken(['auth_code' => $authCode]);
- Log::info('授权回调结果记录', ['auth_code' => $authCode, 'state' => $state, 'user_authorize' => $userAuthorize], 'jxAccountAuth');
- if (!isset($userAuthorize['code']) || $userAuthorize['code'] !== 0) {
- Log::error('磁力聚星授权失败', $userAuthorize, 'CallbackService');
- return false;
- }
- // 根据token获取授权的广告主列表
- $advertiserList = self::getApprovalList($juxingConf, $userAuthorize);
- $stateInfo = json_decode(base64_decode($state), true);
- return self::saveJuxingAccount($stateInfo, $userAuthorize, $advertiserList, 1);
- }
- public static function getApprovalList($juxingConf, $userAuthorize, $retry = 0) {
- $accessToken = $userAuthorize['data']['access_token'] ?? '';
- $requestUrl = 'https://ad.e.kuaishou.com/rest/openapi/oauth2/authorize/approval/list';
- $page = 1;
- $pageSize = 200;
- $params = [
- 'app_id' => $juxingConf['app_id'],
- 'secret' => $juxingConf['secret'],
- 'access_token' => $accessToken,
- 'page_no' => $page,
- 'page_size' => $pageSize,
- ];
- $response = HttpService::httpPost($requestUrl, json_encode($params), true);
- if(empty($response) && $retry < 3) {
- $retry++;
- sleep(1);
- return self::getApprovalList($juxingConf, $userAuthorize, $retry);
- }
- Log::info('获取token授权的广告主列表', [
- 'user_authorize' => $userAuthorize, 'response' => $response,
- ], 'getApprovalList');
- $response = json_decode($response, 1);
- if(isset($response['code']) && 1 == $response['code']) {
- return $response['data']['details'] ?? '';
- } else if (isset($response['code']) && in_array($response['code'], ['30020001']) && $retry < 3) {
- sleep(1);
- $retry++;
- return self::getApprovalList($juxingConf, $userAuthorize, $retry);
- }
- EmailQueue::rPush('获取token授权的广告账户列表异常', json_encode(['user_authorize' => $userAuthorize, 'response' => $response]),
- ['song.shen@kuxuan-inc.com'], '聚星系统');
- return [];
- }
- public static function saveJuxingAccount($stateInfo, $userAuthorize, $advertiserList, $type)
- {
- $data = $userAuthorize['data'] ?? [];
- if (empty($data)) {
- Log::info('磁力聚星存储授权信息为空', $userAuthorize, 'CallbackService');
- return false;
- }
- if(isset($data['advertiser_ids']) && !empty($data['advertiser_ids'])){
- foreach($data['advertiser_ids'] as $advertiser_id){
- $data['advertiser_id'] = $advertiser_id;
- self::saveJuxingMoreAccount($stateInfo, $data, $type);
- }
- } else if(!empty($data['advertiser_id'])) {
- self::saveJuxingMoreAccount($stateInfo, $data, $type);
- } else if(!empty($advertiserList)){
- foreach($advertiserList as $advertiserId) {
- $data['advertiser_id'] = $advertiserId;
- self::saveJuxingMoreAccount($stateInfo, $data, $type);
- }
- }
- return true;
- }
- public static function saveJuxingMoreAccount($stateInfo, $data, $type)
- {
- // 存储accountInfo
- $adminId = $stateInfo['admin_id'] ?? null;
- $accountInfo = self::saveJuxingAccountInfo($adminId, $data, $type);
- if (empty($accountInfo)) {
- Log::error('磁力聚星存储授权信息失败', ['state_info' => $stateInfo, 'data' => $data, 'type' => $type], 'CallbackService');
- return false;
- }
- $advertiserId = $accountInfo->advertiser_id;
- // 存储adAccount
- $tokenId = $accountInfo->id;
- $nickName = $stateInfo['nick_name'] ?? null;
- self::saveJuxingAdAccount($advertiserId, $tokenId, $nickName, $type);
- // 存储关联信息
- if ($type == 1) {
- $customerId = $stateInfo['customer_id'] ?? null;
- self::saveJuxingRelaData($advertiserId, $customerId, $adminId);
- // 存入redis
- (new AssignJuxingAdToRds())->start($advertiserId);
- }
- }
- protected static function saveJinniuAccountInfo($adminId, $data, $type)
- {
- $accountInfo = new JinniuAccountInfo([
- // 'admin_id' => $adminId,
- 'advertiser_id' => $data['advertiser_id'] ?? null,
- 'advertiser_ids' => !empty($data['advertiser_ids']) ? implode('|', $data['advertiser_ids']) : null,
- 'access_token' => $data['access_token'] ?? null,
- 'refresh_token' => $data['refresh_token'] ?? null,
- 'access_token_expires_at' => date('Y-m-d H:i:s', time() + $data['access_token_expires_in'] - 3),
- 'refresh_token_expires_at' => date('Y-m-d H:i:s', time() + $data['refresh_token_expires_in'] - 3),
- 'type' => $type
- ]);
- $accountInfo->save();
- return $accountInfo;
- }
- protected static function saveJinniuAdAccount($advertiserId, $tokenId, $accessToken, $type)
- {
- $adAccount = JinniuAdAccount::query()->where('advertiser_id', $advertiserId)->first();
- if (empty($adAccount)) {
- $jinniu = new JinNiu($accessToken);
- $adAccountInfo = $jinniu->account()->qualificationInfo([
- 'advertiser_id' => $advertiserId
- ]);
- if (!isset($adAccountInfo['code']) || $adAccountInfo['code'] !== 0) {
- Log::error('磁力金牛获取广告主信息失败', $adAccountInfo, 'CallbackService');
- return false;
- }
- $data = $adAccountInfo['data'];
- $adAccount = new JinniuAdAccount([
- 'advertiser_id' => $advertiserId,
- 'ks_id' => $data['ks_id'],
- 'user_name' => $data['user_name'] ?? null,
- 'company_name' => $data['company_name'] ?? null,
- 'industry_l1_id' => $data['industry_l1_id'] ?? null,
- 'industry_l1_name' => $data['industry_l1_name'] ?? null,
- 'industry_l2_id' => $data['industry_l2_id'] ?? null,
- 'industry_l2_name' => $data['industry_l2_name'] ?? null
- ]);
- }
- $adAccount->token_id = $tokenId;
- // 重新授权会更新enable
- if ($type == 1) $adAccount->enable = 1;
- $adAccount->save();
- }
- protected static function saveJuxingAccountInfo($adminId, $data, $type)
- {
- $userId = $data['user_id'] ?? null;
- if (empty($userId)) return false;
- $accountInfo = new JuxingAccountInfo([
- 'admin_id' => $adminId,
- 'user_id' => $userId,
- 'advertiser_id' => $data['advertiser_id'] ?? null,
- 'access_token' => $data['access_token'] ?? null,
- 'refresh_token' => $data['refresh_token'] ?? null,
- 'access_token_expires_at' => date('Y-m-d H:i:s', time() + $data['access_token_expires_in'] - 3),
- 'refresh_token_expires_at' => date('Y-m-d H:i:s', time() + $data['refresh_token_expires_in'] - 3),
- 'type' => $type
- ]);
- $accountInfo->save();
- return $accountInfo;
- }
- protected static function saveJuxingAdAccount($advertiserId, $tokenId, $nickName, $type)
- {
- $adAccount = JuxingAdAccount::query()
- ->where('advertiser_id', $advertiserId)
- ->first();
- if (empty($adAccount)) {
- $adAccount = new JuxingAdAccount([
- 'advertiser_id' => $advertiserId
- ]);
- }
- $adAccount->token_id = $tokenId;
- // 重新授权会更新enable
- if ($type == 1) {
- $adAccount->nick_name = $nickName.'('. $advertiserId .')';
- $adAccount->enable = 1;
- }
- return $adAccount->save();
- }
- protected static function saveJuxingRelaData($advertiserId, $customerId, $adminId)
- {
- if (!isset($advertiserId, $customerId, $adminId)) {
- Log::info('参数传递缺失', [
- 'param' => [
- 'advertiserId' => $advertiserId,
- 'customerId' => $customerId,
- 'adminId' => $adminId,
- ]
- ], 'CallbackService');
- return true;
- }
- $cusAccountInfo = SysCustomerAdver::query()
- ->where('advertiser_id', $advertiserId)
- ->where('enable', 1)
- ->first();
- if (!empty($cusAccountInfo) && ($cusAccountInfo->customer_id != $customerId)) {
- Log::info('账号不能重复授权不同客户', [
- 'param' => [
- 'advertiserId' => $advertiserId,
- 'customerId' => $customerId,
- 'adminId' => $adminId,
- ]
- ], 'CallbackService');
- return true;
- }
- DB::beginTransaction();
- try {
- // 建立单层账户关系
- /*
- SysUserAdver::query()
- ->updateOrInsert([
- 'sys_user_id' => $adminId,
- 'advertiser_id' => $advertiserId
- ], ['enable' => 1]);
- */
- // 建立客户与账号的关系
- SysCustomerAdver::query()->updateOrInsert([
- 'customer_id' => $customerId,
- 'advertiser_id' => $advertiserId
- ], ['enable' => 1]);
- DB::commit();
- return true;
- } catch (\Throwable $e) {
- Log::error('数据关系建立失败:'.$e->getMessage(), [
- 'param' => [
- 'advertiserId' => $advertiserId,
- 'customerId' => $customerId,
- 'adminId' => $adminId,
- ],
- 'trace' => $e->getTrace()
- ], 'CallbackService');
- DB::rollBack();
- return false;
- }
- }
- }
|