Application.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace TwitterPhp\Connection;
  3. use TwitterPhp\RestApiException;
  4. class Application extends Base
  5. {
  6. /**
  7. * @var string
  8. */
  9. private $_consumerKey;
  10. /**
  11. * @var string
  12. */
  13. private $_consumerSecret;
  14. /**
  15. * @var string
  16. */
  17. private $_bearersToken = null;
  18. /**
  19. * @param string $consumerKey
  20. * @param string $consumerSecret
  21. */
  22. public function __construct($consumerKey,$consumerSecret)
  23. {
  24. $this->_consumerKey = $consumerKey;
  25. $this->_consumerSecret = $consumerSecret;
  26. }
  27. /**
  28. * @param string $url
  29. * @param array $parameters
  30. * @param $method
  31. * @return array
  32. */
  33. protected function _buildHeaders($url,array $parameters = null,$method)
  34. {
  35. return $headers = array(
  36. "Authorization: Bearer " . $this->_getBearerToken()
  37. );
  38. }
  39. /**
  40. * Get Bearer token
  41. *
  42. * @link https://dev.twitter.com/docs/auth/application-only-auth
  43. *
  44. * @throws \TwitterPhp\RestApiException
  45. * @return string
  46. */
  47. private function _getBearerToken() {
  48. if (!$this->_bearersToken) {
  49. $token = urlencode($this->_consumerKey) . ':' . urlencode($this->_consumerSecret);
  50. $token = base64_encode($token);
  51. $headers = array(
  52. "Authorization: Basic " . $token
  53. );
  54. $options = array (
  55. CURLOPT_URL => self::TWITTER_API_AUTH_URL,
  56. CURLOPT_HTTPHEADER => $headers,
  57. CURLOPT_POST => 1,
  58. CURLOPT_POSTFIELDS => "grant_type=client_credentials"
  59. );
  60. $response = $this->_callApi($options);
  61. if (isset($response["token_type"]) && $response["token_type"] == 'bearer') {
  62. $this->_bearersToken = $response["access_token"];
  63. } else {
  64. throw new RestApiException('Error while getting access token');
  65. }
  66. }
  67. return $this->_bearersToken;
  68. }
  69. }