Convert data to json format with multiple arrays - php

Long story short, i have the following code which is gettin info about an order from api in json, and should send this order to another system through api. All steps works good, but my problem it's if i have more products on order, my script it's creating a new order for each one.
SCRIPT:
foreach($data['orders'] as $key => $val)
{
$phone = $val['phone'];
$email = $val['email'];
$fullname = $val['invoice_fullname'];
$invoicecompany = $val['invoice_company'];
$invoicenip = $val['invoice_nip'];
$invoiceaddress = $val['invoice_address'];
$invoicecity = $val['invoice_city'];
$deliveryprice = $val['delivery_price'];
$deliverymethod = $val['delivery_method'];
}
foreach($data['orders'][0]['products'] as $key => $val){
$pidBl = $val['product_id'];
$ean = $val['ean'];
$grossprice = $val['price_brutto'];
$vatrate = $val['tax_rate'];
$quantity = $val['quantity'];
//open db
$dbc = mysqli_connect ($dbhost, $dbuser, $dbpassword);
$dbSelected = mysqli_select_db($dbc , $database);
$q = $dbc->query("SELECT pId FROM offers WHERE pBarcode = '$ean';");
while ($rs = $q->fetch_assoc()) {
$pId = $rs['pId'];
}
$arr = [
"objects" => [],
"returnColumns" => []
];
$arr['objects'][] = [
"name" => $fullname,
"uniqueCode" => $invoicenip,
"active" => "true"
];
$arr['returnColumns'][] = ["name" => "id"];
$preparesedona = json_encode($arr);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'BLABLABLA',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $preparesedona,
CURLOPT_HTTPHEADER => array(
'accept: application/json',
'Authorization: Basic BLABLABLA',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$data = json_decode($response, true);
foreach($data['result'] as $key => $val){
$customerId = $val['id'];
}
$arr = [
"objects" => [],
"returnColumns" => []
];
$arr['objects'][] = [
"client_id" => $customerId,
"user_id" => 1,
"administration_id" => 1,
"status" => 1,
"deliveryType" => 1,
"details" => []
];
$arr['objects'][0]['details'][] = [
"product_id" => $pId,
"unitPriceWithVat" => $grossprice,
"orderedUnits" => $quantity
];
$arr['returnColumns'][] = ["name" => "id"];
$preparesedona = json_encode($arr);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'BLABLABLA',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $preparesedona,
CURLOPT_HTTPHEADER => array(
'accept: application/json',
'Authorization: Basic BLABLABLA',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
}
Yas, i know that somewhere it's a small thing which is making difference, but trust me, i tried in any possible way, i tried to look on similar errors and problems but i cannot find anything related cause i have multiple arrays which should be defined and filled...
This is how it looks my postfields
{
"objects":[
{
"client_id":21947,
"user_id":1,
"administration_id":1,
"status":1,
"deliveryType":1,
"details":[
{
"product_id":"11407",
"unitPriceWithVat":159.7,
"orderedUnits":1
}
]
}
],
"returnColumns":[
{
"name":"id"
}
]
}{
"objects":[
{
"client_id":21948,
"user_id":1,
"administration_id":1,
"status":1,
"deliveryType":1,
"details":[
{
"product_id":"14575",
"unitPriceWithVat":45.31,
"orderedUnits":1
}
]
}
],
"returnColumns":[
{
"name":"id"
}
]
}
This is how should look like:
{
"objects":[
{
"client_id":21947,
"user_id":1,
"administration_id":1,
"status":1,
"deliveryType":1,
"details":[
{
"product_id":"11407",
"unitPriceWithVat":159.7,
"orderedUnits":1
},
{
"product_id":"14575",
"unitPriceWithVat":45.31,
"orderedUnits":1
}
]
}
],
"returnColumns":[
{
"name":"id"
}
]
}
I would much appreciate your help and please, be sympathetic, i'm not a pro, i just try to learn and i promise that i do my best :)

this works for me, baiscally, i make one call to API1 to get general info about order and creating customer in API2 // after that i made another call to API1 to get info about products and this is how i structured my script and it's workin very well.
// gettin info about order data
foreach($data['orders'] as $key => $val)
{
$phone = $val['phone'];
$email = $val['email'];
$fullname = $val['invoice_fullname'];
$invoicecompany = $val['invoice_company'];
$invoicenip = $val['invoice_nip'];
$invoiceaddress = $val['invoice_address'];
$invoicecity = $val['invoice_city'];
$deliveryprice = $val['delivery_price'];
$deliverymethod = $val['delivery_method'];
$deliveryaddress = $val ['delivery_address'];
// CREATE CUSTOMER -------------------------
$arr = [
"objects" => [],
"returnColumns" => []
];
$arr['objects'][] = [
"name" => $fullname,
"uniqueCode" => $invoicenip,
"active" => "true"
];
$arr['returnColumns'][] = ["name" => "id"];
$preparesedona = json_encode($arr);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'BLABLABLABLA',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $preparesedona,
CURLOPT_HTTPHEADER => array(
'accept: application/json',
'Authorization: Basic BLABLABLABLA',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$data = json_decode($response, true);
$customerId = $data['result'][0]['id'];
}
// Call again to get data for products
$methodParams = [
'order_id' => $orderidbl
];
$apiParams = [
'method' => 'getOrders',
'parameters' => json_encode($methodParams),
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'BLABLABLABLABLABLABLABLA');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-BLToken: BLABLABLABLA-BLABLABLABLA-BLABLABLABLA"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$output = curl_exec($ch);
curl_close($ch);
$data = json_decode($output, true);
$arr = [
"objects" => [],
"returnColumns" => []
];
$arr['objects'][] = [
"client_id" => $customerId,
"user_id" => 1,
"administration_id" => 1,
"status" => 1,
"deliveryType" => 1,
"deliveryAddress" => $deliveryaddress,
"details" => []
];
$arr['returnColumns'][] = ["name" => "id"];
// prepare products area "details"
foreach($data['orders'][0]['products'] as $key => $val){
$pidBl = $val['product_id'];
$ean = $val['ean'];
$grossprice = $val['price_brutto'];
$vatrate = $val['tax_rate'];
$quantity = $val['quantity'];
//open db
$dbc = mysqli_connect ($dbhost, $dbuser, $dbpassword);
$dbSelected = mysqli_select_db($dbc , $database);
$q = $dbc->query("SELECT pId FROM offers WHERE pBarcode = '$ean';");
while ($rs = $q->fetch_assoc()) {
$pId = $rs['pId'];
}
$arr['objects'][0]['details'][] = [
"product_id" => $pId,
"unitPriceWithVat" => $grossprice,
"orderedUnits" => $quantity
];
}
$preparesedona = json_encode($arr);
var_dump($preparesedona);

Related

API JSON output Format

I have this code
<?php
$id = $_POST['id'];
$nume = $_POST['nume'];
$rrp = $_POST['rrp'];
$pret = $_POST['pret'];
$stoc = $_POST['stoc'];
$url = $_POST['url'];
$url1 = $_POST['url1'];
$url2 = $_POST['url2'];
$url3 = $_POST['url3'];
$username = "xx#xx.eu";
$password = "aaa";
$apiUrl = "https://partners.services.aaaa.eu/v1/mkpApi/product/save";
$auth = base64_encode($username . ":" . $password);
$headers = [
"Authorization: Basic " . $auth,
"Content-Type: application/x-www-form-urlencoded",
];
$payload[] = [
"id" => $id,
"locale" => "RO",
"hidden" => 0,
"currency" => "RON",
"brand" => "Decorepublic",
"name" => $nume,
"category_id" => 10008,
"status" => "1",
"vat" => "0",
"stock" => [[
"warehouse_id" => 1,
"value" => $stoc,
]],
"sale_price" => $pret,
"rrp" => $rrp,
"description" => $nume,
"images" => [
["url" => $url],
["url" => $url1],
["url" => $url2],
["url" => $url3],
],
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(["data" => json_encode($payload)]));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$response = json_decode($result, true);
print_r($response);
//echo '<br><br>';
echo json_encode($payload);
print $stoc;
?>
At output i have
status":"1","vat":"0","stock":[{"warehouse_id":1,"value":"200"}]
I need to have value without "" like this:
status":"1","vat":"0","stock":[{"warehouse_id":1,"value":200}],"
I trie to use print $stoc, but it returns value 1.
I tried get function but it doesn't work. Any idea?
If you've got a string in $stoc and you need to convert it to an integer before you encode it as JSON, then you can use intval.
"value" => intval($stoc)
Demo: http://sandbox.onlinephpfunctions.com/code/8b1ed16c28bfbc47f501981f2bf03f7b1bb9ce45

laravel 7 with CURL

need help. im stop with this situation, i got an error that i don't understand. i think because i am weak in this. i have API payment and i use CURL. i actually get the encoded value but when i try using CURL to pas the value to API. i got this setContent() must be of the type string or null.. take a look my code.
$credentials = $this->creds();
$secret_key = $credentials->private_key;
//$secret_key = 'cxl+hwc%97h6+4#lx1au*ut=ml+=!fx85w94iuf*06=rf383xs';
$public_key = $credentials->public_key;
//$public_key = '7)5dmcfy^dp*9bdrcfcm$k-n=p7b!x(t)_f^i8mxl#v_+rno*x';
$merchant_id = "3581";
$dataToHash = "5a8c12eb19016500.00PHPMy Product";
$secure_hash = hash_hmac('sha256', $dataToHash, $secret_key, false);
$auth_hash = hash_hmac('sha256', $public_key, $secret_key, false);
$customer_array = array (
'merchant_id' => $merchant_id,
'merchant_ref_no' => "6a2c14eb19355",
'merchant_additional_data' => "Additional Data",
'amount' => 1500,
'currency' => 'PHP',
'description' => "Description",
'billing_email' => "email#gmail.com",
'billing_first_name' => "jayson",
'billing_last_name' => "claros",
'billing_middle_name' => "curada",
'billing_phone' => "123456789",
'billing_mobile' => "12345678",
'billing_address' => "address1",
'billing_address2' => "address2",
'billing_city' => "None",
'billing_state' => "None",
'billing_zip' => "None",
'billing_country' => "None",
'billing_remark' => "None",
'payment_method' => 'BOG',
'status_notification_url' => 'https://242c3.ngrok.io/callback',
'success_page_url' => "",
'failure_page_url' => "",
'cancel_page_url' => "",
'pending_page_url' => "",
'secure_hash' => $secure_hash,
'auth_hash' => $auth_hash,
'alg' => 'HS256',
);
// $payform_data = json_encode($raw_payform, JSON_UNESCAPED_SLASHES);
// $decoded = utf8_decode(base64_encode(utf8_encode($payform_data)));
$billing_json = json_encode($customer_array, JSON_UNESCAPED_SLASHES);
$datax= base64_encode($billing_json);
$URL = 'https://api.paymentget.com/payform-link?format=json';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $URL);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS,$datax);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$rest = curl_exec($curl);
if($err = curl_error($curl)) {
echo $err;
} else {
$decoded = json_decode($rest);
}
return $decoded;
the result should look like this.
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtZXJjaGFudCI6ODUyOSwibWVyY2hhbnRfbmFtZSI6IlRvdXJpc21vUEggQ29ycG9yYXRpb24iLCJtZXJjaGFudF9mZWUiOjAuMCwibWVyY2hhbnRfbGV2ZWwiOjIsImFwcGx5X2ZlZXMiOnRydWUsImNhc2hfaW5fbGltaXQiOi0xLjAsInBheW1lX251bWJlciI6ODY2NDIyLCJtZXJjaGFudF9zaG91bGRlcmVkIjp0cnVlLCJhbW91bnQiOjUwOTIuMCwiZGVzY3JpcHRpb24iOiJDb3JyZWRvciBJcy4sIFRoZSBSb2NrIGJvb2tpbmciLCJtZXJjaGFudF9yZWZfbm8iOiI1YThjMTJlYjE5MDE2IiwibWVyY2hhbnRfYWRkaXRpb25hbF9kYXRhIjoiQWRkaXRpb25hbCBEYXRhIiwicHVycG9zZSI6IiIsInNvdXJjZSI6IiIsInNwZWNpZnkiOiIiLCJjY19tZHIiOjAsImNjX2ZlZSI6MCwiYWdncmVnYXRvcl9mZWUiOjB9.MHHqWbf74rokfxqdHJ1HXwB8NEGo24uQBjhdMtuRvGc&form_data=eyJtZXJjaGFudF9pZCI6Ijg1MjkiLCJtZXJjaGFudF9yZWZfbm8iOiI1YThjMTJlYjE5MDE2IiwibWVyY2hhbnRfYWRkaXRpb25hbF9kYXRhIjoiQWRkaXRpb25hbCBEYXRhIiwiYW1vdW50IjoiNTA5Mi4wMCIsImN1cnJlbmN5IjoiUEhQIiwiZGVzY3JpcHRpb24iOiJDb3JyZWRvciBJcy4sIFRoZSBSb2NrIGJvb2tpbmciLCJiaWxsaW5nX2VtYWlsIjoiamF5c29uLmNsYXJvc0BnbWFpbC5jb20iLCJiaWxsaW5nX2ZpcnN0X25hbWUiOiJkZmRmIiwiYmlsbGluZ19sYXN0X25hbWUiOiJzZHNkcyIsImJpbGxpbmdfbWlkZGxlX25hbWUiOiJOb25lIiwiYmlsbGluZ19waG9uZSI6IjA5NDY2ODI5NDIyIiwiYmlsbGluZ19tb2JpbGUiOiIwOTQ2NjgyOTQyMiIsImJpbGxpbmdfYWRkcmVzcyI6IjE0MjUgZmRnZmcuZSBoc2pzaiBramFramFzIiwiYmlsbGluZ19hZGRyZXNzMiI6Ik5vbmUiLCJiaWxsaW5nX2NpdHkiOiJtYW5pbGFgIiwiYmlsbGluZ19zdGF0ZSI6Ik5vbmUiLCJiaWxsaW5nX3ppcCI6Ik5vbmUiLCJiaWxsaW5nX2NvdW50cnkiOiJOb25lIiwiYmlsbGluZ19yZW1hcmsiOiJOb25lIiwicGF5bWVudF9tZXRob2QiOiJCT0ciLCJzdGF0dXNfbm90aWZpY2F0aW9uX3VybCI6Imh0dHBzOi8vNjM0MmEzMzQubmdyb2suaW8vY2FsbGJhY2siLCJzdWNjZXNzX3BhZ2VfdXJsIjoiaHR0cHM6Ly9ib29raW5nLmV0b3VyaXNtby5jb20vbGlzdGluZy1jaGVja291dC8/cGF5bWVudD1zdWNjZXNzJiIsImZhaWx1cmVfcGFnZV91cmwiOiJodHRwczovL2Jvb2tpbmcuZXRvdXJpc21vLmNvbS9wYXltZW50LWZhaWxlZC8iLCJjYW5jZWxfcGFnZV91cmwiOiJodHRwczovL2Jvb2tpbmcuZXRvdXJpc21vLmNvbS9saXN0aW5nLWNoZWNrb3V0Lz9wYXltZW50PWNhbmNlbCYiLCJwZW5kaW5nX3BhZ2VfdXJsIjoiaHR0cHM6Ly9ib29raW5nLmV0b3VyaXNtby5jb20vbGlzdGluZy1jaGVja291dC8/cGF5bWVudD1wZW5kaW5nJiIsInNlY3VyZV9oYXNoIjoiNmUyOTA4ZjdmZDUwYWIwZDg3ZjllY2QxMTNiN2ViYzg4MGYxNzNhNTNhMjM3YzJlNDU2NWVjNjcyNjkxZDlhZCIsImF1dGhfaGFzaCI6IjYwY2Q2MjkyZmY0MDIzZWRmNmZlMjE0YWU0MjUyN2JhMzUzZjViODM5OTEzZDc1NWMyMTllZmJkNDc1MmUyMWEiLCJhbGciOiJIUzI1NiJ9

Upload video to jw player account using Laravel

I want to add video file or video URL to jwplayer in my laravel 5.2 project but i didn't found it's any package or library yet. It's documentation is very difficult to understand for me as I never worked on jwplayer before. My requirement is to upload video to jwplayer and amazon s3 bucket. It's uploading to s3 bucket but I'm stuck at jwplayer. Any guide or example will be helpful.
Use this code...
<?php
require_once('vendor/autoload.php');
function get_parts_count($file) {
// 5 MB is the minimum size of an upload part, per https://developer.jwplayer.com/jwplayer/docs/stream-multipart-resumable-upload
$minimum_part_size = 5 * 1024 * 1024;
$size = filesize($file);
return (floor($size / $minimum_part_size) + 1);
}
$secret = $_ENV('JWPLATFORM_API_SECRET');
$site_id = $_ENV('JWPLATFORM_SITE_ID');
$jwplatform_api = new Jwplayer\JwplatformClient($secret);
$target_file = 'examples/test.mp4';
$params = array();
$params['metadata'] = array();
$params['metadata']['title'] = 'PHP API Test Upload';
$params['metadata']['description'] = 'Video description here';
$params['upload'] = array();
$params['upload']['method'] = 'multipart';
$create_response = json_encode($jwplatform_api->Media->create($site_id, $params));
print_r($create_response);
print("\n");
$decoded = json_decode(json_decode(trim($create_response), true), true);
$upload_id = $decoded['upload_id'];
$upload_token = $decoded['upload_token'];
$media_id = $decoded['id'];
$parts_count = get_parts_count($target_file);
$upload_parts_url = "https://api.jwplayer.com/v2/uploads/$upload_id/parts?page=1&page_length=$parts_count";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $upload_parts_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer ' . $upload_token,
),
));
$upload_parts_response = curl_exec($curl);
curl_close($curl);
$upload_parts_response_object = json_decode($upload_parts_response);
print_r($upload_parts_response_object);
print("\n");
$upload_url_parts = $upload_parts_response_object->parts;
// 5 MB is the minimum size of an upload part, per https://developer.jwplayer.com/jwplayer/docs/stream-multipart-resumable-upload
$buffer = (1024 * 1024) * 5;
if (count($upload_url_parts) > 0) {
$file_handle = fopen($target_file, 'rb');
foreach($upload_url_parts as $upload_url_parts_key => $upload_url_parts_value) {
$upload_bytes_url = $upload_url_parts_value -> upload_link;
$file_part = fread($file_handle, $buffer);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $upload_bytes_url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS, $file_part);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type:'
));
$upload_bytes_response = curl_exec($curl);
print_r($upload_bytes_response);
print("\n");
}
fclose($file_handle);
$complete_upload_url = "https://api.jwplayer.com/v2/uploads/$upload_id/complete";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $complete_upload_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer ' . $upload_token,
),
));
$complete_upload_response = curl_exec($curl);
curl_close($curl);
$complete_upload_response_object = json_decode($complete_upload_response);
print_r($complete_upload_response_object);
print("\n");
}
?>
From what I can tell Laravel is a PHP framework and it shouldn't be a problem to use the JW Player APIs within that. Have you checked the documentation here:
https://developer.jwplayer.com/jw-platform/reference/v1/s3_uploads.html
There are also a couple of script examples (PHP and Python) that you can use here to get started:
https://developer.jwplayer.com/jw-platform/
There are multiple steps in uploading a video on jwplayer:-
$apiKey = env('jw_player_apikey');
$apiV2Secret = env('jw_player_secretkey);
// Step1. for getting upload_token and upload_id
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.jwplayer.com/v2/sites/$apiKey/media/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\"upload\":{\"method\":\"multipart\"},\"metadata\":{\"title\":\"$r->title\",\"description\":\"My media description\"}}",
CURLOPT_HTTPHEADER => [
"Accept: application/json",
"Authorization: $apiV2Secret",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
return response()->json(['status'=>'error']);
} else {
$response=json_decode($response);
// Step2. For getting upload_link
$curl1 = curl_init();
curl_setopt_array($curl1, [
CURLOPT_URL => "https://api.jwplayer.com/v2/uploads/$response->upload_id/parts?page=1&page_length=1",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"Accept: application/json",
"Authorization: Bearer ".$response->upload_token,
"Content-Type: application/json"
],
]);
$response1 = curl_exec($curl1);
$err1 = curl_error($curl1);
curl_close($curl1);
if ($err1) {
return response()->json(['status'=>'error']);
}
else {
$response1=json_decode($response1);
$url = $response1->parts[0]->upload_link;
// Step4. For uploading parts
$curl2 = curl_init($url);
curl_setopt($curl2, CURLOPT_URL, $url);
curl_setopt($curl2, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl2, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($curl2, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl2, CURLOPT_HTTPHEADER, array('Content-Type:'));
$file = $r->file('video');
$handle = fopen($file, "r");
$data = fread($handle, filesize($file));
curl_setopt($curl2, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($curl2);
$err2 = curl_error($curl2);
curl_close($curl2);
if ($err2) {
return response()->json(['status'=>'error']);
}
else {
// Step 5. to complete the upload
$curl3 = curl_init();
curl_setopt_array($curl3, [
CURLOPT_URL => "https://api.jwplayer.com/v2/uploads/".$response->upload_id."/complete",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer ".$response->upload_token,
"Content-Type: application/json"
],
]);
$response3 = curl_exec($curl3);
$err3 = curl_error($curl3);
curl_close($curl3);
if ($err3) {
return response()->json(['status'=>'error']);
} else {
// Step 6. Get uploaded video details
$curl6 = curl_init();
curl_setopt_array($curl6, [
CURLOPT_URL => "https://api.jwplayer.com/v2/sites/$apiKey/media/$response->id",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $apiV2Secret",
"Content-Type: application/json"
],
]);
$response6 = curl_exec($curl6);
$err6 = curl_error($curl6);
curl_close($curl6);
if ($err6) {
return response()->json(['status'=>'error']);
} else {
$video_response=json_decode($response6);
//get video id from the response
if($this->check_count($video_response)>0){
//insert video detail in database
$insert=new videos();
$insert->jw_id=$video_response->id;
$insert->save();
if ($insert) {
return response()->json(['status'=>'success']);
} else {
return response()->json(['status'=>'error','message'=>"Fail to upload video, Please try again!!"]);
}
}
else{
return response()->json(['status'=>'error','message'=>"Fail to upload video, Please try again!!"]);
}
}
}
}
}
}
The above code doc was received from JW player official. It's working on my side. Hope it helps you too.

