123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321 |
- <?php
- /**
- * Created by: PhpStorm
- * User: lytian
- * Date: 2020/2/27
- * Time: 15:19
- */
- namespace app\main\service;
- use app\common\library\Redis;
- use GuzzleHttp\Client as Http;
- use think\Config;
- use think\Exception;
- use think\Log;
- class GdtService extends BaseService
- {
- private $bashUrl = 'https://api.e.qq.com';
- /**
- * @var GdtService
- */
- protected static $self = null;
- /**
- * @return GdtService
- */
- public static function instance()
- {
- if (self::$self == null) {
- self::$self = new self();
- }
- return self::$self;
- }
- /**
- * code 换取 access_token
- * @param string $code
- * @return string
- */
- public function apiGetAccessToken(string $code, $config, $redirect_uri)
- {
- try {
- $params = [
- 'client_id' => $config['client_id'],
- 'client_secret' => $config['client_secret'],
- 'grant_type' => 'authorization_code',
- 'authorization_code' => $code,
- 'redirect_uri' => $redirect_uri,
- ];
- $httpConfig = [
- 'base_uri' => $this->bashUrl,
- 'connect_timeout' => 10,
- 'timeout' => 30,
- 'http_errors' => true, //抛出异常 true是 false否
- 'verify' => false, //不验证ssl证书
- ];
- $client = new Http($httpConfig);
- $reponse = $client->get("/oauth/token?" . http_build_query($params));
- if ($result = json_decode($reponse->getBody(), true)) {
- return $result;
- }
- } catch (\Exception $e) {
- $this->error_msg = $e->getMessage();
- Log::error("GDT授权获取access_token Fail,Error:" . $e->getMessage());
- return null;
- }
- return null;
- }
- /**
- * 刷新access_token
- * @param string $refresh_token
- * @return string
- */
- public function apiUpdateAccessToken(int $account_id, string $refresh_token, $config = [])
- {
- try {
- if (empty($config)) {
- $config = Config::get("gdt");
- }
- $params = [
- 'client_id' => $config['client_id'],
- 'client_secret' => $config['client_secret'],
- 'grant_type' => 'refresh_token',
- 'refresh_token' => $refresh_token,
- ];
- $httpConfig = [
- 'base_uri' => $this->bashUrl,
- 'connect_timeout' => 10,
- 'timeout' => 30,
- 'http_errors' => true, //抛出异常 true是 false否
- 'verify' => false, //不验证ssl证书
- ];
- $client = new Http($httpConfig);
- $reponse = $client->get("/oauth/token?" . http_build_query($params));
- if ($result = json_decode($reponse->getBody(), true)) {
- if ($result['code'] != 0) {
- //获取失败
- Log::error("GDT刷新access_token Fail,Error:" . $result['message']);
- return null;
- }
- //入库更新吧
- $update = [
- 'access_token' => $result['data']['access_token'],
- 'access_token_expire_time' => time() + 85400,
- 'updatetime' => time()
- ];
- model("GdtAccount")->update($update, ['account_id' => $account_id]);
- model("TdcAccount")->update($update, ['account_id' => $account_id]);
- return $result['data']['access_token'];
- }
- } catch (\Exception $e) {
- $this->error_msg = $e->getMessage();
- Log::error("GDT授权获取access_token Fail,Error:" . $e->getMessage());
- return null;
- }
- return null;
- }
- /**
- * 创建或获取 user_action_set_id
- * @param int $account_id
- * @param string $access_token
- * @param array $others
- * @return bool|int
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
- public function apiUserActionSetsAdd(int $account_id, string $access_token, $others = [])
- {
- try {
- //判断是否已经获取
- $key = 'GDTUASA:' . $account_id;
- if (($id = Redis::instance()->get($key)) !== false) {
- return $id;
- }
- $admin_id = $others['admin_id'] ?? 0;
- $commonParams = [
- 'nonce' => $this->quickRandom(),
- 'timestamp' => time(),
- 'access_token' => $access_token,
- ];
- $params = [
- 'account_id' => $account_id,
- 'type' => 'WEB',
- 'name' => 'book2',
- 'description' => 'book3'
- ];
- $httpConfig = [
- 'base_uri' => $this->bashUrl,
- 'connect_timeout' => 10,
- 'timeout' => 30,
- 'http_errors' => true, //抛出异常 true是 false否
- 'verify' => false, //不验证ssl证书
- ];
- $client = new Http($httpConfig);
- $reponse = $client->request('POST', "/v1.1/user_action_sets/add?" . http_build_query($commonParams),
- [
- 'headers' => [
- 'Content-Type' => 'application/json',
- 'charset' => 'utf-8'
- ],
- 'body' => json_encode($params)
- ]
- );
- if ($result = json_decode($reponse->getBody(), true)) {
- if (intval($result['code']) != 0) {
- //失败
- if (intval($result['code']) == 51000) {
- //已存在时,截取ID,并返回成功
- $errMsg = explode(':', $result['message']);
- $ad_source_id = intval(end($errMsg)) ?? false;
- Log::info("GDT: AdminId:{$admin_id} CreateWebSourceId Exists source_id:{$ad_source_id} Data:" . json_encode($result));
- if ($ad_source_id) {
- Redis::instance()->set($key, $ad_source_id, 3600);
- }
- return $ad_source_id;
- } else {
- //失败时处理
- Log::error("GDT: AdminId:{$admin_id} CreateWebSourceId Fail,Error:" . $result['message']);
- return false;
- }
- } else {
- //成功
- Log::info("GDT: AdminId:{$admin_id} CreateWebSourceId Success Data:" . json_encode($result));
- return $result['data']['user_action_set_id'] ?? false;
- }
- }
- } catch (\Exception $e) {
- Log::error("GDT: AdminId:{$admin_id} CreateWebSourceId Fail,Error:" . $e->getMessage());
- return false;
- }
- }
- /**
- * 用户行为数据上传
- * @param int $account_id
- * @param string $access_token
- * @param array $ations
- * @param array $others
- * @return bool
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
- public function apiUserActionAdd(int $account_id, string $access_token, array $ations, $others = [])
- {
- try {
- $admin_id = $others['admin_id'] ?? 0;
- $commonParams = [
- 'nonce' => $this->quickRandom(),
- 'timestamp' => time(),
- 'access_token' => $access_token,
- ];
- if (isset($others['ad_source_id']) && !empty($others['ad_source_id'])) {
- $ad_source_id = $others['ad_source_id'];
- } else {
- $ad_source_id = $this->apiUserActionSetsAdd($account_id, $access_token, $others);
- }
- if (is_null($ad_source_id)) {
- throw new Exception("ad_source_id is null", 201);
- }
- $params = [
- 'account_id' => $account_id,
- 'user_action_set_id' => $ad_source_id,
- 'actions' => $ations,
- ];
- $httpConfig = [
- 'base_uri' => $this->bashUrl,
- 'connect_timeout' => 10,
- 'timeout' => 30,
- 'http_errors' => true, //抛出异常 true是 false否
- 'verify' => false, //不验证ssl证书
- ];
- $client = new Http($httpConfig);
- $reponse = $client->request('POST', "/v1.1/user_actions/add?" . http_build_query($commonParams),
- [
- 'headers' => [
- 'Content-Type' => 'application/json',
- 'charset' => 'utf-8'
- ],
- 'body' => json_encode($params)
- ]
- );
- if ($result = json_decode($reponse->getBody(), true)) {
- if (intval($result['code']) != 0) {
- //失败
- Log::error("GDT上传用户行为数据: AdminId:{$admin_id} Fail, Data: " . json_encode($params) . " Error:" . $result['message']);
- return false;
- } else {
- //成功
- Log::info("GDT上传用户行为数据: AdminId:{$admin_id} Result:" . json_encode($result));
- return true;
- }
- }
- } catch (\Exception $e) {
- Log::error("GDT上传用户行为数据: AdminId:{$admin_id} Fail, Error:" . $e->getMessage());
- return false;
- }
- }
- /**
- * 注册行为回传
- * @param $gdtInfo
- * @param $user_info
- * @param null $click_id
- * @param array $others
- */
- public function regiserReport($gdtInfo, $userInfo, $click_id = null, $others = [])
- {
- $actions = [
- [
- 'url' => $others['url'],
- 'action_time' => time(),
- 'action_type' => 'REGISTER',
- 'trace' => [
- 'click_id' => !is_null($click_id) ? $click_id : '',
- ],
- ]
- ];
- $this->apiUserActionAdd($gdtInfo['account_id'], $gdtInfo['access_token'], $actions, $others);
- }
- /**
- * 下单行为回传
- * @param $gdtInfo
- * @param $userInfo
- * @param $orderInfo
- * @param array $others
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
- public function orderCompleteReport($gdtInfo, $userInfo, $orderInfo, $others = [])
- {
- $actions = [
- [
- 'url' => $others['url'],
- 'action_time' => time(),
- 'action_type' => 'PURCHASE',
- 'action_param' => (object)[
- 'value' => intval($orderInfo['money'] * 100),
- 'productName' => $orderInfo['productName']
- ],
- 'trace' => [
- 'click_id' => $others['click_id'] ?: '',
- ],
- ]
- ];
- $this->apiUserActionAdd($gdtInfo['account_id'], $gdtInfo['access_token'], $actions, $others);
- }
- /**
- * 随机字符串
- * @param int $length
- * @return bool|string
- */
- private function quickRandom($length = 16)
- {
- $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
- return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
- }
- }
|