How to interact with XBox API using PHP and cURL - php

I am trying to learn how to interact with the unofficial xbox api (xboxapi.com) but I can't seem to figure out how to use it. The documentation is very scarce. This is my most recent (and what i thought best) attempt.
<?php
$gamertag = rawurlencode("Major Nelson");
$ch = curl_init("http://www.xboxapi.com/v2/xuid/" . $gamertag);
$headers = array('X-Auth: InsertAuthCodeHere', 'Content-Type: application/json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers ); # custom headers, see above
$xuid = curl_exec( $ch ); # run!
curl_close($ch);
echo $xuid;
?>
Upon running the above I get "301 Moved Permanently". Can anyone see what i am doing wrong? Thanks.

You need to replace xuid with your actual xbox profile user id.
Additionally replace InsertAuthCodeHere with your API auth code.
You can find both on your xboxapi account profile after logging into xbox live.
See: https://xboxapi.com/v2/2533274813081462/xboxonegames
Update - Guzzle
I was able to get it working with Guzzle, works with http or https
require __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/config.php'; //defines XboxAPI_Key
$gamertag = isset($_GET['gamertag']) ? urldecode($_GET['gamertag']) : 'Major Nelson';
$url = 'http://xboxapi.com/v2/xuid/' . rawurlencode($gamertag);
$guzzle = new GuzzleHttp\Client();
$response = $guzzle->get($url, [
'headers' => [
'X-Auth' => XboxAPI_Key,
'Content-Type' => 'application/json'
],
]);
echo $response->getBody(); //2584878536129841
Update 2 - cURL
The issue is related to validating the SSL certificate via CURLOPT_SSL_VERIFYPEER => false and the redirect from http://www. to https:// occurring which is enabled with CURLOPT_FOLLOWLOCATION => true
require_once __DIR__ . '/config.php';
$gamertag = isset($_GET['gamertag']) ? urldecode($_GET['gamertag']) : 'Major Nelson';
$url = 'http://www.xboxapi.com/v2/xuid/' . rawurlencode($gamertag);
/**
* proper url for no redirects
* $url = 'https://xboxapi.com/v2/xuid/' . rawurlencode($gamertag);
*/
$options = [
CURLOPT_RETURNTRANSFER => true, // return variable
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_SSL_VERIFYPEER => false, //do not verify SSL cert
CURLOPT_HTTPHEADER => [
'X-Auth: ' . XboxAPI_Key
]
];
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
echo $content; //2584878536129841

I got an answer. We were missing required curly braces. Working code:
$gamertag = rawurlencode("Major Nelson");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://xboxapi.com/v2/xuid/{$gamertag}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"X-Auth: InsertAuthCode",
]);
$output = curl_exec($ch);
curl_close ($ch);
print $output;

Related

How do I use Oauth2 using cURL and PHP

I can't get the folling script to work:
I'm using an api called swiftdil. Their example is as follows:
Example request:
curl -X POST https://sandbox.swiftdil.com/v1/oauth2/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-u 'your_username:your_password'
Example output:
{
"access_token":"your_access_token",
"expires_in": 3600,
"refresh_expires_in": 1800,
"refresh_token": "your_refresh_token",
"token_type": "bearer",
"not-before-policy": 0,
"session_state": "your_session_state"
}
So the url I've to submit my credentials to is https://sandbox.swiftdil.com/v1/oauth2/token
I've tried the following code:
// Api Credentials
$url = 'https://sandbox.swiftdil.com/v1/oauth2/token';
$username = "my_username";
$password = "my_password";
// Set up api environment
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:
application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" .
$password);
// Give back curl result
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$curl_error = curl_error($ch);
curl_close($ch);
print_r($output);
print_r($info);
print_r($curl_error);
?>
The script is giving me back the following result:
HTTP/1.1 400 Bad Request Server: nginx/1.13.8 Date: Tue, 15 May 2018 09:17:26 GMT Content-Type: text/html Content-Length: 173 Connection: close
400 Bad Request.
Am I missing something? I do fullfill the needs of the example given above right? I do make a postcall, give all the credenatials as asked, but still can't get anything back.
I am not a PHP developer, I mostly do JavaScript. When I integrate with other REST services I tend to use Postman (https://www.getpostman.com/).
Try the following:
Attempt to successfully connect with the API using Postman (should be relatively straightforward).
When successful, Postman has the ability to generate PHP code automatically, which you can then copy and paste. Works like a charm with JavaScript, don't see why it will be any different with PHP.
I just filled in the details in postman based on what you provided:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://sandbox.swiftdil.com/v1/oauth2/token",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQ=",
"Content-Type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Please note, 'Authorization: Basic' can be used as basic authorization mechanism instead of 'Bearer' (it should work too). So replace 'bXlfdXNlcm5hbWU6bXlfcGFzc3dvcmQ' with the base64 encoded string 'username:password' (use actual username and password).
You also need to set the curl post fields by setting the below option as per your data.
"curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
))";
If still not work, you can find the curl error as :
if(curl_error($ch))
{
echo 'error:' . curl_error($ch);
}

API has redirecting page - PHP

I need to send data to an API using PHP. The API has a redirect page before showing the final result. The following code shows the content of the redirecting page rather than the final result. How can I wait until the final result?
$url = 'https://example.com/api';
$data = array('text' => "try");
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'GET',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
echo $result;
P.S. I got this code from one of stackoverflow's questions.
You could use cURL to get the final response, using CURLOPT_FOLLOWLOCATION:
From documentation :
CURLOPT_FOLLOWLOCATION: TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
$url = 'https://example.com/api';
$data = array('text' => "try");
$full_url = $url . (strpos($url, '?') === FALSE ? '?' : '')
. http_build_query($data) ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $full_url) ;
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-type: application/x-www-form-urlencoded',
]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close ($ch);
var_dump($response) ;

Connecting to Outbrain API using PHP

I need to connect to the Outbrain API (This is the documentation: http://docs.amplifyv01.apiary.io/#).
There's a minor example in there, but when I tried connecting to my own account I didn't manage to do so...
Can't understand if I put the wrong CURLOPT_URL or didn't write my credentials in the right form... This is my code:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.outbrain.com/amplify/v0.1/login");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: BASIC BASE-64-ENC(USERNAME:PASSWORD)",
"OB-TOKEN-V1: MY_ACCESS_TOKEN"
));
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
If anyone knows why it didn't worked - I'd very much appreciate it...
Also if anyone has an additional code for talking with the Outbrain API - It'll help me a lot.
Thank you!
<?php
$outbrain_user = 'xxx';
$outbrain_pass = 'xxx';
// Basic access authentication
$enc_credentials = base64_encode($outbrain_user.':'.$outbrain_pass);
$ba_authenticacion = 'Basic '.$enc_credentials;
$auth_header = array(
'Authorization: '.$ba_authenticacion
);
$outbrain_api_endpoint = 'https://api.outbrain.com/amplify/v0.1/';
// authentication
$auth_url = $outbrain_api_endpoint.'/login';
$curl = curl_init();
curl_setopt_array($curl,
array(
CURLOPT_URL => $auth_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $auth_header
)
);
$json_access_token = curl_exec($curl);
// parsing json object to string
$token_object = json_decode($json_access_token);
$token_array = get_object_vars($token_object);
// api access_token
$access_token = $token_array['OB-TOKEN-V1'];
Basically you got a wrong syntax while parsing CURLOPT_HTTPHEADER array,
also outbrain uses a basic access authentication, you can check here for docs https://en.wikipedia.org/wiki/Basic_access_authentication.
With this code you can return the access_token from outbrain.

Coinbase button creation and callback

Im trying to create a button and assign a callback URL with coinbase.
I'm getting some CAPTCHA data returned when trying to post to coinbase API.
I think my webhost is getting blocked by CloudFlare, disabling my code.
Here's what I have:
<a class="coinbase-button" data-code="<?php
$data = array(
"button" => array(
"name" => "Ticket",
"price_string" => "0.01",
"price_currency_iso" => "BTC",
"custom" => $OrderNext . "- " . $ticket,
"callback_url" => "https://x.com/callback.php",
"description" => "Ticket - " . $ticket ,
"type" => "buy_now",
"style" => "buy_now_large"
)
);
$json_data = json_encode($data);
$ch = curl_init("https://coinbase.com/api/v1/buttons?api_key=xxxxxxxxxxxxxxxxxxxxxx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
if( ! $output = curl_exec($ch))
{
trigger_error(curl_error($ch));
}
$result = json_decode($output);
$output returns a CAPTCHA page.
$result is null.
Thanks for any help.
Brian from Coinbase here. It looks like you are hitting the API to generate a new payment button for each page load which, depending on the amount of traffic you get, could trigger our rate limiting either internally or through CloudFlare.
We currently have the merchant create button api limited to 10,000 calls per day internally, for example, for most merchants.
A better approach would be to hit the API once for each product (or if the price changes) and store the resulting 'code' parameter. If you save this in your database you can reuse it on every page load. This will help your pages load faster also.
More details: https://coinbase.com/api/doc/1.0/buttons/create.html
Hope it helps!
I never used coinbase but have you checked if your host does have curl support enabled in phpinfo()? Or maybe curl_init / curl_exec is in the list of disabled functions.
EDIT:
you're using a https url, you must either provide the CA certificate to be checked against setting the flag CURLOPT_CAINFO, or disable the verification of the certificate setting the CURLOPT_SSL_VERIFYPEER to false.
You can use code like this for generating button for payment
$apikey ="***************";
$apisecret = "************************";
$nonce = sprintf('%0.0f',round(microtime(true) * 1000000));
$url = "https://api.sandbox.coinbase.com/v1/buttons?nonce=" . $nonce;
$parameters = [];
$parameters["button"]["name"] = "Checkout Invoice";
$parameters["button"]["custom"] = $orderId;
$parameters["button"]["price_string"] = $priceString;
$parameters["button"]["type"] = "buy_now";
$parameters["button"]["subscription"] = false;
$parameters["button"]["price_currency_iso"] = "USD";
$parameters["button"]["description"] = "Checkout Invoice";
$parameters["button"]["style"] = "custom_large";
$parameters["button"]["include_email"] = true;
$parameters["button"]["callback_url"] = url("bitcoin/callback");
$parameters = http_build_query($parameters, true);
$signature = hash_hmac("sha256", $nonce . $url . $parameters, $apisecret);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
"ACCESS_KEY: " . $apikey,
"ACCESS_NONCE: " . $nonce,
"ACCESS_SIGNATURE: " . $signature
)));
curl_setopt_array($ch, array(
CURLOPT_POSTFIELDS => $parameters,
CURLOPT_POST => true,
));
$response = curl_exec($ch);
curl_close($ch);
$decodeResponse = json_decode($response);
It will return to button code for payment on coinbase.

Bing API Authorization not working - The authorization type you provided is not supported. Only Basic and OAuth are supported

I recently got an email from Microsoft saying that the Bing API was moving to the Windows Azure Marketplace. It seemed that the main difference between the new request was the authentication.
After reading many posts on forums, I found this:
$accountKey = '#########';
$api = 'https://api.datamarket.azure.com/Bing/Search/Web?$format=json&$top=8&Query=';
$context = stream_context_create(array(
'http' => array(
'request_fulluri' => true,
'header' => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
)
));
$request = $api.'%27'.$q.'%27&$skip='.$start;
$result = file_get_contents($request, 0, $context);
However, I still get the error "The authorization type you provided is not supported. Only Basic and OAuth are supported".
Does anyone know how I can fix this. I have also tried cURL and that doesn't work.
Thanks to anyone who can find me a solution.
I think the URLs have changed. This code works. Note the URL in the first line:
$api = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?$format=json&$top=8&Query=';
$context = stream_context_create(array(
'http' => array(
'request_fulluri' => true,
'header' => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
)
));
$q = 'test';
$request = $api.'%27'.$q.'%27';
echo file_get_contents($request, 0, $context);
Here is working example of Search API just replace your access key with "XXXX". Even i wasted quite a few hours to get it work using cURL but it was failing cause of "CURLOPT_SSL_VERIFYPEER" on local :(
$url = 'https://api.datamarket.azure.com/Bing/Search/Web?Query=%27xbox%27';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, "username:XXXX");
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($process);
# Deliver
return $response;
# Have a great day!
curl_close($process);
I met the same problem, now fixed, the root_url has changed, it is now something like:
https://user:yourAccountKey#api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27leo%20fender%27&Market=%27en-US%27&$top=50&$format=JSON">
I had the same problem which occured when I deployed a website to a new server. I think my hosting company disabled some functionality with file_get_contents to external links.
$url = 'https://api.datamarket.azure.com/Data.ashx/Bing/MicrosoftTranslator/v1/Translate?Text=%27'.urlencode($text).'%27&To=%27' . $to . '%27&From=%27' . $from . '%27&$top=100&$format=json';
$accountKey = 'APIKEY';
$handle = curl_init ($url);
if ($handle) {
$curlOptArr = array(
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $accountKey . ':' . $accountKey,
CURLOPT_RETURNTRANSFER => TRUE
);
curl_setopt_array($handle, $curlOptArr);
$response = curl_exec($handle);
$data = json_decode($response,true);
if (is_array($data)) {
if (isset($data['d']['results'][0]['Text'])) {
print $data['d']['results'][0]['Text'];
} else {
print false;
}
} else {
print $text;
}
$errRet = curl_error($handle);
curl_close($handle);
}
This one works for me when using cURL.

Categories