Requesting Api Call using cURL

Someone could help me ? I'm trying to do a request by the code bellow, but anything happen, any message appears. I believe my code it's right:
public function subscribe(){
$json_url = 'https://apisandbox.cieloecommerce.cielo.com.br/1/sales/';
$json_string = json_encode(array(
"MerchantOrderId"=>"2014113245231706",
"Customer" => array(
"Name" => "Comprador rec programada"
),
"Payment" => array(
"Type" => "CreditCard",
"Amount" => 1500,
"Installments" => 1,
"SoftDescriptor" => "Assinatura Fraldas"
)
));
$ch = curl_init($json_url);
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
curl_setopt_array( $ch, $options );
$result = curl_exec($ch); // Getting jSON result string
print_r($result);
}
Find link with instructions of the site:
you will reiceive this:
[
{
"Code": 114,
"Message": "The provided MerchantId is not in correct format"
}
]
with this code:
function subscribe(){
$json_url = 'https://apisandbox.cieloecommerce.cielo.com.br/1/sales/';
$json_string = json_encode(
array(
"MerchantOrderId"=>"2014113245231706",
"Customer" => array(
"Name" => "Comprador rec programada"
),
"Payment" => array(
"Type" => "CreditCard",
"Amount" => 1500,
"Installments" => 1,
"SoftDescriptor" => "Assinatura Fraldas"
)
)
);
$headers = array(
'Content-Type: application/json',
'MerchantId: xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxx',
'MerchantKey: xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxx',
'RequestId: xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxx'
);
$ch = curl_init($json_url);
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $json_string
);
curl_setopt_array( $ch, $options ); $result = curl_exec($ch);
print_r($result);
}
subscribe()
It would be interesting what HTTP status code you get:
print_r(curl_getinfo($ch, CURLINFO_HTTP_CODE));

