· 8 years ago · Dec 08, 2016, 07:36 PM
1<?php
2
3class OAuth_Authorization_Header {
4
5 private $keys;
6 private $url;
7 private $method;
8 private $credentials;
9
10 public function __construct( $keys, $url, $method ) {
11 $this->keys = $keys;
12 $this->url = $url;
13 $this->method = $method;
14 $this->set_credentials();
15 }
16
17 public function get_header() {
18
19 $header = 'OAuth ';
20
21 $oauth_params = array();
22
23 foreach ( $this->credentials as $key => $value ) {
24 $oauth_params[] = "$key=\"" . rawurlencode( $value ) . '"';
25 }
26
27 $header .= implode( ', ', $oauth_params );
28
29 return $header;
30 }
31
32 private function set_credentials() {
33
34 $credentials = array(
35 'oauth_consumer_key' => $this->keys['oauth_consumer_key'],
36 'oauth_nonce' => wp_generate_password( 12, false, false ),
37 'oauth_signature_method' => 'HMAC-SHA1',
38 'oauth_token' => $this->keys['oauth_token'],
39 'oauth_timestamp' => time(),
40 'oauth_version' => '1.0'
41 );
42
43 // For some reason, this matters!
44 ksort( $credentials );
45
46 $this->credentials = $credentials;
47
48 $this->set_oauth_signature();
49 }
50
51 private function set_oauth_signature() {
52
53 $string_params = array();
54
55 foreach ( $this->credentials as $key => $value ) {
56 $string_params[] = "$key=$value";
57 }
58
59 $signature = "$this->method&" . rawurlencode( $this->url ) . '&' . rawurlencode( implode( '&', $string_params ) );
60
61 $hash_hmac_key = rawurlencode( $this->keys['oauth_consumer_secret'] ) . '&' . rawurlencode( $this->keys['oauth_token_secret'] );
62
63 $oauth_signature = base64_encode( hash_hmac( 'sha1', $signature, $hash_hmac_key, true ) );
64
65 $this->credentials['oauth_signature'] = $oauth_signature;
66 }
67}