User.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace TwitterPhp\Connection;
  3. class User extends Base
  4. {
  5. /**
  6. * @var string
  7. */
  8. private $_consumerKey;
  9. /**
  10. * @var string
  11. */
  12. private $_consumerSecret;
  13. /**
  14. * @var string
  15. */
  16. private $_accessToken;
  17. /**
  18. * @var string
  19. */
  20. private $_accessTokenSecret;
  21. /**
  22. * @param string $consumerKey
  23. * @param string $consumerSecret
  24. * @param string $accessToken
  25. * @param string $accessTokenSecret
  26. */
  27. public function __construct($consumerKey,$consumerSecret,$accessToken,$accessTokenSecret)
  28. {
  29. $this->_consumerKey = $consumerKey;
  30. $this->_consumerSecret = $consumerSecret;
  31. $this->_accessToken = $accessToken;
  32. $this->_accessTokenSecret = $accessTokenSecret;
  33. }
  34. /**
  35. * @param string $url
  36. * @param array $parameters
  37. * @param $method
  38. * @return array
  39. */
  40. protected function _buildHeaders($url,array $parameters = null,$method)
  41. {
  42. $oauthHeaders = array(
  43. 'oauth_version' => '1.0',
  44. 'oauth_consumer_key' => $this->_consumerKey,
  45. 'oauth_nonce' => time(),
  46. 'oauth_signature_method' => 'HMAC-SHA1',
  47. 'oauth_token' => $this->_accessToken,
  48. 'oauth_timestamp' => time()
  49. );
  50. $data = $oauthHeaders;
  51. if ($method == self::METHOD_GET) {
  52. $data = array_merge($oauthHeaders,$parameters);
  53. }
  54. $oauthHeaders['oauth_signature'] = $this->_buildOauthSignature($url,$data,$method);
  55. ksort($oauthHeaders);
  56. $oauthHeader = array();
  57. foreach($oauthHeaders as $key => $value) {
  58. $oauthHeader[] = $key . '="' . rawurlencode($value) . '"';
  59. }
  60. $headers[] = 'Authorization: OAuth ' . implode(', ', $oauthHeader);
  61. return $headers;
  62. }
  63. /**
  64. * @param $url
  65. * @param array $params
  66. * @param $method
  67. * @return string
  68. */
  69. private function _buildOauthSignature($url,array $params,$method)
  70. {
  71. ksort($params);
  72. $sortedParams = array();
  73. foreach($params as $key=>$value) {
  74. $sortedParams[] = $key . '=' . $value;
  75. }
  76. $signatureBaseString = $method . "&" . rawurlencode($url) . '&' . rawurlencode(implode('&', $sortedParams));
  77. $compositeKey = rawurlencode($this->_consumerSecret) . '&' . rawurlencode($this->_accessTokenSecret);
  78. return base64_encode(hash_hmac('sha1', $signatureBaseString, $compositeKey, true));
  79. }
  80. }