I've been trying to translate some PHP code to Python 3 but can't quite get it to work. In PHP I have the following:
$request = "https://api.example.com/token";
$developerKey = "Basic VVVfdFdfsjkUIHDfdsjYTpMX3JQSDNJKSFQUkxCM0p0WWFpRklh";
$data = array('grant_type'=>'password',
'username'=>'name',
'password'=>'pass',
'scope'=>'2346323');
$cjconn = curl_init($request);
curl_setopt($cjconn, CURLOPT_POST, TRUE);
curl_setopt($cjconn, CURLOPT_HTTPHEADER, array('Authorization: '.$developerKey));
curl_setopt($cjconn, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($cjconn, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($cjconn, CURLOPT_POSTFIELDS,http_build_query($data));
$result = curl_exec($cjconn);
curl_close($cjconn);
$tokens = json_decode($result,true);
$accesstoken = $tokens['access_token'];
echo $accesstoken."\n";
I tried converting it to the following in Python:
import pycurl, json
url = 'https://api.example.com/token'
data = json.dumps({"grant_type":"password",
"username":"name",
"password":"pass",
"scope":"2346323"})
key = 'Basic VVVfdFdfsjkUIHDfdsjYTpMX3JQSDNJKSFQUkxCM0p0WWFpRklh'
c = pycurl.Curl()
c.setopt(pycurl.URL,url)
c.setopt(pycurl.HTTPHEADER,['Authorization: {}'.format(key)])
c.setopt(pycurl.POST,1)
c.setopt(pycurl.POSTFIELDS,data)
c.perform()
But I get the following error:
<faultstring>String index out of range: -1</faultstring>
How can I correct this, or is there a more pythonic solution?
If anyone is interested in the solution, I came up with the following which worked:
def getToken(self):
"""Retrieves the token from provider"""
#The data to be passed to retrieve the token
tokenData = {'grant_type':'password',
'username':TOKENUSERNAME,
'password':TOKENPASSWORD,
'scope':TOKENSCOPE}
#The header parameters
header_params = {'Authorization':KEY}
#Make the request for the token
r = requests.post(TOKENURL,data=tokenData,headers=header_params)
#Check the status code
if r.status_code not in [200,203]:
self.log.logentry("There was an error retrieving the data from Linkshare: {}:{}".format(r.status_code,r.text))
sys.exit()
#Extract the data from the response
data = r.json()
#Parse the access token
token = {'token':data['access_token'],
'type':data['bearer']}
return token
Related
I have a Vimeo PRO account.
I have protected videos uploaded.
Videos are also set to ONLY be embeddable on my domains (set in the video settings)
I am -not- grasping how to use their examples (sorry, for me the examples do not include real working samples for me,..or at least how to implement them to understand.. so I'm hoping to get some help)
Not clear on all the OAuth2, Oembed... authentication stuff either.. which I believe is where my problem lies.
I was following this gitHub example:
https://github.com/vimeo/vimeo-api-examples/blob/master/oembed/php-example.php
(looks to be pretty old?)
I'm looking to get JSON data returned for a video when an ID is passed along.
I was/am under the impression that I need to 'authenticate' before I can get my response/return data?
Is this best done in the CURL header or something?
Can someone guide me a bit more? (shouldnt be this hard!) haha..
Here is my code:
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
//JSON url
//$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
//this fixes the cURL approach
$json_url = $video_endpoint . rawurlencode($video_url);
// Curl helper function
function curl_get($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization : bearer xxxxxx'));
$return = curl_exec($curl);
curl_close($curl);
return $return;
}
$vimeoJSON = json_decode((curl_get($json_url)));
var_dump($vimeoJSON);
And I get this response:
object(stdClass)#1 (1) { ["error"]=> string(52) "You must provide a valid authenticated access token." }
questions are:
1.) Is this even a valid approach? (assuming I just need to append some lines of code to the CURL header to send my auth over before getting a response?)
2.) How do I update my CURL snippet to work with VIEMO authentication?
I'm trying to keep this as CLEAN/SIMPLE as I can (for the JSON call/return portion)..
Any guidance is appreciated.
Thanks
update:
this code does NOT work:
$access_token = 'xxx';
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $json_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer ".$access_token
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The video I want to use is located here:
https://vimeo.com/171811266/5822169b48
IT IS A PRIVATE VIDEO. (not sure you'll be able to see it)..
When I use the latest version of the code posted above.. I get this response:
{"error":"The requested video could not be found"}
Is this because its a PRIVATE video?
(actually I just set the video to be able to be viewed by anyone.. and I still got the same error/response) (not found)
If so.. what is the fix to use MY videos.. that are set to private... but use them on my site/domain still?
===========================================================================
FINAL UPDATE:
Trying to use the code in the readme example:
https://github.com/vimeo/vimeo.php
Trying to use (un-successfully) the LIB #Dashron pointed me too.. I cant even seem to get the basics to work from the GIT Page:
Code:
//project vars
$client_id = 'xxxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$redirect_uri = 'http://domain.com/file.php'; //where do I redirect them back to? the page where I have the embeded video at?
// scope is an array of permissions your token needs to access. You can read more at https://developer.vimeo.com/api/authentication#scopes
$scopes = Array('public', 'private');
$state = 'Ldhg0478y';
require("Vimeo/autoload.php");
$lib = new Vimeo\Vimeo($client_id, $client_secret);
// build a link to Vimeo so your users can authorize your app. //whatever that means and is for?
$url = $lib->buildAuthorizationEndpoint($redirect_uri, $scopes, $state);
// redirect_uri must be provided, and must match your configured uri
$token = $lib->accessToken(code, redirect_uri);
// usable access token
var_dump($token['body']['access_token']);
// accepted scopes
var_dump($token['body']['scope']);
// use the token
$lib->setToken($token['body']['access_token']);
I get this error message:
Parse error: syntax error, unexpected Fatal error: Class 'Vimeo\Vimeo' not found in /usr/www/users/aaemorg/aaem.org/video/vimeo_lib.php
Seems like its not creating instantiating my $lib object/class??
(I know I'm not great at high level PHP class/code... but this absurdly hard just to get a JSON response for video I own to embed (again) on a site I own as well)
Any direction would be appreciated?
======================================================================
Update: "what worked for me"..
I am appreciate the link to the 'official' library.. but the readme examples just didnt work for me...
To keep things nice and easy for others who may be new to the Vimeo API stuff as well.. here is a quick and dirty, simple code sample to get you up and running:
<?
//include offifial library
require("Vimeo/autoload.php");
$client_id = 'xxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$video_id = 'xxx';
$lib = new Vimeo\Vimeo($client_id, $client_secret, $access_token);
$video_response = $lib->request('/videos/'.$video_id);
//dont really need this, but included in case there is some data you need to display
$token_response = $lib->clientCredentials();
//example of parsing out specific data from the array returned
//name/title
echo $video_response['body']['name'] . '<br><br>';
?>
The link you provided is very, very old. It is actually part of a different API, and no longer relevant.
The Library you should be using is located here: https://github.com/vimeo/vimeo.php with many examples in the readme, and the examples directory!
Below code works for me
Please follow this step before
Under video settings : General->privacy, Change Who can watch select box to Anyone.
$url = 'https://api.vimeo.com/videos/388591356';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
$headers[] = "Accept: application/json";
$headers[] = "Authorization: Bearer 969329f9b5b3882d74d1b39297528242";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$final_result = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $result), true );
echo "<pre>";
print_r($final_result);
I'm going to rewrite this POST request in python:
<?php
// Set these variables
$networkid = ""; // In your HasOffers system at Support -> API
$apikey = ""; // In your HasOffers system at Support -> API
$offerid = "0"; // Specify an offer ID to add the creative to
$creativetype = "image banner"; // Types: file, image banner, flash banner, email creative, offer thumbnail, text ad, html ad, hidden
$filename = "banner_728x90.gif"; // File name; no spaces, and file must be in same directory as this script
$display = $filename; // Or change this to the "display name" for this creative
// Don't change anything below here
$creativetype = urlencode($creativetype);
$display = urlencode($display);
$fields[$filename] = "#{$filename}";
$url = "http://api.hasoffers.com/v3/OfferFile.json?Method=create&NetworkToken={$apikey}&NetworkId={$networkid}&data[offer_id]={$offerid}&data[type]={$creativetype}&data[display]={$display}&return_object=1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$resp = curl_exec($ch);
curl_close($ch);
print_r(json_decode($resp, true)); // Final output; remove or change this if you want
?>
As I know, in pycurl the CURLOPT_POSTFIELDS attribute is absent. What can I use instead?
Thank you!
there are many python libraries that can be used:
http.client
https://docs.python.org/3.1/library/http.client.html
requests
https://pypi.python.org/pypi/requests/
the commands are pretty straightforwards:
using http.client:
import http.client
conn = http.client.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print(res.status, res.reason)
200 OK
or requests:
import requests
r = requests.get('https://github.com/timeline.json')
print r.json
Using HTTP client, a simple POST request may be done as follows:
connect = http.client.HTTPSConnection("base_url")
connect.request('POST', '/rest/api/'+ you_can_add_variables+ '/users?userEmail=' + another_variable, headers=headers)
Using requests:
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
the documentation provided above should not prove difficult to understand
I'm stuck trying to convert some sample Ruby API code from https://vircurex.com/welcome/api?locale=en to PHP. Here is the Ruby Code provided:
t = Time.now.gmtime.strftime("%Y-%m-%dT%H:%M:%S");
trx_id = Digest::SHA2.hexdigest("#{t}-#{rand}")
user_name = "MY_USER_NAME"
secret_word = "123456789"
tok = Digest::SHA2.hexdigest("#{secret_word};#{user_name};#{t};#{trx_id};create_order;sell;10;btc;50;nmc")
Order.call_https("https://vircurex.com", "/api/create_order.json?account=#{user_name}&id=#{trx_id}&token=#{tok}×tamp=#{t}&ordertype=sell&amount=10¤cy1=btc&unitprice=50¤cy2=nmc")
def self.call_https(my_url,my_params)
uri = URI.parse(my_url)
http = Net::HTTP.new(uri.host, '443')
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
response=""
resp=""
http.start do |http|
cmd = my_params
req = Net::HTTP::Get.new(cmd)
response = http.request(req)
resp = response.body
end
return ActiveSupport::JSON.decode(resp)
end
Here is what I attempted to come up with so far in PHP, but i know nothing of Ruby, so it is hard to figure out what the original code is doing:
date_default_timezone_set("UTC");
$t = date("Y-m-d H:i:s", time());
$trx_id = hash("sha256", $t."-".rand()); // i think this is wrong
$user_name = "MY_USER_NAME";
$secret_word = "123456789";
$tok = hash("sha256", $secret_word.";".$user_name.";".$t.";".$trx_id.";create_order;sell;10;btc;50;nmc");
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "https://vircurex.com/api/create_order.json?account=$username&id=$trx_id&token=$tok×tamp=$t&ordertype=sell&amount=10¤cy1=btc&unitprice=50¤cy2=nmc");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$resp = curl_exec($ch);
return json_decode($resp);
Can someone familiar with both languages please help me out? Thanks!
I get the following response with my code:
stdClass Object
(
[status] => 8003
[statustxt] => Authentication failed
)
So obviously, something is not being translated correctly. I just need to generate some working PHP code to use with the API listed. You can create an account to test the code if you like.
The problem is on two lines:
First, change this line:
$t = date("Y-m-d H:i:s", time());
to:
$t = date("Y-m-d\TH:i:s", time());
And second, fix this:
curl_setopt($ch, CURLOPT_URL, "https://vircurex.com/api/create_order.json?account=$username&id=$trx_id&token=$tok×tamp=$t&ordertype=sell&amount=10¤cy1=btc&unitprice=50¤cy2=nmc");
by changing $username param into $user_name:
curl_setopt($ch, CURLOPT_URL, "https://vircurex.com/api/create_order.json?account=$user_name&id=$trx_id&token=$tok×tamp=$t&ordertype=sell&amount=10¤cy1=btc&unitprice=50¤cy2=nmc");
I successfully received a valid response from Vircurex with another API call, as the create_order API is currently disabled as reported on Vircurex site. In any case, I've had no authentication problems.
NOTE: When the user accepts my permissions to use my app. I ask them to accept manage_notifications
I am so confused. I research this on the web and it seems I get a mix of deprecated and wrong information and I am trying to send a notification to the user using my facebook canvas app using facebook graph. the following is how I do it and its not working.
public function getAccessToken() {
$app_id = $this->settings['app_id'];
$app_secrete = $this->settings['app_secrete'];
$url = "https://graph.facebook.com/oauth/access_token?".
"client_id={$app_id}".
"&client_secret={$app_secrete}".
"&grant_type=client_credentials";
$c = curl_init($url);
// necessary so CURL doesn't dump the results on your page
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($c);
$result = explode("=", $result);
curl_close ($c);
return $result[1];
}
The result passes something like this access_token=523216317ewwer235|K4A1XugBpajwrweu1K2k12jzckdU . so that is why i explode the = sign within the code. I call this function every time the user enters my app. I take the access code and pass it as $token in the following code.
public function alertUser($userid,$token,$message="You have a notification") {
$inviteMessage = $message;
$inviteMessage = urlencode($inviteMessage);
$url = "https://graph.facebook.com/{$userid}/notifications?access_token={$token}&".
"template={$inviteMessage}&ref=notify";
$c = curl_init($url);
// necessary so CURL doesn't dump the results on your page
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($c);
curl_close ($c);
$r = json_decode($result);
}
and I get the following response
object(stdClass) {
error => object(stdClass) {
message => 'A user access token is required to request this resource.'
type => 'OAuthException'
code => (int) 102
}
}
You must use POST requests in order to make notifications work :
curl_setopt ($c, CURLOPT_POST, true);
Apparently you are making GET requests, trying to request a resource.
I'm trying to create a bucket on GCS using API v1.0 (interoperable mode) in PHP but I'm getting a 'signature does not match' error response.
Here's what I'm doing:
$access_id = "GOOGxxxxxx";
$secret_key = "xyxyxyxyx/xyxyxyxyx";
$bucket = "random_bucket_name";
$url = 'https://'.$bucket.'commondatastorage.googleapis.com';
$timestamp = date("r");
$canonicalizedResources = "/ HTTP 1.1";
$stringToSign = utf8_encode("PUT "."\n"."\n"."\n".$canonicalizedResources);
$signature = base64_encode(hash_hmac("sha1",$stringToSign,$secret_key,true));
$authSignature = $access_id.":".$signature;
$headers = array('Host: '.$bucket.'.commondatastorage.googleapis.com',
'Date: '.$timestamp, 'x-goog-api-version: 1',
'x-goog-project-id: xxxyyyxy','Content-Length: 0',
'Authorization: GOOG1 '.$authSignature);
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c,CURLOPT_HTTPHEADER,$headers);
$xml = curl_exec($c);
And here's the response that I get:
<?xml version='1.0' encoding='UTF-8'?>
<Error>
<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you
provided. Check your Google secret key and signing method.</Message>
<StringToSign>
GET
Sat, 03 Mar 2012 14:56:53 -0800
x-goog-api-version:1
x-goog-project-id:xxxyyyxy
/random_bucket_name/
</StringToSign>
</Error>
Any ideas where I'm going wrong?
Here's Google's documentation on this:
https://developers.google.com/storage/docs/reference-methods#putbucket
One thing I noticed is that even though I specify "PUT" in the "stringToSign" variable ... the response says that I used "GET" ... ?
Any help would be appreciated.
There are a few problems here:
Your canonicalized resource should be "/bucket/", not "/ HTTP 1.1".
You need to include your two custom headers (x-goog-version and x-goog-project-id) in the string to sign.
The string to sign must include the timestamp sent in the Date: header.
You need to set CURLOPT_PUT so that curl knows to send a PUT request, rather than the default GET request (that's why your error response alludes to a GET request).
Here's a corrected version of your code, which I tested and used to create a new bucket:
<?php
$access_id = "REDACTED";
$secret_key = "REDACTED";
$bucket = "your-bucket";
$url = 'https://'.$bucket.'commondatastorage.googleapis.com';
$timestamp = date("r");
$version_header = "x-goog-api-version:1";
$project_header = "x-goog-project-id:REDACTED";
$canonicalizedResources = "/".$bucket."/";
$stringToSign = utf8_encode("PUT\n\n\n".$timestamp."\n".$version_header."\n".$project_header."\n".$canonicalizedResources);
$signature = base64_encode(hash_hmac("sha1",$stringToSign,$secret_key,true));
$authSignature = $access_id.":".$signature;
$headers = array('Host: '.$bucket.'.commondatastorage.googleapis.com',
'Date: '.$timestamp, $version_header,
$project_header,'Content-Length: 0',
'Authorization: GOOG1 '.$authSignature);
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c,CURLOPT_HTTPHEADER,$headers);
curl_setopt($c, CURLOPT_PUT, TRUE);
$xml = curl_exec($c);
print($xml);
?>
P.S. All the details on HMAC authentication for Google Cloud Storage are provided here: https://developers.google.com/storage/docs/reference/v1/developer-guidev1#authentication