PHP对接腾讯广点通数据回传推送(demo),整理了下大致流程,有些地方需要自己修改。
class gdtPush
{
public $account_id;
public function __construct($account_id=0){
$this->account_id = empty($account_id) ? 1 : $account_id;
}
/**
* @description: 网站行为数据接入
*/
function userActions($info='')
{
$url = 'https://api.e.qq.com/v1.1/user_actions/add?'.$this->getUrlCommon();
$data = '{
"account_id": '.$this->account_id.',
"user_action_set_id": '.$redis->get('gdtUserActionSetId_'.$this->account_id).',
"actions": ['.$info.']
}';
$res = $this->curl('post', $url, $data);
if($res['code'] != 0){
var_dump('推送失败:'.$res['message']);
}
}
/**
* @description: 获取url公共参数有
* @return string
* @author: injurys
*/
function getUrlCommon()
{
$access_token = $this->requestGetAccessToken();
return 'access_token='.$access_token.'×tamp='.time().'&nonce='.rand(1000000, 9999999);
}
/**
* @description: 授权码换取的访问令牌
*/
function requestGetAccessToken()
{
$token = $redis->get('gdtToken_'.$this->account_id);
if(empty($token)){
return $this->requestRefreshToken();
}else{
return $token['access_token'];
}
}
/**
* @description: 用授权码换取访问令牌
*/
function requestRefreshToken(){
$refreshToken = $redis->get('gdtRefreshToken_'.$this->account_id);
if(empty($refreshToken)){
var_dump('RefreshToken不存在,token刷新失败');
exit;
}
$request_url = 'https://api.e.qq.com/oauth/token?client_id=1109998051&client_secret=yJfdDq7rKCjmELKn&grant_type=refresh_token&refresh_token='.$refreshToken['refresh_token'];
$res = $this->curl('get', $request_url);
$result = json_decode($res, true);
if ($result['code'] == 0){
$data = [
'access_token' => $res['data']['access_token'],
'expires_in' => $res['data']['access_token_expires_in'],
];
$redis->setex('gdtToken_'.$this->account_id, 82800, json_encode($data));
$data = [
'refresh_token' => $result['data']['refresh_token'],
'expires_in' => $refreshToken['expires_in'],
];
$redis->setex('gdtRefreshToken_'.$this->account_id, 82800, json_encode($data));
return $res['data']['access_token'];
}else{
var_dump('token刷新失败:'.$result['message']);
return false;
}
}
/**
* @description: 网络请求
* @param string $type
* @param string $url
* @param string $data
* @return mixed
* @author: injurys
*/
public function curl($type='post', $url='', $data='')
{
$ch = curl_init();
if($type == 'post'){
curl_setopt($ch, CURLOPT_POST, 1);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
)
);
$response = curl_exec($ch);
return json_decode($response);
}
}
友情提示:垃圾评论一律封号...