I am trying to create a new listing on Etsy.
I used oauth to authenticate and got
OAUTH_CONSUMER_KEY
and
OAUTH_CONSUMER_SECRET
I check it with this code and I got return og all the seller data, so everything is ok with the OAuth.
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken("key","secret");
try {
$data = $oauth->fetch("http://openapi.etsy.com/v2/users/__SELF__", null, OAUTH_HTTP_METHOD_GET);
$json = $oauth->getLastResponse();
print_r(json_decode($json, true));
} catch (OAuthException $e) {
error_log($e->getMessage());
error_log(print_r($oauth->getLastResponse(), true));
error_log(print_r($oauth->getLastResponseInfo(), true));
exit;
}
I am trying to crate a new listings. First i managed to create a new listing through the api browser on the production. Now, i want to create a new listing through PHP. This is what i did, and it return my error:
This is my code:
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken("key","secret");
try {
$url = "http://openapi.etsy.com/v2/listings";
$params = array('description' => 'thisisdesc','materials' => 'yes','price'=>"5.99"
,'quantity'=>"2",'shipping_template_id'=>"52299",'shop_section_id'=>"1"
,'title'=>"thisistitle",'category_id'=>"i_did",'who_made'=>"5.99"
,'is_supply'=>"1",'when_made'=>"2010_2012");
$oauth->fetch($url, $params, OAUTH_HTTP_METHOD_POST);
print_r(json_decode($json, true));
} catch (OAuthException $e) {
print_r($e);
error_log($e->getMessage());
error_log(print_r($oauth->getLastResponse(), true));
error_log(print_r($oauth->getLastResponseInfo(), true));
exit;
}
I get the response of:
Invalid auth/bad request (got a 403, expected HTTP/1.1 20X or a redirect)
This method not accessible to restricted API key.
If you are still developing your application you can create listings without gaining full API access, so long as the shop is on your account. Make sure you parse in listings_w as a permission scope when making the first OAUTH request. I have altered the example provided by ETSY in the code below.
// instantiate the OAuth object
// OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET are constants holding your key and secret
// and are always used when instantiating the OAuth object
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
// make an API request for your temporary credentials
$req_token = $oauth->getRequestToken("https://openapi.etsy.com/v2/oaut/request_token?scope=email_r%20listings_r%20listings_w", 'oob');
print $req_token['login_url']."\n";`
Notice the scope=email_r%20listings_r%20listings_w;
Hope this helps
Aha, here's the answer. From an Etsy developer:
Your API was not yet approved for full API access. I've fixed that, so you should be able to use those methods now.
Hence, get in touch with the firm, and ask for your key to be approved.
Related
I'm trying to access public information for a user based on their username/pagename.
I'm doing this:
$uname = 'csga5000';
$session = new Facebook\Facebook([
'app_id' => self::$FACEBOOK_APP_ID,
'app_secret' => self::$FACEBOOK_APP_SECRET,
'default_graph_version' => 'v2.2'
]);
try {
// Returns a `Facebook\FacebookResponse` object
$response = $session->get('/search?q='+$uname+'&type=user');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
print_r($e);
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
But the exception is thrown, here is the output:
Graph returned an error: (#803) Some of the aliases you requested do not exist: v2.20
Alternatively(Got this from looking at the source code)
$response = $session->sendRequest('GET','/search',['q'=>$uname,'type'=>'user']);
Returns "Graph returned an error: An access token is required to request this resource." I stole a reference from somewhere using app id and secret as the token in this format:
$response = $session->sendRequest('GET','/search',['q'=>$uname,'type'=>'user'], self::$FACEBOOK_APP_ID.'|'.self::$FACEBOOK_APP_SECRET);
This throws: "Graph returned an error: A user access token is required to request this resource."
I don't understand why a USER access token is required :/
Anyone know how to search for a user based on username in php? I've seen other examples that were slightly outdated, but I was pretty much the same as what they claim worked.
Edit:
The information we want to acquire is primarily follower count.
First of all, you can´t search for users by username anymore. Earlier this was possible by just using a simple API call: graph.facebook.com/username
This does not work anymore, and the Search API only allows to search for the name (first/last). You are not supposed to use the username anymore.
That being said, you need to authorize yourself and use a User Token, as the error message tells you. That´s just how it is, and you can read it in the docs too:
Searches across Page and Place objects requires an app access token.
All other endpoints require a user access token.
Source: https://developers.facebook.com/docs/graph-api/using-graph-api/v2.4#search
More information about Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
It seems to be the case that it's not possible(at the time) to access more than a user's name publicly. OAuth is required to access the public profile (which is a default permission).
Using the graph api explorer you can verify this using the endpoint /{user-id} and trying to get additional information for a user with whatever id.
The return is like this:
{
"name": "John Doe",
"id": "100003216243221"
}
You can get first and last name as well, by appending:
?fields=name,first_name,last_name
But access to other information fails, even when public. (I only tested location, which clearly has an additional permission).
EDIT!
HOWEVER:
If you wish to access a facebook page, some information is accessible.
This is some of the information returned if no fields are specified: about, id, can_post, category, check_ins, has_added_app, is_community_page, is_published, likes, link, location, name, phone, talking_about_count, username, website, were_here_count.
Using the endpoint:
{page-username-or-id}?fields=engagement,is_permanently_closed,emails,picture
Can retrieve other information fields (assuming they're public).
So code for this:
Facebook sdk v4:
$session = FacebookSession::newAppSession();
$session->validate();
$ret = new FacebookRequest(
$session, 'GET', '/'.$uname.'?fields=name,engagement,phone,link,is_community_page,is_permanently_closed,influences,hometown,general_info,emails,bio,birthday,description,location,username,likes,picture'
);
$ret = $ret->execute()->getGraphObject()->asArray();
If you want to catch exceptions, you can look the thrown exceptions up: https://developers.facebook.com/docs/php/
This works for the same request for facebook sdk v5 (though, I don't know that the way I called send request is advised):
$uname = 'tbdsolutions5000';
$session = new Facebook\Facebook([
'app_id' => self::$FACEBOOK_APP_ID,
'app_secret' => self::$FACEBOOK_APP_SECRET,
'default_graph_version' => 'v2.2'
]);
try {
$response = $session->sendRequest('GET','/'.$uname,[
//Optionally:
//'fields' => 'comma, separated, fields'
],
self::$FACEBOOK_APP_ID.'|'.self::$FACEBOOK_APP_SECRET
);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
print_r($e);
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$response = $response->getGraphObject()->asArray();
So I admittedly am quite new to the facebook Graph api, but what I want to do feels like it should be doable.
All I want to do is display posts from a facebook page that is owned by me on a website.
Now I should say that I have achieved this with the api and the php sdk already, but its all of the access token stuff that is perplexing me, I just want a permanent access token so that I don't have to renew it in anyway.
Any help would be much appreciated
Just in case anyone landed on this question and was looking for direction on this subject too
$client = array(
"id" => {APP_ID},
"secret" => {APP_SECRET},
"token" => {ACCESS_TOKEN}, // Generated from the graph api explorer, with the 'manage_posts' extended permission ticked
"page" => {PAGE_ID}
);
FacebookSession::setDefaultApplication($client['id'], $client['secret']);
$session = new FacebookSession($client['token']);
try
{
$response = (new FacebookRequest($session, 'GET', '/oauth/access_token?grant_type=fb_exchange_token&client_id='.$client['id'].'&client_secret='.$client['secret'].'&fb_exchange_token='.$client['token']))->execute();
$results = $response->getGraphObject();
$data = $results->asArray();
$token = $data['access_token'];
$response = (new FacebookRequest($session, 'GET', '/'.$client['page'].'?fields=access_token'))->execute();
$results = $response->getGraphObject();
$data = $results->asArray();
echo "Access Token: ".$data['access_token']; // this is your never expiring access token
}
catch (FacebookRequestException $e) {
print_r($e);
}
catch (\Exception $e) {
print_r($e);
}
Obviously I do not recommend doing this in any form of production environment, but if you are in a local environment and just need the access token, feel free to use this to find out the access token.
Im using Facebook PHP SDK to exchange a short lived token for a new long lived token.
As it says here, you should just call a URL with these parameters:
GET /oauth/access_token?
client_id={app-id}
&client_secret={app-secret}
&grant_type=client_credentials
If I call this directly in browser, it works ok. I could just do a curl call and that would be ok. But I want stay close the oficial FacebookSDK, so in my Class I did this method:
public function renewToken($userShortToken, $redirectURI = FALSE) {
if ($redirectURI !== FALSE)
$this->redirectURI = $redirectURI;
$this->fbSession = new FacebookSession($userShortToken);
$params = '/oauth/access_token?grant_type=fb_exchange_token' .
'&client_id=' . $this->appId .
'&client_secret=' . $this->appSecret .
'&fb_exchange_token=' . $userShortToken .
'&appsecret_proof=' . hash_hmac('sha256', $userShortToken, $this->appSecret);
# About appsecret_proof: https://developers.facebook.com/docs/graph-api/securing-requests
$this->debug->log('params', $params);
try {
$request = new FacebookRequest($this->fbSession, 'GET', $params);
$this->debug->log('request', $params);
$response = $request->execute();
$this->debug->log('response', $response);
$object = $response->getGraphObject();
return $object;
} catch (FacebookRequestException $ex) {
$this->debug->log('FacebookRequestException', $ex);
} catch (\Exception $ex) {
$this->debug->log('FacebookRequestException', $ex->getMessage());
}
return FALSE;
}
PS: the "$userShortToken" is sent via Ajax to the server, after the user has logged in my website through Facebook Javascritp SDK.
So I see in my console these errors (im using FirePHP to output messages to console):
/oauth/access_token?grant_type=fb_exchange_token&client_id=305...57&client_secret=759...6c4&fb_exchange_token=CAAEV...lR&appsecret_proof=2e...76
You must provide or set a default application secret. FacebookRequestException /myserver/.../socialshare/MyClass.php:96
I cant understanding this message. I setted the app secret, the short token, all the necessary parameters in the URL. Even the "appsecret_proof" hash. It is all correct. If I copy the url and call the graph, it works and give me back the long Token.
Does someone have an idea how to stick with FacebookSDK or I should just drop that for this task? I just want to do this in the most correct possible way.
Thank you.
When I get this error it helped me to call
FacebookSession::setDefaultApplication($fbAppId, $fbAppSecret);
before creating a FacebookSession
I just upgraded to PHP 5.4.19 and facebook-php-sdk-v4.
Is it just me or has FB made the integration deliberately difficult?! For instance, I don't use Composer (can't install it on my shared host) so loading the new classes required a specific (discover-for-yourself) ordering - that was enough headache! The suggested solution at http://metah.ch/blog/2014/05/facebook-sdk-4-0-0-for-php-a-working-sample-to-get-started/ wasn't completely correct.
Anyway, when I finally got it to run and enabled "App Secret Proof for Server API calls" under the
App advanced settings tab as recommended by Facebook I got into a catch 22.
This is it:
1) To make an FB API call from my server, e.g. $request = new FacebookRequest($session, 'GET', '/me'); I must now provide an appsecret_proof argument.
2) To create an appsecret_proof I need an access_token i.e. $appsecret_proof= hash_hmac('sha256', $access_token, $app_secret);.
3) To get an access_token with only $_GET['code'] at this point, I must do code exchange via
GET https://graph.facebook.com/oauth/access_token?
client_id={app-id}
&redirect_uri={redirect-uri}
&client_secret={app-secret}
&code={code-parameter}.
4) To call FB for code exchange I get the error {"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100}}.
Two questions arise therefore:
1) How else can I get an access_token except via code exchange, so that I can use that token to create an appsecret_proof and in turn call FacebookRequest?
2) Where/How do I put that appsecret_proof into FacebookRequest? Is it perhaps this way $request = new FacebookRequest($session, 'GET', '/me', array("appsecret_proof" => $appsecret_proof));? I cannot seem to find the specific instruction on how to use appsecret_proof with PHP API (it is clear how to do it via http with Graph API).
Ladies and Gentlemen, I resolved it all - I just needed to use $access_token = $session->getToken();. This helped me negate the call for code exchange which was causing OAuthException because Facebook has since changed their policy on the exchange code from being used more than once.
Now "App Secret Proof for Server API calls" is properly enabled under the App advanced settings tab as recommended by Facebook.
So the specific solution in complete:
$app_id = 'APPID'; $app_secret = 'APPSECRET';
FacebookSession::setDefaultApplication($app_id, $app_secret);
$redirect_url = "https://mydomain.com/login";
$helper = new FacebookRedirectLoginHelper($redirect_url);
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
} catch (Exception $ex) {
}
if (isset($session)) {
$access_token = $session->getToken();
$appsecret_proof = hash_hmac('sha256', $access_token, $app_secret);
$request = new FacebookRequest($session, 'GET', '/me', array("appsecret_proof" => $appsecret_proof));
$response = $request->execute();
$graphObject = $response->getGraphObject();
echo print_r($graphObject, 1);
} else {
echo 'Login';
}
I'm using PECL OAuth with LinkedIn because it is working fine with Twitter and LinkedIn's GET requests. Will switch to LinkedIn's own OAuth libraries if this fails to work, but would prefer to do everything through the same OAuth library.
Code:
$xmlString = "<?xml version='1.0' encoding='UTF-8'?>".
"<mailbox-item>".
"<recipients>".
"<recipient>".
"<person path=\"/people/email={$person->PersonEmail}\">".
"<first-name>{$person->PersonFirstName}</first-name>".
"<last-name>{$person->PersonLastName}</last-name>".
"</person>".
"</recipient>".
"</recipients>".
"<subject>Invitation to Connect</subject>".
"<body>Please join my professional network on LinkedIn.</body>".
"<item-content>".
"<invitation-request>".
"<connect-type>friend</connect-type>".
"</invitation-request>".
"</item-content>".
"</mailbox-item>";
try {
$oauth = new OAuth(self::$apiKey, self::$secretKey, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM);
$oauth->setToken($accessToken, $accessTokenSecret);
$oauth->fetch("http://api.linkedin.com/v1/people/~/mailbox", $xmlString, OAUTH_HTTP_METHOD_POST, array('Content-Type'=>'text/xml'));
$result = $oauth->getLastResponse();
return $result;
} catch (OAuthException $e) {
var_dump($e);
throw new ModelException('Error - Invalid Access Token', ModelException::$excodes['invalid_access_token']);
}
This throws an exception which is caught, and the var_dump spits out a lot, primarily: "Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)"
I've tried a number of variations with the code. For example dropping the 'Content-Type'=>'text/xml' and that gives the same error. I've validated the xml and I know the access tokens are good, as I'm using them just fine to make GET requests.
Any help would be appreciated, thanks.
Found the solution, it was replacing
$oauth = new OAuth(self::$apiKey, self::$secretKey, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM);
with
$oauth = new OAuth(self::$apiKey, self::$secretKey, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);