GetAccessToken.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. require_once __DIR__ . '/../../vendor/autoload.php'; // change path as needed
  3. use TencentAds\TencentAds;
  4. use TencentAds\Exception\TencentAdsResponseException;
  5. use TencentAds\Exception\TencentAdsSDKException;
  6. /*****
  7. * 本文件提供了一个从Authorization Code获取Access Token的示例
  8. */
  9. class GetAccessToken
  10. {
  11. public static $tads;
  12. public static $CLIENT_ID = 'YOUR CLIENT ID';
  13. public static $CLIENT_SECRET = 'YOUR CLIENT SECRET';
  14. public static $AUTHORIZATION_CODE = 'YOUR AUTHORIZATION CODE';
  15. public static $REDIRECT_URI = 'YOUR REDIRECT URI';
  16. public function init()
  17. {
  18. $tads = TencentAds::init([
  19. 'is_debug' => true,
  20. ]);
  21. $tads->useProduction(); // oauth/token不提供沙箱环境
  22. static::$tads = $tads;
  23. return $tads;
  24. }
  25. public function main()
  26. {
  27. try {
  28. /* @var TencentAds $tads */
  29. $tads = static::$tads;
  30. $token = $tads->oauth()
  31. ->token([
  32. 'client_id' => static::$CLIENT_ID,
  33. 'client_secret' => static::$CLIENT_SECRET,
  34. 'grant_type' => 'authorization_code',
  35. 'authorization_code' => static::$AUTHORIZATION_CODE,
  36. 'redirect_uri' => static::$REDIRECT_URI,
  37. ]);
  38. // 从返回里获得AccessToken并设置到$tads中
  39. $tads->setAccessToken($token->getAccessToken());
  40. // echo 'Access token expires in: ' . $token->getAccessTokenExpiresIn() . PHP_EOL;
  41. // echo 'Refresh token: ' . $token->getRefreshToken() . PHP_EOL;
  42. // echo 'Refresh token expires in: ' . $token->getRefreshTokenExpiresIn() . PHP_EOL;
  43. } catch (TencentAdsResponseException $e) {
  44. // When Api returns an error
  45. echo 'Tencent ads returned an error: ' . $e->getMessage() . PHP_EOL;
  46. throw $e;
  47. } catch (TencentAdsSDKException $e) {
  48. // When validation fails or other local issues
  49. echo 'Tencent ads SDK returned an error: ' . $e->getMessage() . PHP_EOL;
  50. throw $e;
  51. } catch (Exception $e) {
  52. echo 'Other exception: ' . $e->getMessage() . PHP_EOL;
  53. throw $e;
  54. }
  55. }
  56. }
  57. if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) {
  58. try {
  59. $example = new GetAccessToken();
  60. $example->init();
  61. $example->main();
  62. } catch (\Exception $e) {
  63. exit(-1);
  64. }
  65. }