HTTP Put via php client - php

I'm writing a small 'app' for a accounting site called Xena.biz
The system has an API that uses oAuth2 to connect to. All that I have sorted out - I can perfectly retrieve the information I need. Now I need to submit a PUT string back to Xena - here is where I can't figure it out.
The system is build on a file called XenaClient.php which contains all the authorization calls and all the requests.
Here is an example on how I retrieve information :
<?
require('XenaClient.php');
const CLIENT_ID = 'SECRET';
const CLIENT_SECRET = 'VERY SECRET';
$xenaclient = new XenaOAuth2Client(CLIENT_ID, CLIENT_SECRET);
$xenaclient->setAccessToken($_COOKIE["MaskedCookieName"]);
$ordertask = $xenaclient->fetch('https://my.xena.biz/Api/Fiscal/'.$_GET["fiscal"].'/OrderTask/'.$_GET["orderId"]);
var_dump($ordertask);
?>
But now I want to SEND information via PUT. According to the XenaClient.php script, I should use the command $xenaclient->fetch($url,$parameters);
So this is my shot
require('XenaClient.php');
const CLIENT_ID = 'SECRET';
const CLIENT_SECRET = 'VERY SECRET';
$xenaclient = new XenaOAuth2Client(CLIENT_ID, CLIENT_SECRET);
$xenaclient->setAccessToken($_COOKIE["MaskedCookieName"]);
$xenaclient->fetch('https://my.xena.biz/Api/Fiscal/96946/Order/243936250/Confirmation',array('ConfirmationDate'=>NULL,'ConfirmationReportLayoutId'=>261205291));
?>
This doesn't turn anything back, or doesn't create the wanted effect inside the accounting system. No help to get from Xena themselves, so this is why I ask you guys, hope you can help me.
Heres a few pointers:
The API resource: https://dev.xena.biz
XenaClient.php: https://github.com/EG-BRS/Xena.ExampleApp.PHP/blob/master/XenaClient.php

