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;
Related
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.
I am posting json and audio file to my api built on laravel with the code below
$endPoint = 'http://localhost:9000/api/audio/send';
$apiKey = 'anvx7P7ackndaD8MvXlufSaG4uJ901raoWIwMPGZ93dkH';
$url = $endPoint . '?key=' . $apiKey;
$curlFile = new \CURLFile('/Users/desktop/myapp/public/Voice/aaaah.wav');
$data = array("request" =>
json_encode(array("test" => "First audio ",'recipient' =>['442342342', '35345242'])) . ";
type=application/json","file" => "#d8696c304d09eb1.wav;type=audio/wav");
$ch = curl_init();
$headers = array();
$headers[] = "Content-Type: application/json";
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, $data);
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
return $result;
When i submit my json to the api, it returns null from the api. Meaning no data is being posted to my api. Is there any error with how i am posting my json and audio file to the laravel api please?
PS: Beginner in PHP
You cannot post files in a JSON!.
A normal POST request is needed (the one that gets generated from the <form> element) for posting a file.
If you are bound to send the file using JSON, base64_encode it and send. On the other end though, the server will need to base64_decode it first.
I'm trying to get data posted using cURL in my endpoint, which is built on Laravel. In my API controller, where I receive data, I am able to receive all the data except my media file. I check for presence of the file using $request->hasFile('file') but it returns false. I also try to get the file using $request->file('file') but it returns null.
When I use $request->get('file'), I get the following response.
file":{"name":"/Users/name/File/path/public/media/aaaah.wav","mime":null,"postname":null}
Below, I am using $headers[] = "Content-Type: application/json"; to convert the recipient from array to string. Can anyone help me understand why the file posted by cURL is not being received in my Laravel method when I use $request->hasFile('file') and $request->file('file')?
AppController
public function postCurlData()
{
$endPoint = 'http://127.0.0.1:9000/api';
$apiKey = '****';
$url = $endPoint . '?key=' . $apiKey;
$dir = '/Users/name/File/path/app/public/media/test.wav'; // full directory of the file
$curlFile = curl_file_create($dir);
$data = [
'recipient' => ['44909090', '44909090'],
'content' => 'i love to code',
'file' => $curlFile,
];
$ch = curl_init();
$headers = array();
$headers[] = "Content-Type: application/json";
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, json_encode($data));
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
}
My endpoint where I'm receiving data:
APIController
public function receiveCurlData()
{
$apiKey = $request->get('key');
if (($apiKey)) {
return response()->json([
'status' => 'success',
'content' => $request->get('content'),
'recipient' => $request->get('recipient'),
'file' => $request->hasFile('file')
]);
}
}
Response
{"status":"success","content":"I love to code","recipient":
["44909090","44909090"],"file":false}
This answer is related to your question:
how to upload file using curl with php.
You should delete
$headers = array();
$headers[] = "Content-Type: application/json";
And
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
And also delete the json_encode() replacing it by the plain array
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$result = json_decode($result, TRUE);
curl_close($ch);
I'm working on an application in which I'd like to be able to upload activities (GPX files) to Strava using it's API v3.
My application successfully handles the OAuth process - I'm able to request activities, etc, successfully.
However, when I try to upload an activity - it fails.
Here's the relevant sample of my code:
// $filename is the name of the GPX file
// $actual_file contains the full path
$actual_file = realpath($filename);
$url="https://www.strava.com/api/v3/uploads";
$postdata = "activity_type=ride&file=". "#" . $actual_file . ";filename=" . $filename . "&data_type=gpx";
$headers = array('Authorization: Bearer ' . $strava_access_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_POST, 3);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec ($ch);
Here's what I get in response:
{"message":"Bad Request", "errors":[{"resource":"Upload", "field":"file","code":"not a file"}]}
I then tried this:
// $filename is the name of the GPX file
// $actual_file contains the full path
$actual_file = realpath($filename);
$url="https://www.strava.com/api/v3/uploads";
$postfields = array(
"activity_type" => "ride",
"data_type" => "gpx",
"file" => "#" . $filename
);
$postdata = http_build_query($postfields);
$headers = array('Authorization: Bearer ' . $strava_access_token, "Content-Type: application/octet-stream");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_POST, count($postfields));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$fp = fopen($filename, 'r');
curl_setopt($ch, CURLOPT_INFILE, $fp);
$json = curl_exec ($ch);
$error = curl_error ($ch);
Here's what I get in response:
{"message":"Bad Request", "errors":[{"resource":"Upload", "field":"data","code":"empty"}]}
Clearly, I'm doing something wrong when trying to pass the GPX file.
Is it possible to provide a bit of sample PHP code to show how this should work?
For what it's worth - I'm fairly certain the GPX file is valid (it's actually a file I downloaded using Strava's export feature).
I hope that answering my own question less than one day after posting it isn't bad form. But I've got it working, so I may as well, just in case anyone else finds it useful...
// $filename is the name of the file
// $actual_file includes the filename and the full path to the file
// $strava_access_token contains the access token
$actual_file = realpath($filename);
$url="https://www.strava.com/api/v3/uploads";
$postfields = array(
"activity_type" => "ride",
"data_type" => "gpx",
"file" => '#' . $actual_file . ";type=application/xml"
);
$headers = array('Authorization: Bearer ' . $strava_access_token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
Apparently, it's important not to include the CURLOPT_POST option.
Here is also a working Python example
import os
import requests
headers = {
'accept': 'application/json',
'authorization': 'Bearer <Token>',
}
dir = os.getcwd() + '/files/'
for filename in os.listdir(dir):
file = open(dir + filename, 'rb')
files = {
"file": (filename, file, 'application/gpx+xml'),
"data_type": (None, 'gpx'),
}
try:
response = requests.post('http://www.strava.com/api/v3/uploads',files=files, headers=headers)
print(filename)
print(response.text)
print(response.headers)
except requests.exceptions.RequestException as e: # This is the correct syntax
print(e)
sys.exit(1)
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.