No Description

CallbackService.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. <?php
  2. namespace App\Services;
  3. use App\Console\Commands\AssignJuxingAdToRds;
  4. use App\Models\JinniuAccountInfo;
  5. use App\Models\JinniuAdAccount;
  6. use App\Models\JuxingAccountInfo;
  7. use App\Models\JuxingAdAccount;
  8. use App\Models\Sys\SysCustomerAdver;
  9. use App\Models\Sys\SysUserAdver;
  10. use App\Models\Sys\SysUsers;
  11. use App\Support\EmailQueue;
  12. use App\Support\Log;
  13. use Illuminate\Support\Facades\DB;
  14. use kwaiSDK\JinNiu;
  15. use kwaiSDK\PubUse;
  16. class CallbackService
  17. {
  18. public static function jinniuAccountAuth($authCode, $adminId)
  19. {
  20. $jinniuConf = config('kwai')['jinniu'];
  21. $pubuse = new PubUse($jinniuConf['app_id'], $jinniuConf['secret']);
  22. /**
  23. {
  24. "code":0,
  25. "message":"OK",
  26. "data":{
  27. "access_token":"1221fde0c81fb825d7af04ac0f8f96b3",
  28. "refresh_token_expires_in":2591999,
  29. "refresh_token":"9adfcc6450e94872d133aa20b84cbde6",
  30. "advertiser_ids":[
  31. 10497747,
  32. 10497748,
  33. 10497749,
  34. 10497750,
  35. 10497751,
  36. 11349879
  37. ],
  38. "access_token_expires_in":86399,
  39. "advertiser_id":0
  40. },
  41. "request_id":"73a289a10c49411a85ec0b61be97ae1e"
  42. }
  43. */
  44. // 获取accessToken
  45. $userAuthorize = $pubuse->authorize()->accessToken(['auth_code' => $authCode]);
  46. if (!isset($userAuthorize['code']) || $userAuthorize['code'] !== 0) {
  47. Log::info('磁力金牛授权失败', $userAuthorize, 'CallbackService');
  48. return false;
  49. }
  50. return self::saveJinniuAccount($adminId, $userAuthorize, 1);
  51. }
  52. public static function saveJinniuAccount($adminId, $userAuthorize, $type)
  53. {
  54. $data = $userAuthorize['data'] ?? [];
  55. if (empty($data)) {
  56. Log::info('磁力金牛存储授权信息为空', $userAuthorize, 'CallbackService');
  57. return false;
  58. }
  59. // 存储accountInfo
  60. $accountInfo = self::saveJinniuAccountInfo($adminId, $data, $type);
  61. if (empty($accountInfo)) {
  62. Log::error('磁力金牛存储授权信息失败', $data, 'CallbackService');
  63. return false;
  64. }
  65. // 存储adAccount
  66. $advertiserIds = isset($accountInfo->advertiser_ids) ?
  67. explode('|', trim($accountInfo->advertiser_ids, '|')) : [];
  68. if (empty($accountInfo->advertiser_id)) {
  69. array_unshift($advertiserIds, $accountInfo->advertiser_id);
  70. $advertiserIds = array_unique($advertiserIds);
  71. }
  72. if (empty($advertiserIds)) return false;
  73. foreach ($advertiserIds as $advertiserId) {
  74. $tokenId = $accountInfo->id;
  75. $accessToken = $accountInfo->access_token;
  76. self::saveJinniuAdAccount($advertiserId, $tokenId, $accessToken, $type);
  77. }
  78. return true;
  79. }
  80. public static function juxingAccountAuth($authCode, $state)
  81. {
  82. $juxingConf = config('kwai')['juxing'];
  83. $pubuse = new PubUse($juxingConf['app_id'], $juxingConf['secret']);
  84. // 获取accessToken
  85. $userAuthorize = $pubuse->authorize()->accessToken(['auth_code' => $authCode]);
  86. Log::info('授权回调结果记录', ['auth_code' => $authCode, 'state' => $state, 'user_authorize' => $userAuthorize], 'jxAccountAuth');
  87. if (!isset($userAuthorize['code']) || $userAuthorize['code'] !== 0) {
  88. Log::error('磁力聚星授权失败', $userAuthorize, 'CallbackService');
  89. return false;
  90. }
  91. // 根据token获取授权的广告主列表
  92. $advertiserList = self::getApprovalList($juxingConf, $userAuthorize);
  93. $stateInfo = json_decode(base64_decode($state), true);
  94. return self::saveJuxingAccount($stateInfo, $userAuthorize, $advertiserList, 1);
  95. }
  96. public static function getApprovalList($juxingConf, $userAuthorize, $retry = 0) {
  97. $accessToken = $userAuthorize['data']['access_token'] ?? '';
  98. $requestUrl = 'https://ad.e.kuaishou.com/rest/openapi/oauth2/authorize/approval/list';
  99. $page = 1;
  100. $pageSize = 200;
  101. $params = [
  102. 'app_id' => $juxingConf['app_id'],
  103. 'secret' => $juxingConf['secret'],
  104. 'access_token' => $accessToken,
  105. 'page_no' => $page,
  106. 'page_size' => $pageSize,
  107. ];
  108. $response = HttpService::httpPost($requestUrl, json_encode($params), true);
  109. if(empty($response) && $retry < 3) {
  110. $retry++;
  111. sleep(1);
  112. return self::getApprovalList($juxingConf, $userAuthorize, $retry);
  113. }
  114. Log::info('获取token授权的广告主列表', [
  115. 'user_authorize' => $userAuthorize, 'response' => $response,
  116. ], 'getApprovalList');
  117. $response = json_decode($response, 1);
  118. if(isset($response['code']) && 1 == $response['code']) {
  119. return $response['data']['details'] ?? '';
  120. } else if (isset($response['code']) && in_array($response['code'], ['30020001']) && $retry < 3) {
  121. sleep(1);
  122. $retry++;
  123. return self::getApprovalList($juxingConf, $userAuthorize, $retry);
  124. }
  125. EmailQueue::rPush('获取token授权的广告账户列表异常', json_encode(['user_authorize' => $userAuthorize, 'response' => $response]),
  126. ['song.shen@kuxuan-inc.com'], '聚星系统');
  127. return [];
  128. }
  129. public static function saveJuxingAccount($stateInfo, $userAuthorize, $advertiserList, $type)
  130. {
  131. $data = $userAuthorize['data'] ?? [];
  132. if (empty($data)) {
  133. Log::info('磁力聚星存储授权信息为空', $userAuthorize, 'CallbackService');
  134. return false;
  135. }
  136. if(isset($data['advertiser_ids']) && !empty($data['advertiser_ids'])){
  137. foreach($data['advertiser_ids'] as $advertiser_id){
  138. $data['advertiser_id'] = $advertiser_id;
  139. self::saveJuxingMoreAccount($stateInfo, $data, $type);
  140. }
  141. } else if(!empty($data['advertiser_id'])) {
  142. self::saveJuxingMoreAccount($stateInfo, $data, $type);
  143. } else if(!empty($advertiserList)){
  144. foreach($advertiserList as $advertiserId) {
  145. $data['advertiser_id'] = $advertiserId;
  146. self::saveJuxingMoreAccount($stateInfo, $data, $type);
  147. }
  148. }
  149. return true;
  150. }
  151. public static function saveJuxingMoreAccount($stateInfo, $data, $type)
  152. {
  153. // 存储accountInfo
  154. $adminId = $stateInfo['admin_id'] ?? null;
  155. $accountInfo = self::saveJuxingAccountInfo($adminId, $data, $type);
  156. if (empty($accountInfo)) {
  157. Log::error('磁力聚星存储授权信息失败', ['state_info' => $stateInfo, 'data' => $data, 'type' => $type], 'CallbackService');
  158. return false;
  159. }
  160. $advertiserId = $accountInfo->advertiser_id;
  161. // 存储adAccount
  162. $tokenId = $accountInfo->id;
  163. $nickName = $stateInfo['nick_name'] ?? null;
  164. self::saveJuxingAdAccount($advertiserId, $tokenId, $nickName, $type);
  165. // 存储关联信息
  166. if ($type == 1) {
  167. $customerId = $stateInfo['customer_id'] ?? null;
  168. self::saveJuxingRelaData($advertiserId, $customerId, $adminId);
  169. // 存入redis
  170. (new AssignJuxingAdToRds())->start($advertiserId);
  171. }
  172. }
  173. protected static function saveJinniuAccountInfo($adminId, $data, $type)
  174. {
  175. $accountInfo = new JinniuAccountInfo([
  176. // 'admin_id' => $adminId,
  177. 'advertiser_id' => $data['advertiser_id'] ?? null,
  178. 'advertiser_ids' => !empty($data['advertiser_ids']) ? implode('|', $data['advertiser_ids']) : null,
  179. 'access_token' => $data['access_token'] ?? null,
  180. 'refresh_token' => $data['refresh_token'] ?? null,
  181. 'access_token_expires_at' => date('Y-m-d H:i:s', time() + $data['access_token_expires_in'] - 3),
  182. 'refresh_token_expires_at' => date('Y-m-d H:i:s', time() + $data['refresh_token_expires_in'] - 3),
  183. 'type' => $type
  184. ]);
  185. $accountInfo->save();
  186. return $accountInfo;
  187. }
  188. protected static function saveJinniuAdAccount($advertiserId, $tokenId, $accessToken, $type)
  189. {
  190. $adAccount = JinniuAdAccount::query()->where('advertiser_id', $advertiserId)->first();
  191. if (empty($adAccount)) {
  192. $jinniu = new JinNiu($accessToken);
  193. $adAccountInfo = $jinniu->account()->qualificationInfo([
  194. 'advertiser_id' => $advertiserId
  195. ]);
  196. if (!isset($adAccountInfo['code']) || $adAccountInfo['code'] !== 0) {
  197. Log::error('磁力金牛获取广告主信息失败', $adAccountInfo, 'CallbackService');
  198. return false;
  199. }
  200. $data = $adAccountInfo['data'];
  201. $adAccount = new JinniuAdAccount([
  202. 'advertiser_id' => $advertiserId,
  203. 'ks_id' => $data['ks_id'],
  204. 'user_name' => $data['user_name'] ?? null,
  205. 'company_name' => $data['company_name'] ?? null,
  206. 'industry_l1_id' => $data['industry_l1_id'] ?? null,
  207. 'industry_l1_name' => $data['industry_l1_name'] ?? null,
  208. 'industry_l2_id' => $data['industry_l2_id'] ?? null,
  209. 'industry_l2_name' => $data['industry_l2_name'] ?? null
  210. ]);
  211. }
  212. $adAccount->token_id = $tokenId;
  213. // 重新授权会更新enable
  214. if ($type == 1) $adAccount->enable = 1;
  215. $adAccount->save();
  216. }
  217. protected static function saveJuxingAccountInfo($adminId, $data, $type)
  218. {
  219. $userId = $data['user_id'] ?? null;
  220. if (empty($userId)) return false;
  221. $accountInfo = new JuxingAccountInfo([
  222. 'admin_id' => $adminId,
  223. 'user_id' => $userId,
  224. 'advertiser_id' => $data['advertiser_id'] ?? null,
  225. 'access_token' => $data['access_token'] ?? null,
  226. 'refresh_token' => $data['refresh_token'] ?? null,
  227. 'access_token_expires_at' => date('Y-m-d H:i:s', time() + $data['access_token_expires_in'] - 3),
  228. 'refresh_token_expires_at' => date('Y-m-d H:i:s', time() + $data['refresh_token_expires_in'] - 3),
  229. 'type' => $type
  230. ]);
  231. $accountInfo->save();
  232. return $accountInfo;
  233. }
  234. protected static function saveJuxingAdAccount($advertiserId, $tokenId, $nickName, $type)
  235. {
  236. $adAccount = JuxingAdAccount::query()
  237. ->where('advertiser_id', $advertiserId)
  238. ->first();
  239. if (empty($adAccount)) {
  240. $adAccount = new JuxingAdAccount([
  241. 'advertiser_id' => $advertiserId
  242. ]);
  243. }
  244. $adAccount->token_id = $tokenId;
  245. // 重新授权会更新enable
  246. if ($type == 1) {
  247. $adAccount->nick_name = $nickName.'('. $advertiserId .')';
  248. $adAccount->enable = 1;
  249. }
  250. return $adAccount->save();
  251. }
  252. protected static function saveJuxingRelaData($advertiserId, $customerId, $adminId)
  253. {
  254. if (!isset($advertiserId, $customerId, $adminId)) {
  255. Log::info('参数传递缺失', [
  256. 'param' => [
  257. 'advertiserId' => $advertiserId,
  258. 'customerId' => $customerId,
  259. 'adminId' => $adminId,
  260. ]
  261. ], 'CallbackService');
  262. return true;
  263. }
  264. $cusAccountInfo = SysCustomerAdver::query()
  265. ->where('advertiser_id', $advertiserId)
  266. ->where('enable', 1)
  267. ->first();
  268. if (!empty($cusAccountInfo) && ($cusAccountInfo->customer_id != $customerId)) {
  269. Log::info('账号不能重复授权不同客户', [
  270. 'param' => [
  271. 'advertiserId' => $advertiserId,
  272. 'customerId' => $customerId,
  273. 'adminId' => $adminId,
  274. ]
  275. ], 'CallbackService');
  276. return true;
  277. }
  278. DB::beginTransaction();
  279. try {
  280. // 建立单层账户关系
  281. /*
  282. SysUserAdver::query()
  283. ->updateOrInsert([
  284. 'sys_user_id' => $adminId,
  285. 'advertiser_id' => $advertiserId
  286. ], ['enable' => 1]);
  287. */
  288. // 建立客户与账号的关系
  289. SysCustomerAdver::query()->updateOrInsert([
  290. 'customer_id' => $customerId,
  291. 'advertiser_id' => $advertiserId
  292. ], ['enable' => 1]);
  293. DB::commit();
  294. return true;
  295. } catch (\Throwable $e) {
  296. Log::error('数据关系建立失败:'.$e->getMessage(), [
  297. 'param' => [
  298. 'advertiserId' => $advertiserId,
  299. 'customerId' => $customerId,
  300. 'adminId' => $adminId,
  301. ],
  302. 'trace' => $e->getTrace()
  303. ], 'CallbackService');
  304. DB::rollBack();
  305. return false;
  306. }
  307. }
  308. }