php how to send this data threw curl

I have to send this data threw curl:
-d '{"payer": {
"default_payment_instrument":"BANK_ACCOUNT",
"allowed_payment_instruments":["BANK_ACCOUNT"],
"default_swift":"FIOBCZPP",
"contact":{"first_name":"First",
"last_name":"Last",
"email":"first.last#example.com"
}
},
}'
How am I supposed to save those data into fields variable?
$fields = {
"payer": {
"default_payment_instrument":"BANK_ACCOUNT",
"allowed_payment_instruments":["BANK_ACCOUNT"],
"default_swift":"FIOBCZPP",
"contact":{"first_name":"First",
"last_name":"Last",
"email":"first.last#example.com"
}
},
};
$field_string = http_build_query($fields);
curl_setopt($process, CURLOPT_POSTFIELDS, $field_string);
This is GoPay right?
Do something like this:
$fields = [
"payer" => [
"default_payment_instrument" => "BANK_ACCOUNT",
"allowed_payment_instruments" => ["BANK_ACCOUNT"],
"default_swift" => "FIOBCZPP",
"contact" => [
"first_name" => "First",
"last_name" => "Last",
"email" => "first.last#example.com"
]
]
];
$json = json_encode($fields);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
Ok, posting stuff with cURL. Here you go...
<?php
$target_url = "http://domain.dev/post-acceptor.php";
$data_to_post = array(
"payer" => array(
"default_payment_instrument" => "BANK_ACCOUNT",
"allowed_payment_instruments" => "BANK_ACCOUNT",
"default_swift" => "FIOBCZPP",
"contact" => array(
"first_name" => "First",
"last_name" => "Last",
"email" => "first.last#example.com"
)
)
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target_url);
curl_setopt($curl, CURLOPT_POST, count($data_to_post));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data_to_post));
$result = curl_exec($curl);
curl_close($curl);
Notes:
you might try to turn your JSON into an PHP array by using json_decode()

Categories