GdtService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. <?php
  2. /**
  3. * Created by: PhpStorm
  4. * User: lytian
  5. * Date: 2020/2/27
  6. * Time: 15:19
  7. */
  8. namespace app\main\service;
  9. use app\common\library\Redis;
  10. use GuzzleHttp\Client as Http;
  11. use think\Config;
  12. use think\Exception;
  13. use think\Log;
  14. class GdtService extends BaseService
  15. {
  16. private $bashUrl = 'https://api.e.qq.com';
  17. /**
  18. * @var GdtService
  19. */
  20. protected static $self = null;
  21. /**
  22. * @return GdtService
  23. */
  24. public static function instance()
  25. {
  26. if (self::$self == null) {
  27. self::$self = new self();
  28. }
  29. return self::$self;
  30. }
  31. /**
  32. * code 换取 access_token
  33. * @param string $code
  34. * @return string
  35. */
  36. public function apiGetAccessToken(string $code, $config, $redirect_uri)
  37. {
  38. try {
  39. $params = [
  40. 'client_id' => $config['client_id'],
  41. 'client_secret' => $config['client_secret'],
  42. 'grant_type' => 'authorization_code',
  43. 'authorization_code' => $code,
  44. 'redirect_uri' => $redirect_uri,
  45. ];
  46. $httpConfig = [
  47. 'base_uri' => $this->bashUrl,
  48. 'connect_timeout' => 10,
  49. 'timeout' => 30,
  50. 'http_errors' => true, //抛出异常 true是 false否
  51. 'verify' => false, //不验证ssl证书
  52. ];
  53. $client = new Http($httpConfig);
  54. $reponse = $client->get("/oauth/token?" . http_build_query($params));
  55. if ($result = json_decode($reponse->getBody(), true)) {
  56. return $result;
  57. }
  58. } catch (\Exception $e) {
  59. $this->error_msg = $e->getMessage();
  60. Log::error("GDT授权获取access_token Fail,Error:" . $e->getMessage());
  61. return null;
  62. }
  63. return null;
  64. }
  65. /**
  66. * 刷新access_token
  67. * @param string $refresh_token
  68. * @return string
  69. */
  70. public function apiUpdateAccessToken(int $account_id, string $refresh_token, $config = [])
  71. {
  72. try {
  73. if (empty($config)) {
  74. $config = Config::get("gdt");
  75. }
  76. $params = [
  77. 'client_id' => $config['client_id'],
  78. 'client_secret' => $config['client_secret'],
  79. 'grant_type' => 'refresh_token',
  80. 'refresh_token' => $refresh_token,
  81. ];
  82. $httpConfig = [
  83. 'base_uri' => $this->bashUrl,
  84. 'connect_timeout' => 10,
  85. 'timeout' => 30,
  86. 'http_errors' => true, //抛出异常 true是 false否
  87. 'verify' => false, //不验证ssl证书
  88. ];
  89. $client = new Http($httpConfig);
  90. $reponse = $client->get("/oauth/token?" . http_build_query($params));
  91. if ($result = json_decode($reponse->getBody(), true)) {
  92. if ($result['code'] != 0) {
  93. //获取失败
  94. Log::error("GDT刷新access_token Fail,Error:" . $result['message']);
  95. return null;
  96. }
  97. //入库更新吧
  98. $update = [
  99. 'access_token' => $result['data']['access_token'],
  100. 'access_token_expire_time' => time() + 85400,
  101. 'updatetime' => time()
  102. ];
  103. model("GdtAccount")->update($update, ['account_id' => $account_id]);
  104. model("TdcAccount")->update($update, ['account_id' => $account_id]);
  105. return $result['data']['access_token'];
  106. }
  107. } catch (\Exception $e) {
  108. $this->error_msg = $e->getMessage();
  109. Log::error("GDT授权获取access_token Fail,Error:" . $e->getMessage());
  110. return null;
  111. }
  112. return null;
  113. }
  114. /**
  115. * 创建或获取 user_action_set_id
  116. * @param int $account_id
  117. * @param string $access_token
  118. * @param array $others
  119. * @return bool|int
  120. * @throws \GuzzleHttp\Exception\GuzzleException
  121. */
  122. public function apiUserActionSetsAdd(int $account_id, string $access_token, $others = [])
  123. {
  124. try {
  125. //判断是否已经获取
  126. $key = 'GDTUASA:' . $account_id;
  127. if (($id = Redis::instance()->get($key)) !== false) {
  128. return $id;
  129. }
  130. $admin_id = $others['admin_id'] ?? 0;
  131. $commonParams = [
  132. 'nonce' => $this->quickRandom(),
  133. 'timestamp' => time(),
  134. 'access_token' => $access_token,
  135. ];
  136. $params = [
  137. 'account_id' => $account_id,
  138. 'type' => 'WEB',
  139. 'name' => 'book2',
  140. 'description' => 'book3'
  141. ];
  142. $httpConfig = [
  143. 'base_uri' => $this->bashUrl,
  144. 'connect_timeout' => 10,
  145. 'timeout' => 30,
  146. 'http_errors' => true, //抛出异常 true是 false否
  147. 'verify' => false, //不验证ssl证书
  148. ];
  149. $client = new Http($httpConfig);
  150. $reponse = $client->request('POST', "/v1.1/user_action_sets/add?" . http_build_query($commonParams),
  151. [
  152. 'headers' => [
  153. 'Content-Type' => 'application/json',
  154. 'charset' => 'utf-8'
  155. ],
  156. 'body' => json_encode($params)
  157. ]
  158. );
  159. if ($result = json_decode($reponse->getBody(), true)) {
  160. if (intval($result['code']) != 0) {
  161. //失败
  162. if (intval($result['code']) == 51000) {
  163. //已存在时,截取ID,并返回成功
  164. $errMsg = explode(':', $result['message']);
  165. $ad_source_id = intval(end($errMsg)) ?? false;
  166. Log::info("GDT: AdminId:{$admin_id} CreateWebSourceId Exists source_id:{$ad_source_id} Data:" . json_encode($result));
  167. if ($ad_source_id) {
  168. Redis::instance()->set($key, $ad_source_id, 3600);
  169. }
  170. return $ad_source_id;
  171. } else {
  172. //失败时处理
  173. Log::error("GDT: AdminId:{$admin_id} CreateWebSourceId Fail,Error:" . $result['message']);
  174. return false;
  175. }
  176. } else {
  177. //成功
  178. Log::info("GDT: AdminId:{$admin_id} CreateWebSourceId Success Data:" . json_encode($result));
  179. return $result['data']['user_action_set_id'] ?? false;
  180. }
  181. }
  182. } catch (\Exception $e) {
  183. Log::error("GDT: AdminId:{$admin_id} CreateWebSourceId Fail,Error:" . $e->getMessage());
  184. return false;
  185. }
  186. }
  187. /**
  188. * 用户行为数据上传
  189. * @param int $account_id
  190. * @param string $access_token
  191. * @param array $ations
  192. * @param array $others
  193. * @return bool
  194. * @throws \GuzzleHttp\Exception\GuzzleException
  195. */
  196. public function apiUserActionAdd(int $account_id, string $access_token, array $ations, $others = [])
  197. {
  198. try {
  199. $admin_id = $others['admin_id'] ?? 0;
  200. $commonParams = [
  201. 'nonce' => $this->quickRandom(),
  202. 'timestamp' => time(),
  203. 'access_token' => $access_token,
  204. ];
  205. if (isset($others['ad_source_id']) && !empty($others['ad_source_id'])) {
  206. $ad_source_id = $others['ad_source_id'];
  207. } else {
  208. $ad_source_id = $this->apiUserActionSetsAdd($account_id, $access_token, $others);
  209. }
  210. if (is_null($ad_source_id)) {
  211. throw new Exception("ad_source_id is null", 201);
  212. }
  213. $params = [
  214. 'account_id' => $account_id,
  215. 'user_action_set_id' => $ad_source_id,
  216. 'actions' => $ations,
  217. ];
  218. $httpConfig = [
  219. 'base_uri' => $this->bashUrl,
  220. 'connect_timeout' => 10,
  221. 'timeout' => 30,
  222. 'http_errors' => true, //抛出异常 true是 false否
  223. 'verify' => false, //不验证ssl证书
  224. ];
  225. $client = new Http($httpConfig);
  226. $reponse = $client->request('POST', "/v1.1/user_actions/add?" . http_build_query($commonParams),
  227. [
  228. 'headers' => [
  229. 'Content-Type' => 'application/json',
  230. 'charset' => 'utf-8'
  231. ],
  232. 'body' => json_encode($params)
  233. ]
  234. );
  235. if ($result = json_decode($reponse->getBody(), true)) {
  236. if (intval($result['code']) != 0) {
  237. //失败
  238. Log::error("GDT上传用户行为数据: AdminId:{$admin_id} Fail, Data: " . json_encode($params) . " Error:" . $result['message']);
  239. return false;
  240. } else {
  241. //成功
  242. Log::info("GDT上传用户行为数据: AdminId:{$admin_id} Result:" . json_encode($result));
  243. return true;
  244. }
  245. }
  246. } catch (\Exception $e) {
  247. Log::error("GDT上传用户行为数据: AdminId:{$admin_id} Fail, Error:" . $e->getMessage());
  248. return false;
  249. }
  250. }
  251. /**
  252. * 注册行为回传
  253. * @param $gdtInfo
  254. * @param $user_info
  255. * @param null $click_id
  256. * @param array $others
  257. */
  258. public function regiserReport($gdtInfo, $userInfo, $click_id = null, $others = [])
  259. {
  260. $actions = [
  261. [
  262. 'url' => $others['url'],
  263. 'action_time' => time(),
  264. 'action_type' => 'REGISTER',
  265. 'trace' => [
  266. 'click_id' => !is_null($click_id) ? $click_id : '',
  267. ],
  268. ]
  269. ];
  270. $this->apiUserActionAdd($gdtInfo['account_id'], $gdtInfo['access_token'], $actions, $others);
  271. }
  272. /**
  273. * 下单行为回传
  274. * @param $gdtInfo
  275. * @param $userInfo
  276. * @param $orderInfo
  277. * @param array $others
  278. * @throws \GuzzleHttp\Exception\GuzzleException
  279. */
  280. public function orderCompleteReport($gdtInfo, $userInfo, $orderInfo, $others = [])
  281. {
  282. $actions = [
  283. [
  284. 'url' => $others['url'],
  285. 'action_time' => time(),
  286. 'action_type' => 'PURCHASE',
  287. 'action_param' => (object)[
  288. 'value' => intval($orderInfo['money'] * 100),
  289. 'productName' => $orderInfo['productName']
  290. ],
  291. 'trace' => [
  292. 'click_id' => $others['click_id'] ?: '',
  293. ],
  294. ]
  295. ];
  296. $this->apiUserActionAdd($gdtInfo['account_id'], $gdtInfo['access_token'], $actions, $others);
  297. }
  298. /**
  299. * 随机字符串
  300. * @param int $length
  301. * @return bool|string
  302. */
  303. private function quickRandom($length = 16)
  304. {
  305. $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  306. return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
  307. }
  308. }