XenoOAuth2Client::fetch tells you, that the third parameter to the fetch function - although optional - determines the method of the request. Default ist GET (XenaOAuth2Client::HTTP_METHOD_GET), so if you want PUT, you should explicitly provide the appropriate PUT parameter (other methods see the XenoOAuth2Client class constants:
$xenaclient->fetch(
'https://my.xena.biz/Api/Fiscal/96946/Order/243936250/Confirmation',
array('ConfirmationReportLayoutId'=>261205291),
XenaOAuth2Client::HTTP_METHOD_PUT
);
most APIs consume json today, perhaps it's supposed to be json...
$xenaclient->fetch(
'https://my.xena.biz/Api/Fiscal/96946/Order/243936250/Confirmation',
json_encode(array('ConfirmationReportLayoutId'=>261205291)),
XenaOAuth2Client::HTTP_METHOD_PUT
);

Related

How to access the page protected by basic auth using Faraday?

I have a php page I want to access and that page is protected by basic auth. I know the url and username/password, they are listed below in code:
url = 'https://henry.php' # note that it is a php website
username = 'foo'
password = 'bar'
Faraday provide basic auth function, their doc says that I should use the following code:
connection = Faraday.new(url: url) do |conn|
conn.basic_auth(username, password)
end
I want to get the response body of the above url to make sure that the basic auth indeed succeed and I can access the content, but I don't know how to. I tried each of the following ways but none of them work:
connection.body
connection.response.body
connection.env.response.body
# or
r = connection.get
r.body
r.response.body
r.env.response.body
# or
r = connection.get '/'
r.body
r.response.body
r.env.response.body
What is the proper way to get the body?
Note:
In browser, I access https://henry.php directly and browser prompt me a box asking my username and password and I enter them and I can see the content - I can see the details I have is correct and it should work (this is because browser knows how to do basic auth), but I just can't figure out how to do it in code using Faraday.
Answering my own question:
Instead of just:
connection = Faraday.new(url: url) do |conn|
conn.basic_auth(username, password)
end
you should remember to use an adapter:
connection = Faraday.new(url: url) do |conn|
conn.adapter Faraday.default_adapter # make requests with Net::HTTP
conn.basic_auth(username, password)
end
because Faraday is an interface, it does not do the actual work of making connection and request, the adapter does that, so you need it for it to work.
Then, to get ther response body you want, you can just:
response = connection.get
response.body
The Faraday gem comes with a number of plugins (middleware) that make HTTP requests simpler and more customizable. In Ruby, basic authentication might be difficult. Let's have a look at it;
require "faraday"
request_helper = Faraday.new(url: 'example.com') do |builder|
builder.use Faraday::Request::BasicAuthentication, client_key, secret_key
end
# you make HTTP requests using `request_helper` since basic auth is configured
response = request_helper.get('/myendpoit')
You must obtain tokens by proving client and secret keys when using an API such as the Stripe API. We can give client and secret keys as inputs to the Faraday::Request::BasicAuthentication middleware to establish basic authentication using the same approach as before.
You can use:
Faraday.new(...) do |conn|
conn.request :authorization, :basic, 'username', 'password'
end
source: https://lostisland.github.io/faraday/middleware/authentication
For Faraday 1.x this is actually different:
Faraday.new(...) do |conn|
conn.request :basic_auth, 'username', 'password'
end

php openid connect get token

I try to use jumbojett library for php and openid. I made connection but and get secret id and client, but when I want to get token I don't know how.
In small documentation is next example:
$oidc = new OpenIDConnectClient('https://id.provider.com',
'ClientIDHere',
'ClientSecretHere');
$oidc->providerConfigParam(array('token_endpoint'=>'https://id.provider.com/connect/token'));
$oidc->addScope('my_scope');
// this assumes success (to validate check if the access_token property is there and a valid JWT) :
$clientCredentialsToken = $oidc->requestClientCredentialsToken()->access_token;
But function requestClientCredentialsToken() doesn't exist in library. Does anyone know how to get token or to recommend some another php library where I can define scope, redirect uri, get client secret and id from open server and offcourse to get token.
Thanks in advance
There is a public function getAccessToken().
You should modify the the code above like this:
$oidc = new OpenIDConnectClient('https://id.provider.com',
'ClientIDHere',
'ClientSecretHere');
$oidc->providerConfigParam(array('token_endpoint'=>'https://id.provider.com/connect/token'));
$oidc->addScope('my_scope');
$oicd->authenticate();
$mytoken=$oidc->getAccessToken();

What is correct Twilio AddOns syntax for php REST client?

Beginner to both Twilio & php here:
I have: Twilio php helper, Twilio account, Whitepages Pro AddOn enabled for Lookups and have successfully retrieved "basic" lookup data, ie, "Carrier->Type" (the "basic" lookup does not use the AddOn)
I need: to use Twilio Rest Client with Whitepages Pro AddOn to retrieve other data, ie, "standard_address_line1", for an individual phone number. I do not want the $0.07 per call AddOn enabled for all incoming calls, although I was able to receive this data from the AddOn that way.
Twilio API Documentation is scant. Shows output format, but not REST Client request syntax: WhitePagesPro AddOn Documentation
Here is what I tried:
<?php
require 'vendor/autoload.php';
use Twilio\Rest\Client;
$client = new Client(ACxxxxxxxxxx,Tokenxxxxxxxx);
$number = $client->lookups
->phoneNumbers("+1xxxxxxxxxx")
->fetch(
array("AddOns" => "whitepages_pro_caller_id")
);
echo $number->
results->
whitepages_pro_caller_id->
result->
results[0]->
associated_locations[0]->
standard_address_line1;
//This syntax works for 'basic' lookup
//Returns: "landline"
//
//$number = $client->lookups
// ->phoneNumbers("+1xxxxxxxxxx")
// ->fetch(
// array("type" => "carrier")
// );
//
//echo $number->carrier['type'];
?>
Throws error: Uncaught exception 'Twilio\Exceptions\TwilioException' with message 'Unknown property: results'
I'm way over my head, I don't know how to go about debugging this. Any Twilio experts?
Ideally I'd also like to know if it's possible to specify this particular data in the request vs traversing many levels of the response in order to get the data I need...
Twilio developer evangelist here.
You're very close with what you have there. The addOns results are actually returned in the addOns property of the number there. So, using your code, you can print the request SID of the call like this:
<?php
require 'vendor/autoload.php';
use Twilio\Rest\Client;
$client = new Client(ACxxxxxxxxxx,Tokenxxxxxxxx);
$number = $client->lookups
->phoneNumbers("+1xxxxxxxxxx")
->fetch(
array("AddOns" => "whitepages_pro_caller_id")
);
echo $number->addOns['results']['whitepages_pro_caller_id']['request_sid']
If you want to inspect the entire result, you can use var_dump to see the entire structure
var_dump($number->addOns['results']['whitepages_pro_caller_id'])
The structure will appear as it does in the documentation but it might be easier to see in the PHP output.
Let me know if that helps at all.

How to get user image with Twitter API 1.1?

In API 1.0, we can use users/profile_image/:screen_name
For example : http://api.twitter.com/1/users/profile_image/EA_FIFA_FRANCE
But, it doesn't work anymore in API 1.1.
Do you have a solution, please ?
You can also get the twitter profile image by calling this kind of url :
https://twitter.com/[screen_name]/profile_image?size=original
For instance : https://twitter.com/VancityReynolds/profile_image?size=original
Got the info from this post :
https://twittercommunity.com/t/how-to-get-user-image-original-size-with-api-1-1/10187/14
The user's profile image
Okay, so you want a user's profile image. You're going to need to take a look at the twitter REST API 1.1 docs. This is a list of all the different requests you can make to their API (don't worry, I'll get to how you actually do this later on).
There are multiple ways to get the user's profile image, but the most notable one is: users/show. According to the docs for this, the users/show method:
Returns a variety of information about the user specified by the required user_id or screen_name parameter. The author's most recent Tweet will be returned inline when possible.
Well, the user profile image must be in there somewhere, correct?
Let's have a look at a typical response to a request for this information, using the users/show url (we'll use my profile as an example).
I've cut off some from the bottom, because there is a lot of data to go through. Most importantly, you'll see what you require:
This is the profile_image_url key that you need to get access to.
So, how do you do all this? It's pretty simple, actually.
Authenticated Requests
As you rightly pointed out, as of June 11th 2013 you can't make unauthenticated requests, or any to the 1.0 API any more, because it has been retired. So OAuth is the way to make requests to the 1.1 API.
I wrote a stack overflow post with an aim to help all you guys make authenticated requests to the 1.1 API with little to no effort.
When you use it, you'll get back the response you see above. Follow the posts instructions, step-by-step, and you can get the library here (you only need to include one file in your project).
Basically, the previous post explains that you need to do the following:
Create a twitter developer account
Get yourself a set of unique keys from twitter (4 keys in total).
Set your application to have read/write access
Include TwitterApiExchange.php (the library)
Put your keys in a $settings array
Choose your URL and request method (Post/Get) from the docs (I put the link above!)
Make the request, that's it!
A practical example
I'm going to assume you followed the step-by-step instructions in the above post (containing pretty colour pictures). Here's the code you would use to get what you want.
// Require the library file, obviously
require_once('TwitterAPIExchange.php');
// Set up your settings with the keys you get from the dev site
$settings = array(
'oauth_access_token' => "YOUR_ACCESS_TOKEN",
'oauth_access_token_secret' => "YOUR_ACCESS_TOKEN_SECRET",
'consumer_key' => "YOUR_CONSUMER_KEY",
'consumer_secret' => "YOUR_CONSUMER_SECRET"
);
// Chooose the url you want from the docs, this is the users/show
$url = 'https://api.twitter.com/1.1/users/show.json';
// The request method, according to the docs, is GET, not POST
$requestMethod = 'GET';
// Set up your get string, we're using my screen name here
$getfield = '?screen_name=j7mbo';
// Create the object
$twitter = new TwitterAPIExchange($settings);
// Make the request and get the response into the $json variable
$json = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
// It's json, so decode it into an array
$result = json_decode($json);
// Access the profile_image_url element in the array
echo $result->profile_image_url;
That's pretty much it! Very simple. There's also users/lookup which effectively does the same thing, but you can:
Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters.
If you ever need to get more than one user's details, use that, but as you only require one user's details, use users/show as above.
I hope that cleared things up a bit!
You say you want to use Twitter API 1.1 and yet you don't want to authenticate your requests.
Unauthenticated requests are not supported in API v1.1. So please adjust to the API change. See updates :
https://dev.twitter.com/blog/planning-for-api-v1-retirement
https://dev.twitter.com/docs/rate-limiting/1.1
You can get image from profile_image_url field of https://api.twitter.com/1.1/users/show.json request. Either a id or screen_name is required for this method. For example :
GET https://api.twitter.com/1.1/users/show.json?screen_name=rsarver
See details here https://dev.twitter.com/docs/api/1.1/get/users/show
I try the above methods to get the profile URL but it does not work for me. I think because Twitter changes API v1.1 to API v2.0.
I found a simple method to get a profile URL.
I use Twitter API v2 there User Lookup -> User by Username API part
Code Sample:
https://api.twitter.com/2/users/by/username/{user_name}?user.fields=profile_image_url
For Example:
https://api.twitter.com/2/users/by/username/TwitterDev?user.fields=profile_image_url
Of course, You should request with your Bearer Token then it properly work. For that, I recommend a platform it calls postman. It really helps for calling API.
Above example code return JSON like this:
{
"data": {
"name": "Twitter Dev",
"profile_image_url": "https://pbs.twimg.com/profile_images/1445764922474827784/W2zEPN7U_normal.jpg",
"username": "TwitterDev",
"id": "2244994945"
}
}
Additional:
If You want the Profile Image to be a higher size. Then you can put size in place of normal in the URL. For More Details read this one
Like This:
https://pbs.twimg.com/profile_images/1445764922474827784/W2zEPN7U_400x400.jpg
Give a vote to help more developers. 🍵
As the previous answers and comments point out:
Twitter API v1.0 is deprecated
Twitter API v1.1 requires OAuth
OP (#Steffi) doesn't want to authenticate
Pick any two; with all three it's a no-go. #Jimbo's answer is correct (and the proper way to do it), but excludes #3. Throwing out #1 means going back in time. But, we can throw out #2, and go directly to the source:
curl -s https://twitter.com/EA_FIFA_FRANCE |
sed -ne 's/^.*ProfileAvatar-image.*\(https:[^"]*\).*$/\1/p'
The sed command just says, find the line that contains "ProfileAvatar-image" and print the substring that looks like a quoted URL.
This is less stable than an authenticated API call, since Twitter may change their HTML at any time, but it's easier than dealing with OAuth, and no official rate limits!
The PHP translation should be straightforward.
try this
http://api.twitter.com/1/users/profile_image/{twitter_account}.xml?size=bigger
In API 1.1 the only way is to connect your application, retrieve the user by
https://dev.twitter.com/docs/api/1.1/get/users/show
and retrieve after his picture
profile_image_url
Hare is a very simple way to get Twitter Profile picture.
http://res.cloudinary.com/demo/image/twitter_name/w_300/{User_Name}.jpg
it's my Profile picutre:
Big: http://res.cloudinary.com/demo/image/twitter_name/w_300/avto_key.jpg
Small: http://res.cloudinary.com/demo/image/twitter_name/w_100/avto_key.jpg
you can regulate size by this part of URL - w_100, w_200, w_500 and etc.

Issue with LinkedIn API call after OAuth authentication

I've successfully made my way through the LinkedIn OAuth process (using the REST API - OAuth 1.0a). However I'm having trouble with my first API call after the callback. I set the UserToken, UserTokenSecret and UserVerfier in the library I am writing, and this call this function to get my profile information:
public function getUserProfile()
{
$consumer = new OAuthConsumer($this->consumer_key, $this->consumer_secret, NULL);
$auth_token = new OAuthConsumer($this->getUserToken(), $this->getUserTokenSecret());
$access_token_req = new OAuthRequest("GET", $this->access_token_endpoint);
$params['oauth_verifier'] = $this->getUserVerifier();
$access_token_req = $access_token_req->from_consumer_and_token($this->consumer,
$auth_token, "GET", $this->access_token_endpoint, $params);
$access_token_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,
$auth_token);
$after_access_request = $this->doHttpRequest($access_token_req->to_url());
$access_tokens = array();
parse_str($after_access_request,$access_tokens);
# line 234 below
$access_token = new OAuthConsumer($access_tokens['oauth_token'], $access_tokens['oauth_token_secret']);
// prepare for get profile call
$profile_req = $access_token_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$profile_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($profile_req->to_url());
var_dump($after_request);
}
The function var_dumps a string, which is the basic synopsis of my profile:
string(402) " User Name etc. etc. http://www.linkedin.com/profile?viewProfile=&key=28141694&authToken=HWBC&authType=name&trk=api*a137731*s146100* "
That's good. However, the minute I refresh the page, the same function call fails with:
Undefined index: oauth_token, line number: 234
(this line marked with comment in above code block).
Then, of course, the var_dump reports this error from LinkedIn:
string(290) " 401 1310652477038 R8MHA2787T 0 [unauthorized]. The token used in the OAuth request is not valid. "
something to note:
the user token, secret, and verifier are persisted during the initial authorization callback (right before this function is called). So, they are the same during the first call (when it works, right after coming back from linkedin) and during a page reload (when it fails on line 234).
Also, I must admit I'm not 100% sure I understand everything that's going on in this function. I actually took examples from this tutorial (about a different service, not linkedin) http://apiwiki.justin.tv/mediawiki/index.php/OAuth_PHP_Tutorial and combined it with the information I gathered from the LinkedIn API documentation, spread throughout their developer site. Most notable was the addition of the 'verifier' which the tutorial did not use.
Any insight into this problem would be greatly appreciated. Thanks in advance.
-Nick
UPDATE
The only way I've been able to get this going is to do a new OAuth handshake every single time. Is this the way it's supposed to happen? I was under the impression that once I got my user token/secret and verifier, that I could then use these for continuous API calls until the token expired or was revoked.
As it is now, every time the page reloads I'm requesting a new user token, secret and verifier, then immediately calling to get the user profile (which succeeds). Next reload, I get a whole new key/secret and verifier. Seems like quite a lot of work for each call, and as I understood it, you should be able to perform offline operations with this method - and if I need new authorization each time, then I guess I can't do that?
Well. I've finally figured out what was going on so thought I'd post the answer here, just in case someone else runs into this.
The example that I was using as a guide was flawed. After the access token is retrieved, you should then create a new OAuthRequest object, instead of using the existing $access_token_req instance.
So this:
// prepare for get profile call
$profile_req = $access_token_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$profile_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($profile_req->to_url());
Should be changed to this:
$api_req = new OAuthRequest("GET", $this->api_url.$api_call);
// prepare for get profile call
$api_req = $api_req->from_consumer_and_token($consumer,
$access_token, "GET", $this->api_url.'/v1/people/~');
$api_req->sign_request(new OAuthSignatureMethod_HMAC_SHA1(),$consumer,$access_token);
$after_request = $this->doHttpRequest($api_req->to_url());

Categories