接口文档SDK业务专题开发者工具

刷新Access Token

                <?php
require_once __DIR__ . '/../../vendor/autoload.php'; // change path as needed
use TencentAds\TencentAds;
use TencentAds\Exception\TencentAdsResponseException;
use TencentAds\Exception\TencentAdsSDKException;

/*****
 * 本文件提供了一个从Refresh Token刷新Access Token的示例
 */
class RefreshAccessToken
{
    public static $tads;
    public static $CLIENT_ID     = 'YOUR CLIENT ID';
    public static $CLIENT_SECRET = 'YOUR CLIENT SECRET';
    public static $REFRESH_TOKEN = 'YOUR REFRESH TOKEN';

    public function init()
    {
        $tads = TencentAds::init([
            'is_debug'     => true,
        ]);
        $tads->useProduction(); // oauth/token不提供沙箱环境
        static::$tads = $tads;

        return $tads;
    }

    public function main()
    {
        try {
            /* @var TencentAds $tads */
            $tads = static::$tads;

            $token = $tads->oauth()
                          ->token([
                              'client_id'     => static::$CLIENT_ID,
                              'client_secret' => static::$CLIENT_SECRET,
                              'grant_type'    => 'refresh_token',
                              'refresh_token' => static::$REFRESH_TOKEN,
                          ]);

            // 从返回里获得AccessToken并设置到$tads中
            $tads->setAccessToken($token->getAccessToken());
            // echo 'Access token expires in: ' . $token->getAccessTokenExpiresIn() . PHP_EOL;
            // echo 'Refresh token: ' . $token->getRefreshToken() . PHP_EOL;
            // echo 'Refresh token expires in: ' . $token->getRefreshTokenExpiresIn() . PHP_EOL;
        } catch (TencentAdsResponseException $e) {
            // When Api returns an error
            echo 'Tencent ads returned an error: ' . $e->getMessage() . PHP_EOL;
            throw $e;
        } catch (TencentAdsSDKException $e) {
            // When validation fails or other local issues
            echo 'Tencent ads SDK returned an error: ' . $e->getMessage() . PHP_EOL;
            throw $e;
        } catch (Exception $e) {
            echo 'Other exception: ' . $e->getMessage() . PHP_EOL;
            throw $e;
        }
    }
}

if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) {
    try {
        $example = new RefreshAccessToken();
        $example->init();
        $example->main();
    } catch (\Exception $e) {
        exit(-1);
    }
}
            
                package com.tencent.ads.examples.Authentication;

import com.tencent.ads.ApiContextConfig;
import com.tencent.ads.ApiException;
import com.tencent.ads.TencentAds;
import com.tencent.ads.exception.TencentAdsResponseException;
import com.tencent.ads.exception.TencentAdsSDKException;
import com.tencent.ads.model.OauthTokenResponseData;

/** 本文件提供了一个从Refresh Token刷新Access Token的示例 */
public class RefreshAccessToken {

  /** YOUR CLIENT ID */
  public Long CLIENT_ID = 0L;
  /** YOUR CLIENT SECRET */
  public String CLIENT_SECRET = "YOUR CLIENT SECRET";
  /** YOUR REFRESH TOKEN */
  public String REFRESH_TOKEN = "YOUR REFRESH TOKEN";

  /** TencentAds */
  public TencentAds tencentAds;

  public void init() {
    this.tencentAds = TencentAds.getInstance();
    this.tencentAds.init(new ApiContextConfig().isDebug(true));
    // oauth/token不提供沙箱环境
    this.tencentAds.useProduction();
  }

  public String refreshAccessToken() throws ApiException {
    OauthTokenResponseData responseData =
        tencentAds
            .oauth()
            .oauthToken(CLIENT_ID, CLIENT_SECRET, "refresh_token", null, REFRESH_TOKEN, null);
    if (responseData != null) {
      String accessToken = responseData.getAccessToken();
      tencentAds.setAccessToken(accessToken);
      return accessToken;
    }
    return null;
  }

  public static void main(String[] args) {
    try {
      RefreshAccessToken refreshAccessToken = new RefreshAccessToken();
      refreshAccessToken.init();
      String accessToken = refreshAccessToken.refreshAccessToken();
    } catch (TencentAdsResponseException e) {
      e.printStackTrace();
    } catch (TencentAdsSDKException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
            
                package main

import (
	"encoding/json"
	"fmt"

	"github.com/antihax/optional"
	"github.com/tencentad/marketing-api-go-sdk/pkg/ads"
	"github.com/tencentad/marketing-api-go-sdk/pkg/api"
	"github.com/tencentad/marketing-api-go-sdk/pkg/config"
	"github.com/tencentad/marketing-api-go-sdk/pkg/errors"
)

// RefreshAccessTokenExample ...
type RefreshAccessTokenExample struct {
	TAds           *ads.SDKClient
	AccessToken    string
	ClientId       int64
	ClientSecret   string
	GrantType      string
	OauthTokenOpts *api.OauthTokenOpts
}

// Init ...
func (e *RefreshAccessTokenExample) Init() {
	e.TAds = ads.Init(&config.SDKConfig{
		IsDebug: true,
	})
	// oauth/token不提供沙箱环境
	e.TAds.UseProduction()
	// YOUR CLIENT ID
	e.ClientId = int64(0)
	e.ClientSecret = "YOUR CLIENT SECRET"
	e.GrantType = "refresh_token"
	e.OauthTokenOpts = &api.OauthTokenOpts{
		RefreshToken: optional.NewString("YOUR REFRESH TOKEN"),
	}
}

// RunExample ...
func (e *RefreshAccessTokenExample) RunExample() {
	tads := e.TAds

	// change ctx as needed
	ctx := *tads.Ctx
	response, _, err := tads.Oauth().Token(ctx, e.ClientId, e.ClientSecret, e.GrantType, e.OauthTokenOpts)

	if err != nil {
		if resErr, ok := err.(errors.ResponseError); ok {
			// When Api returns an error
			errStr, _ := json.Marshal(resErr)
			fmt.Println("Resopnse error:", string(errStr))
		} else {
			// When validation fails or other local issues
			fmt.Println("Error:", err)
		}
	} else {
		// 从返回里获得AccessToken并设置到tads中
		tads.SetAccessToken(response.AccessToken)
	}
}

func main() {
	e := &RefreshAccessTokenExample{}
	e.Init()
	e.RunExample()
}