简体   繁体   中英

Using OAuth for API Authorization with PHP

There are several APIs I'm trying to access to grab data in PHP. They all use OAuth authorization and I can't for the life of me figure it out.

If I make a CURL request or file_get_contents request for data using the API's url, obviously it asks me for authorization.

My question is, how do I initialize this authorization using OAuth?

I have my consumer key, consumer secret, OAuth token, and OAuth token secret. One of the APIs stated that I need to include a proper OAuth header with my request, ie:

Authorization: OAuth
  oauth_consumer_key="key",
  oauth_token="token",
  oauth_signature_method="HMAC-SHA1",
  oauth_signature="f922O9A2W5mFwDgiDvZbTSMK%2FPY%3D",
  oauth_timestamp="157131220",
  oauth_nonce="90922def48616d6d65724c61686176",
  oauth_version="1.0"  

But I have no idea how to actually code this header in PHP properly.
I've tried with header() at the top of my PHP script or using a context parameter in my file_get_contents request. I've looked into curl headers as well.

I just can't figure it out.
I feel like I'm missing something obvious, any advice would be much appreciated!

I followed the instructions from ( https://dev.twitter.com/oauth/overview/authorizing-requests ), as it was their API I was trying to access at the time. There was one thing that was wrong on there at the time. That was the urlencoding at step 2.1. This may be different now.

have you tried using cURL for the request? i find it a little more straight-forward than file_get_contents() try

$headers = array(
Authorization => OAuth
oauth_consumer_key => "key",
oauth_token => "token",
oauth_signature_method => "HMAC-SHA1",
oauth_signature => "f922O9A2W5mFwDgiDvZbTSMK%2FPY%3D",
oauth_timestamp => "157131220",
oauth_nonce => "90922def48616d6d65724c61686176",
oauth_version => "1.0" ); 

curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_NOBODY, true);
curl_setopt($cURL, CURLOPT_POST, true);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_POSTFIELDS, $data);
curl_setopt($cURL, CURLOPT_HEADER, true);
curl_setopt($cURL, CURLINFO_HEADER_OUT, true);
curl_setopt($cURL, CURLOPT_NOBODY, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($cURL);

not too sure of the format of the array but something similar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM