Token invalid - Error 401 in YouTube API - php

I am Working send message using youtuba api. But i got a Error on my file. it shows Invalid Token 401 Error. My file is given below.I'm pretty sure I must be missing something vital but small enough to not notice it.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = array('accountType' => 'GOOGLE',
'Email' => 'User Email',
'Passwd' => 'pass',
'source'=>'PHI-cUrl-Example',
'service'=>'lh2');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$kk = curl_getinfo($ch);
$response = curl_exec($ch);
list($auth, $youtubeuser) = explode("\n", $response);
list($authlabel, $authvalue) = array_map("trim", explode("=", $auth));
list($youtubeuserlabel, $youtubeuservalue) = array_map("trim", explode("=", $youtubeuser));
$developer_key = 'AI39si7SavL5-RUoR0kvGjd0h4mx9kH3ii6f39hcAFs3O1Gf15E_3YbGh-vTnL6mLFKmSmNJXOWcNxauP-0Zw41obCDrcGoZVw';
$token = '7zWKm-LZWm4'; //The user's authentication token
$url = "http://gdata.youtube.com/feeds/api/users/worshipuk/inbox" ; //The URL I need to send the POST request to
$title = $_REQUEST['title']; //The title of the caption track
$lang = $_REQUEST['lang']; //The languageof the caption track
$transcript = $_REQUEST['transcript']; //The caption file data
$headers = array(
'Host: gdata.youtube.com',
'Content-Type: application/atom+xml',
'Content-Language: ' . $lang,
'Slug: ' . rawurlencode($title),
'Authorization: GoogleLogin auth='.$authvalue,
'GData-Version: 2',
'X-GData-Key: key=' . $developer_key
);
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007">
<id>Qm6znjThL2Y</id>
<summary>sending a message from the api</summary>
</entry>';
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_HEADER, TRUE );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($xml) );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1 );
$tt = curl_getinfo($ch);
print_r($tt);
$result = curl_exec($ch);
print_r($result);
exit;
// close cURL resource, and free up system resources
curl_close($ch);
?>
any problem in my code? Please guide me. How can I get a result from this code?

Most likely your authentication is wrong, please debug that part first. Either you are not using right scope or that API is not enabled from your console.
On a separate note, I strongly suggest to use Youtube Data API v3 for this. We have updated PHP client library and great samples to get you started.

Related

Issue sending post request to API | PHP

Essentially I need to send the appropriate POST request to the following Parcel Tracking API that return the shipping data from the courier provided:
API Doc: https://www.kd100.com/docs/real-time-shipment-tracking
The problem I am having, is the response:
[code] => 104
[message] => Invalid signature
Can someone please have a look at my request below and tell me if I've made a mistake based on the doc? Assuming the Key, Secret Key and Tracking data is correct, my request should be completely valid.
My POST Request so far:
$key = 'KEY';
$secret = 'SECRET KEY';
$param = array (
'carrier_id' => 'usps',
'tracking_number' => 'TRACKING #'
);
$post_data = array();
$post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
$header_data = array();
$header_data['API-Key'] = $key;
$sign = md5($post_data['param'].$key.$secret);
$header_data['signature'] = strtoupper($sign);
$url = 'https://www.kd100.com/api/v1/tracking/realtime';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"signature: $sign",
"API-Key: $key"
));
$result = curl_exec($ch);
$data = json_decode($result, true);
echo '<br/><br/>Start:<br/><pre>';
echo print_r($data);
echo '</pre>';
Your signature is not in uppercase. You set $sign variable but never actually set uppercase to it. You actually set uppercase to $header_data['signature'] and then never use it.
$sign = md5($post_data['param'].$key.$secret);
$header_data['signature'] = strtoupper($sign);
Your problem should be solved if you write it like this:
$sign = strtoupper(md5(post_data['param'].$key.$secret));
Remember to clean your code. You don't actually use $header_data anywhere

Uniquely identify iOS device with DeviceCheck API and server side php code not working

I'm getting error : Missing or incorrectly formatted payload
I'm generating device token from Apple DeviceCheck API in swift language with real device and also passing Transaction ID to this php api.
jwt token generating successfully with this code but further code not working with apple query bit api.
This is my server side code in php :
<?php
require_once "vendor/autoload.php";
use Zenstruck\JWT\Token;
use Zenstruck\JWT\Signer\OpenSSL\ECDSA\ES256;
use \Ramsey\Uuid\Uuid;
$deviceToken = (isset($_POST["deviceToken"]) ? $_POST["deviceToken"] : null);
$transId = (isset($_POST["transId"]) ? $_POST["transId"] : null);
function generateJWT($teamId, $keyId, $privateKeyFilePath) {
$payload = [
"iss" => $teamId,
"iat" => time()
];
$header = [
"kid" => $keyId
];
$token = new Token($payload, $header);
return (string)$token->sign(new ES256(), $privateKeyFilePath);
}
$teamId = "#####";// I'm passing My team id
$keyId = "#####"; // I'm passing my key id
$privateKeyFilePath = "AuthKey_4AU5LJV3.p8";
$jwt = generateJWT($teamId, $keyId, $privateKeyFilePath);
function postReq($url, $jwt, $bodyArray) {
$header = [
"Authorization: Bearer ". $jwt
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyArray); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$server_output = curl_exec($ch);
//$info = curl_getinfo($ch);
// print_r($info);
//echo 'http code: ' . $info['http_code'] . '<br />';
//echo curl_error($ch);
curl_close($ch);
return $server_output;
}
$body = [
"device_token" => $deviceToken,
"transaction_id" => $transId,
"timestamp" => ceil(microtime(true)*1000)
];
$myjsonis = postReq("https://api.development.devicecheck.apple.com/v1/query_two_bits", $jwt, $body);
echo $myjsonis;
?>
Where is problem in this code? Or any other solution in php code.
Is there anything that I'm missing.
I just checked the Docs. They don't want POST fields like a form, they want a JSON body instead. Here's a snippet of code that you should be able to tweak to do what you require:
$data = array("name" => "delboy1978uk", "age" => "41");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
Actually, looking again at your code, it could be as simple as running json_encode() on your array.

Sending an voice file to API (laravel) - 5.4

I am trying to send a voice file to my api built in laravel. Everything seems right in my code but when i send the file to my api, i check at my api side if the data posted has file contained in it but i keep getting false. Am i posting my voice file wrongly.
Path: Absolute path
PHP version : 7.0
$endPoint = 'https://api.domain.com/api';
$apiKey = '**********';
$url = $endPoint . '?key=' . $apiKey;
$curlFile = new \CurlFile('/Users/public/Voice/aaaah.wav');
$data = [
'message' => 'First Voice',
'file' => $curlFile,
];
$ch = curl_init();
$headers = array();
$headers[] = "Content-Type: multipart/form-data";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
return $result;

JSON RPC 2.0 API Call using CURL in PHP - Changelly API

I am trying to call changelly API with below codes but it is returning "Unauthorized" in response.
Appreciate if someone can help in identifying the mistake I am making in below code.
$API_URL = 'https://api.changelly.com';
$API_KEY = 'XXXXX';
$API_SECRET = 'XXXXX';
$message = array();
$message['jsonrpc'] = '2.0';
$message['method'] = 'getMinAmount';
$message['params'] = array('from' => 'BTC', 'to' => 'LTC');
$message['id'] ='12345';
$data = json_encode($message);
$sign = hash_hmac('SHA512', $data, $API_SECRET);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_URL);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_GET, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json",'Authorization:api-key: '.$API_KEY.':sign: '.$sign));
$final_result = curl_exec($ch);
curl_close($ch);
echo '<pre>';
print_r($final_result);
Changelly API guide is at https://changelly.com/developers
Thanks
in your code you have wrong set of headers.
please check this example: https://github.com/changelly/changelly-examples/blob/master/php/example.php, hope it helps.

Bing Image search API v5.0 example for PHP

I'm trying, without success, to get some results using Bing's Image search API without HTTP/Request2.php component (as used in the official examples).
I understand that the only two required parameters to make a very primitive call are q which is the query string and the subscription key. The key must be sent using headers. After looking around I found this very simple example to send headers with PHP:
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$aHTTP = array(
'Ocp-Apim-Subscription-Key' => 'xxxxxxx',
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);
echo $contents;
But it does not output anything. Would you kindly help me with a very basic example of use of Bing's API?
SOLVED
Thanks to Vadim's hint I changed the way headers are sent and now output is a Json encoded result. (Remember to add your API subscription key.)
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: xxxxx'
));
$content = curl_exec($ch);
echo $content;
Just another tip. The syntax of query filters and other parameters change form version to version. For example the following work correctly in version 5.0:
To search only for JPEG images of cats and get 30 results use:
q=cats&encodingFormat='jpeg'&count=30
To search only for 'portrait' aspect images with size between 200x200 and 500x500 use:
q=cats&aspect=Tall&size=Medium
Try using cURL
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$key = "xxxxxxx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);
echo $content;
Here is my working code..
Replace ******** with your bing subscription key.
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=microsoft-surface&count=6&mkt=en-US";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: *******************'
));
$contents = curl_exec($ch);
$myContents = json_decode($contents);
if(count($myContents->value) > 0) {
foreach ($myContents->value as $imageContent) {
echo '<pre/>';
print_r($imageContent);
}
}

Categories