Here below i have attached my api request
$apiKey = "XXXX";
$Secret = "XXX";
$endpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/hotels";
$request = new http\Client\Request("POST",
$endpoint,
[ "Api-Key" => $apiKey,
"X-Signature" => $signature,
"Accept" => "application/xml" ]);
try
{ $client = new http\Client;
$client->enqueue($request)->send();
$response = $client->getResponse();
if ($response->getResponseCode() != 200) {
printf("%s returned '%s' (%d)\n",
$response->getTransferInfo("effective_url"),
$response->getInfo(),
$response->getResponseCode()
);
} else {
printf($response->getBody());
}
} catch (Exception $ex) {
printf("Error while sending request, reason: %s\n",$ex->getMessage());
}'
getting following error
Uncaught Error: Class 'http\Client\Request' not found in
You need to add a use statement.
use http\Client\Request;
$request = new Request(blah blah);
Of course I assume you are using Composer autoloader. If not, you will also need to require_once() the file.
You can try using cURL instead of pecl_http. Here is an example:
<?php
// Your API Key and secret
$apiKey = "yourApiKey";
$Secret = "yourSecret";
// Signature is generated by SHA256 (Api-Key + Secret + Timestamp (in seconds))
$signature = hash("sha256", $apiKey.$Secret.time());
$endpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/status";
echo "Your API Key is: " . $apiKey . "<br>";
echo "Your X-Signature is: " . $signature . "<br><br>";
// Example of call to the API
try
{
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $endpoint,
CURLOPT_HTTPHEADER => ['Accept:application/json' , 'Api-key:'.$apiKey.'', 'X-Signature:'.$signature.'']
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Check HTTP status code
if (!curl_errno($curl)) {
switch ($http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
case 200: # OK
echo "Server JSON Response:<br>" . $resp;
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
echo $resp;
}
}
// Close request to clear up some resources
curl_close($curl);
} catch (Exception $ex) {
printf("Error while sending request, reason: %s\n",$ex->getMessage());
}
?>
Just make sure that first you uncomment ;extension=php_curl.dll in your php.ini file and restart your server.
We are planning to update our examples in the developer portal because some are outdated or not well documented.
Related
I am totally new to this hotelbed API, is there anybody done before please guide me how to get result from this API using Codeigniter frame work?
I have tried their code, but I couldn't:
<?php
$apiKey = " ";
$Secret = " ";
$signature = hash("sha256", $apiKey.$Secret.time());
$endpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/status";
//echo "Your API Key is: " . $apiKey . "";
//echo "Your X-Signature is: " . $signature . "";
try
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $endpoint,
CURLOPT_HTTPHEADER => ['Accept:application/json' , 'Api-key:'.$apiKey.'', 'X-Signature:'.$signature.'']
));
$resp = curl_exec($curl);
if (!curl_errno($curl)) {
switch ($http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
case 200: # OK
echo "Server JSON Response:" . $resp;
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
echo $resp;
}
}
curl_close($curl);
} catch (Exception $ex) {
printf("Error while sending request, reason: %s\n",$ex->getMessage());
}
?>
I ran this code and it was fine for me:
Server JSON Response:{"auditData":{"timestamp":"2017-11-09 10:25:04.503"},"status":"OK"}
It must be a problem with your setup. Have you uncommented php_curl & php_openssl in your php.ini? What server are you using?
Is the "Server JSON Response:" even printing at all?
Maybe try running an availability request and see if you are getting the same problem (https://github.com/hotelbeds-sdk/hotel-api-sdk-php/issues/107#issuecomment-342760756)
I'm new at Stripe integration. I've read the API documentation for Stripe and here is the OAuth flow. But I still don't receive any OAuth access token. Can someone explain how can I receive an access token? Thanks!
if (isset($_GET['code'])) { // Redirect w/ code
$code = $_GET['code'];
$token_request_body = array(
'grant_type' => 'authorization_code',
'client_id' => 'ca_32D88BD1qLklliziD7gYQvctJIhWBSQ7',
'code' => $code,
'client_secret' => ''
);
$req = curl_init(TOKEN_URI);
curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
curl_setopt($req, CURLOPT_POST, true );
curl_setopt($req, CURLOPT_POSTFIELDS, http_build_query($token_request_body));
// TODO: Additional error handling
$respCode = curl_getinfo($req, CURLINFO_HTTP_CODE);
$resp = json_decode(curl_exec($req), true);
curl_close($req);
echo $resp['access_token'];
} else if (isset($_GET['error'])) { // Error
echo $_GET['error_description'];
} else { // Show OAuth link
$authorize_request_body = array(
'response_type' => 'code',
'scope' => 'read_write',
'client_id' => 'ca_32D88BD1qLklliziD7gYQvctJIhWBSQ7'
);
$url = AUTHORIZE_URI . '?' . http_build_query($authorize_request_body);
echo "<a href='$url'>Connect with Stripe</a>";
}
You should use an OAuth 2.0 client library for this instead of attempting to roll this yourself as suggested by Stripe:
https://stripe.com/docs/connect/standalone-accounts#sample-code
There are many of these, but this is a pretty good option:
https://github.com/thephpleague/oauth2-client
You could modify this example and retrieve the account ID like so:
$provider->getResourceOwner($accessToken)->getId();
Once you retrieve the account ID, you'd store and use this to authenticate as the connected account as suggested by Stripe:
https://stripe.com/docs/connect/authentication#authentication-via-the-stripe-account-header
they actually have, what seems like, an official github library
and they have an example for the oauth thing
just missing in the docs for whatever reason...
https://github.com/stripe/stripe-php/blob/master/examples/oauth.php
in case they delete it, i include the file here, note: they make use of their library, so you have to install it prior to this to work
<?php
require('../init.php');
\Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
\Stripe\Stripe::setClientId(getenv('STRIPE_CLIENT_ID'));
if (isset($_GET['code'])) {
// The user was redirected back from the OAuth form with an authorization code.
$code = $_GET['code'];
try {
$resp = \Stripe\OAuth::token([
'grant_type' => 'authorization_code',
'code' => $code,
]);
} catch (\Stripe\Error\OAuth\OAuthBase $e) {
exit("Error: " . $e->getMessage());
}
$accountId = $resp->stripe_user_id;
echo "<p>Success! Account <code>$accountId</code> is connected.</p>\n";
echo "<p>Click here to disconnect the account.</p>\n";
} elseif (isset($_GET['error'])) {
// The user was redirect back from the OAuth form with an error.
$error = $_GET['error'];
$error_description = $_GET['error_description'];
echo "<p>Error: code=" . htmlspecialchars($error, ENT_QUOTES) . ", description=" . htmlspecialchars($error_description, ENT_QUOTES) . "</p>\n";
echo "<p>Click here to restart the OAuth flow.</p>\n";
} elseif (isset($_GET['deauth'])) {
// Deauthorization request
$accountId = $_GET['deauth'];
try {
\Stripe\OAuth::deauthorize([
'stripe_user_id' => $accountId,
]);
} catch (\Stripe\Error\OAuth\OAuthBase $e) {
exit("Error: " . $e->getMessage());
}
echo "<p>Success! Account <code>" . htmlspecialchars($accountId, ENT_QUOTES) . "</code> is disconnected.</p>\n";
echo "<p>Click here to restart the OAuth flow.</p>\n";
} else {
$url = \Stripe\OAuth::authorizeUrl([
'scope' => 'read_only',
]);
echo "Connect with Stripe\n";
}
I tried the below code though I am not sure whether these are the required set of scripts, but it didn't work and gives
SOAP-ERROR: Parsing WSDL: Couldn't load from : Start tag expected, '<' not found
$wsdlUrl = 'http://localhost/magento20_0407/soap/default?wsdl_list=1';
$apiUser = 'testUser';
$apiKey = 'admin123';
$token = 'xioxnuuebn7tlh8ytu7781t14w7ftwmp';
$opts = array('http' => array('method' => "GET", 'header' => "Accept-language: en\r\nConnection: close\r\n"));
$context = stream_context_create($opts);
stream_context_set_option($context, "http", "protocol_version", 1.1);
fpassthru(fopen($wsdlUrl, 'r', false, $context));
$opts = array('http'=>array('header' => 'Authorization: Bearer '.$token));
$serviceArgs = array("id"=>1);
try{
$context = stream_context_create($opts);
$soapClient = new SoapClient($wsdlUrl, array('version' => SOAP_1_2, 'context' => $context));
$soapResponse = $soapClient->customerCustomerAccountServiceV1($serviceArgs);
}catch(Exception $e){
$e->getMessage();
}
var_dump($soapResponse);exit;
Can anyone share the code to make SOAP connection in Magento2.x
In Magento1.x the below code works fine to connect SOAP
$apiUrl = 'http://localhost/magento_28_03/index.php/api/soap?wsdl';
$apiUser = 'testUser';
$apiKey = 'admin123';
ini_set("soap.wsdl_cache_enabled", "0");
try{
$client = new SoapClient($apiUrl, array('cache_wsdl' => WSDL_CACHE_NONE));
} catch (SoapFault $e) {
echo 'Error in Soap Connection : '.$e->getMessage();
}
try {
$session = $client->login($apiUser, $apiKey);
if($session) echo 'SOAP Connection Successful.';
else echo 'SOAP Connection Failed.';
} catch (SoapFault $e) {
echo 'Wrong Soap credentials : '.$e->getMessage();
}
But the above doesn't work for Magento 1. Can anyone say, what changes the above code needs to work fine for Magento 2?
For SOAP API call follow the below
test.php
<?php
$token = 'YOUR_ACCESS_TOKEN';
require('vendor/zendframework/zend-server/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client/Common.php');
$addArgs = array('num1'=>2, 'num2'=>1);// Get Request
$sumArgs = array('nums'=>array(2,1000));// Post request
//$wsdlUrl = YOUR_BASE_URL."soap?wsdl&services=customerAccountManagementV1,customerCustomerRepositoryV1,alanKentCalculatorWebServiceCalculatorV1";//To declar multiple
$wsdlUrl = YOUR_BASE_URL."soap?wsdl&services=alanKentCalculatorWebServiceCalculatorV1";
try{
$opts = ['http' => ['header' => "Authorization: Bearer " . $token]];
$context = stream_context_create($opts);
$soapClient = new \Zend\Soap\Client($wsdlUrl);
$soapClient->setSoapVersion(SOAP_1_2);
$soapClient->setStreamContext($context);
}catch(Exception $e){
echo 'Error1 : '.$e->getMessage();
}
try{
$soapResponse = $soapClient->alanKentCalculatorWebServiceCalculatorV1Add($addArgs);print_r($soapResponse);
$soapResponse = $soapClient->alanKentCalculatorWebServiceCalculatorV1Sum($sumArgs);print_r($soapResponse);
}catch(Exception $e){
echo 'Error2 : '.$e->getMessage();
}
?>
http://YOUR_BASE_URL/test.php
SOAP-ERROR: Parsing WSDL: Couldn't load from : Start tag expected, '<' not found
Tells you all you need to know; the URL you're trying to load isn't a proper WSDL.
What are the contents of: http://localhost/magento20_0407/soap/default?wsdl_list=1
I'm trying to revoke the access from a web app. This is my code:
When the user do login:
$scriptUri = "http:...";
$client = new Google_Client();
$client->setAccessType('online');
$client->setApplicationName('xxx');
$client->setClientId('xxx');
$client->setClientSecret('xxx');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('xxx'); // API key
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'));
$oauth2 = new Google_Service_Oauth2($client);
if (isset($_GET['code']) && isset($_GET["google"])){
$client->authenticate($_GET['code']);
$token = $client->getAccessToken();
$client->setAccessToken($token);
$_SESSION['google_token'] = $token;
}
And here is the code when I want to revoke the app:
$ch = curl_init("https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'].";");
curl_exec($ch);
curl_close($ch)
The result is a NOT FOUND page saying The requested URL /v2/{ "error" : "invalid_token"} was not found on this server.
I'm not sure if this is the correct way to revoke the access.
Thanks.
I tried your code and had the same error.
Take a look at how you have concatenated the strings at:
$ch = curl_init("https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'].";");
PHP easily lets committing syntax errors over concatenated strings. The fixed that worked for me was:
$RevokeTokenURL="https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'];
$ch = curl_init($RevokeTokenURL);
And in case you need it, my complete code is:
if(isset($_GET['action']) && $_GET['action'] == 'logout') {
session_destroy();
header('Location:'.$RedirectURL);
$RevokeTokenURL="https://accounts.google.com/o/oauth2/revoke?token=".$_SESSION['google_token'];
$ch = curl_init($RevokeTokenURL);
curl_exec($ch);
curl_close($ch);
}
I think this should work..
$revokeURL = "https://accounts.google.com/o/oauth2/revoke?token=".$access_token;
$ch = curl_init();
$options = array(
CURLOPT_URL => $revokeURL,
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true, //verify HTTPS
CURLOPT_SSL_CIPHER_LIST => 'TLSv1'); //remove this line if curl SSL error
curl_setopt_array($ch, $options); //setup
$response = curl_exec($ch); //run
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get HTTP code
if ($httpCode == 200)
{
echo "Success"; // .$response;
}
else
{
echo "Error : ".$httpCode."__".curl_error($ch);
}
curl_close($ch);```
Based on https://developers.google.com/accounts/docs/OAuth2WebServer#tokenrevoke
I have a video exist on my server,
I need to post that video on Facebook using Graph API.
Here is the code suggested by Team Facebook.
What I am doing is as below.
1) From an Android device I am getting an access token
2) Recognizing user by passing that access token to Facebook and get email id and through email id recognize user
3) Posting user's video from my server to Facebook through Graph API.
4) Returning a video id to android device as an API response.
I am approaching this route because in Android device it is 2 step process to post video on Facebook.
1) Download the video first
2) Post to Facebook
This is time consuming.
Here is the code that I am trying
define("FB_WEB_APP_ID","********");
define("FB_WEB_SECRET","********");
define("FB_WEB_REDIRECT_URI","<< redirect url >>");
$GLOBALS["all_user_dir_path"]="/var/www/proj/web/video/user_videos/";
define("FB_WEB_SCOPE","user_friends,email,public_profile,user_hometown,user_location,user_photos,user_videos,publish_actions,read_friendlists,publish_stream,offline_access");
define("FB_WEB_RESPONSE_TYPE","code%20token");
$GLOBALS["fb_app_creds"]=array();
$GLOBALS["fb_app_creds"]['appId']= FB_WEB_APP_ID;
$GLOBALS["fb_app_creds"]['secret']=FB_WEB_SECRET;
$GLOBALS["fb_app_creds"]['response_type']=FB_WEB_RESPONSE_TYPE;
$GLOBALS["fb_app_creds"]['redirect_uri']=FB_WEB_REDIRECT_URI;
$GLOBALS["fb_app_creds"]['scope']=FB_WEB_SCOPE;
$GLOBALS["facebook"] = new Facebook($GLOBALS["fb_app_creds"]);
class DefaultController extends Controller
{
// some code....
/**
* #Route("/gk",name="_fb")
* #Template()
*/
public function gkAction(Request $request){
$facebook = $GLOBALS["facebook"];
$access_token=$request->query->get("access_token");
if(!$access_token){
die("give access token in url.......");
}
echo "<pre>";
$facebook->setAccessToken($access_token);
$user = $facebook->getUser();
$me=$facebook->api("/me");
$email=$me['email'];
$all_user_dir_path=$GLOBALS["all_user_dir_path"];
$user_directory = str_replace(array(".","#"), "_",$email);
$user_dir_abs_path=$all_user_dir_path.$user_directory;
print_r($me);
$video_file_path=$user_dir_abs_path."/video.mp4";
if(file_exists($video_file_path))
{
echo "file exists...";
}else{
die("not exist");
}
$video_title="Test";
$video_desc="Test";
$access_token=$request->query->get("access_token");
$file = "#".$video_file_path;
$data = array('name' => 'file', 'file' => $file);
$post_url = "https://graph-video.facebook.com/me/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&". $access_token
;
echo "<hr>TRY 1<hr>";
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$res = curl_exec($ch);
$video_id=0;
if( $res === false ) {
}else{
$res=json_decode($res,true);
/* $video_id = $res['id'];*/
echo ":::: ";print_r($res);
}
curl_close($ch);
}catch(\Exception $e){
echo " Exception generated in Try 1 : ".$e->getMessage();
}
echo "<hr>TRY 2<hr>";
$params = array(
"access_token" => $access_token,
"name"=>"file",
"file" => "#".$video_file_path,
"title" => $video_title,
"description" => $video_desc
);
try {
$ret = $facebook->api('/me/videos', 'POST', $params);
print_r($ret);
} catch(\Exception $e) {
echo " Exception generated in Try 2 : ".$e->getMessage();
}
die("</pre>");
}
}
Output I am getting is An active access token must be used to query information about the current user. error and (#353) You must select a video file to upload.
Look at this image
Please tell me how to solve this problem ??
New code tried...................................................
/* code with sdk - object oriented way */
$file=$GLOBALS["all_user_dir_path"].$user_directory."/video.mp4";
$source = array();
$source['name']="video.mp4";
$source['type'] = "video/mp4";
$source['tmp_name'] = $file;
$source['error'] = 0;
$source['size'] = filesize($file);
echo "<br><br>$file<br><br>";
$params = array(
"access_token" => $access_token,
"source" => $source,
"title" => "testvideo",
"description" => "testvideo"
);
try {
$ret = $facebook->api('/me/videos', 'POST', $params);
echo 'Successfully posted to Facebook';
echo "<pre>";print_r($ret);echo "</pre>";
} catch(Exception $e) {
echo $e->getMessage();
}
but this gives (#353) You must select a video file to upload error
Here is the answer
public function shareSocialgrationFB($access_token,& $exception){
$video_id=0;
try{
$config = array();
$config['appId'] = FB_WEB_APP_ID;
$config['secret'] = FB_WEB_SECRET;
$config['fileUpload'] = true;
$config['cookie'] = true;
$facebook = new Facebook($config);
$facebook->setFileUploadSupport(true);
$facebook->setAccessToken($access_token);
$me=$facebook->api("/me");
$email=$me['email'];
$user_directory = str_replace(array(".","#"), "_",$email);
$file = $GLOBALS["all_user_dir_path"].$user_directory."/video.mp4";
$usersFacebookID=$facebook->getUser();
$video_details = array(
'access_token'=> $access_token,
'message'=> 'Testvideo!',
'source'=> '#' .realpath($file),
'title'=>'Test'
);
$post_video = $facebook->api('/'.$usersFacebookID.'/videos', 'post', $video_details);
$video_id=$post_video['id'];
}catch(\Exception $e){
//echo "Exception generated :: ".$e->getMessage();
$exception=$e->getMessage();
// extra code to handle exception
}
return $video_id;
}
Reference : How to POST video to Facebook through Graph API using PHP
I don't know why the info about configurations
$config['fileUpload'] = true;
$config['cookie'] = true;
is not mentioned at below official docs of APIs
https://developers.facebook.com/blog/post/493/
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/videos#publish
However solution given above, worked fine for me.
file is not a valid parameter. Instead of parameter file, use source.
Reference
For FB SDK4+Composer: (see the hardcoded video path, and the encoding).
Doc: https://developers.facebook.com/docs/php/gettingstarted/4.0.0
FB requests the video file to be passed encoded as form-data:
https://developers.facebook.com/docs/graph-api/reference/user/videos/
use Facebook\FacebookSession;
use Facebook\GraphSessionInfo;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
private function postFBVideo($authResponse, $filePath, $formDataMessage)
{
FacebookSession::setDefaultApplication('yourAppkey', 'yourAppSecret');
$ajaxResponse = '';
try {
$session = new FacebookSession($authResponse->accessToken);
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
$ajaxResponse = 'FB Error ->' . json_encode($ex) ;
} catch (\Exception $ex) {
// When validation fails or other local issues
$ajaxResponse = 'FB Validation Error - ' . json_encode($ex) ;
}
if ($session) {
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => new CURLFile('videos/81JZrD_IMG_4349.MOV', 'video/MOV'),
'message' => $formDataMessage,
)
))->execute();
$ajaxResponse = $response->getGraphObject();
}
return json_encode($ajaxResponse);
}