Passing body header with PHP - php

I'm trying make a Vimeo-API to upload subtitles/captions, following this guide: https://developer.vimeo.com/api/upload/texttracks#uploading-a-text-track-step-3
The guide gives 4 steps, I'm stalled in step 3.
Step 3:
To upload the text track, take the value of the link field from Step 2, and make a PUT request to this location: PUT https://api.vimeo.com{link}
Here is my code:
require 'Vimeo/autoload.php';
use Vimeo\Vimeo;
$client = new Vimeo("xxxxxxxxxxxxxxxxxxxxxx,xxxxxxxxxxxxxxxxxx,xxxxxxxxxxxxx");
include __DIR__ . '/Vimeo/autoload.php';
$clientId = "xxxxxxxxxxxxxxxxxxxxx";
$clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxx";
$scope = "public";
$userId = 9999999;
$lib = new \Vimeo\Vimeo($clientId, $clientSecret);
$token = $lib->clientCredentials($scope);
$lib->setToken('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$videos = $lib->request("/videos/99999999/texttracks", ["type"=>"captions", "language"=>"pt-BR", "name"=>"legenda"], "POST");
$link = $videos["body"]["link"];
$videos = $lib->request("/videos/99999999/texttracks/", ["link"=>$link, "body"=>"https://paste.ee/r/E3Q1K/0"], "PUT");
echo "<pre>".var_export($videos, true)."</pre>";
Output:
array (
'body' => NULL,
'status' => 405,
'headers' =>
array (
'Server' => 'nginx',
'Content-Type' => 'application/json',
'Allow' => 'GET,POST,OPTIONS',
'X-Vimeo-DC' => 'ge',
'Accept-Ranges' => 'bytes',
'Via' => '1.1 varnish',
'Content-Length' => '0',
'Date' => 'Wed, 22 May 2019 07:11:58 GMT',
'Connection' => 'keep-alive',
'X-Served-By' => 'cache-bwi5150-BWI, cache-lax8642-LAX',
'X-Cache' => 'MISS, MISS',
'X-Cache-Hits' => '0, 0',
'X-Timer' => 'S1558509118.323164,VS0,VE80',
'Vary' => 'Accept-Encoding',
),
)
So, the problem occur in this line:
$videos = $lib->request("/videos/99999999/texttracks/", ["link"=>$link, "body"=>"https://paste.ee/r/E3Q1K/0"], "PUT");
As you can see, the output body is NULL. How can I set up correctly body header? I'm trying make this API for three days, here is my last hope, I'll be very glad if you could help me.
Thank you

Related

Can't get an unenrolled 3d-secure card authenticaited (secrure trading)

I am running a PHP 7.3, running on apache server. I used composer to get this library:
https://github.com/SecureTrading/PHP-API
For the code provided, I am now using the test site reference. I already managed to use for regular transitions. I now started managing 3D secure transactions, with the test MAESTRO card provided by secure trading here: https://docs.securetrading.com/document/testing/. the one designed not to demand 3D auth - that is 5000000000000421
The code provided next, will sum up the way I think thought this should work: I start by creating AUTH request, get error 30004, using CACHETOKENISE request to get a token, run THREEDQUERY to figure out if I need a full auth sceme on this card, get N as an answer, and run another AUTH request, this time with the transactionreference.
I am providing a version of the code I am testing (obviously, username, password and site reference name was removed to protect my privacy, but the code otherwise is the same)
<?php
$configData = array(
'username' => 'api#gigsberg.com',
'password' => 'xq!Kq$j4',
);
$site_refrance = 'test_gigsberg74319';
?>
<?php
$configData = array(
'username' => '*****',
'password' => '*****',
);
$site_refrance = '*****';
if (!($autoload = realpath(__DIR__ . '/vendor/autoload.php'))) {
throw new \Exception('Composer autoloader file could not be found.');
}
require_once($autoload);
$api = \Securetrading\api($configData);
$requestData = array(
'sitereference' => $site_refrance,
'requesttypedescription' => 'AUTH',
'accounttypedescription' => 'ECOM',
'currencyiso3a' => 'GBP',
'mainamount' => '1000',
'pan' => '5000000000000421',
'expirymonth' => '12',
'expiryyear' => '2030',
'securitycode' => '123',
);
echo '<pre>';
print_r($requestData);
$response = $api->process($requestData)->toArray();
print_r( $response['responses'] ); // $response['responses'][0]['errorcode'] == 30004
echo "\n--------------------------------------\n";
$transactionreference = $response['responses'][0]['transactionreference'];
$requestData = array(
'sitereference' => $site_refrance,
'expirymonth' => '12',
'expiryyear' => '2030',
'requesttypedescriptions' => array('CACHETOKENISE'),
'securitycode' => '123',
'orderreference' => $transactionreference,
'pan' => '5000000000000421'
);
print_r($requestData);
$response = $api->process($requestData)->toArray();
echo "\n--------------------------------------\n";
$cachetoken = $response['responses'][0]['cachetoken'];
$requestData = array(
'termurl' => 'https://termurl.com',
'accept' => 'text/html,*/*',
'currencyiso3a' => 'GBP',
'requesttypedescription' => 'THREEDQUERY',
'accounttypedescription' => 'ECOM',
'sitereference' => $site_refrance,
'baseamount' => '1000',
'pan' => '5000000000000421',
'expirymonth' => '12',
'expiryyear' => '2030',
'cachetoken' => $cachetoken,
);
print_r($requestData);
$response = $api->process($requestData)->toArray(); // $response['responses'][0]['enrolled'] == 'N'
/* Copying from the docs here: https://docs.securetrading.com/document/api/security/3-d-secure/
* If the enrolled value returned in the response is “Y”, the customer’s card is enrolled in 3-D secure. Please refer to the following table for enrolled values:
* .
* .
* N - The card is not enrolled in the card issuer’s 3-D Secure scheme. - Perform an AUTH Request, including the transactionreference returned in the THREEDQUERY response.
* .
* .
*/
print_r( $response['responses'] );
echo "\n--------------------------------------\n";
$transactionreference = $response['responses'][0]['transactionreference'];
$requestData = array(
'sitereference' => $site_refrance,
'requesttypedescription' => 'AUTH',
'accounttypedescription' => 'ECOM',
'currencyiso3a' => 'GBP',
'mainamount' => '1000',
'pan' => '5000000000000421',
'expirymonth' => '12',
'expiryyear' => '2030',
'securitycode' => '123',
'transactionreference' => $transactionreference
);
print_r($requestData);
$response = $api->process($requestData)->toArray();
print_r( $response['responses'] ); // Still get $response['responses'][0]['errorcode'] == 30004
I expected it to give me a note that all works well, but I still got error 30004, as if the transactionreference wasn't provided. Any idea what I can do, to fix this code, and prevent this error?
Thanks in advance
Yair
Well, I read the Api tests, and I found my error. On the last request data, instead of
$requestData = array(
.
.
'transactionreference' => $transactionreference
.
.
);
I should use
$requestData = array(
.
.
'parenttransactionreference' => $transactionreference
.
.
);
Anyway, home this helps somone

Facebook Ads SDK - Unsupported Post Request

I got some example scripts from Facebook App Management to use the Marketing API. When I run the script, I just get this error by curl:
'Unsupported post request. Object with ID \'105101623679981\' does not exist, cannot be loaded due to missing permissions, or does not support this operation.
I already tried to deactivate the Sandbox Mode and go public, tried many different scripts in different languages and also other keys.
Any Ideas?
This is the Script:
<?php
//Add all those Uses and the autoloader
$access_token = '<my_very_long_accessToken';
$ad_account_id = '<my_account_id>'; //<-- This is the Object in the Error Code
$app_secret = '<my_app_secret>';
$page_id = '<my_page_id>';
$app_id = '<my_app_is>';
$api = Api::init($app_id, $app_secret, $access_token);
$api->setLogger(new CurlLogger());
$fields = array(
);
$params = array(
'objective' => 'PAGE_LIKES',
'status' => 'PAUSED',
'buying_type' => 'AUCTION',
'name' => 'My Campaign',
);
$campaign = (new AdAccount($ad_account_id))->createCampaign(
$fields,
$params
);
$campaign_id = $campaign->id;
echo 'campaign_id: ' . $campaign_id . "\n\n";
$fields = array(
);
$params = array(
'status' => 'PAUSED',
'targeting' => array('geo_locations' => array('countries' => array('US'))),
'daily_budget' => '1000',
'billing_event' => 'IMPRESSIONS',
'bid_amount' => '20',
'campaign_id' => $campaign_id,
'optimization_goal' => 'PAGE_LIKES',
'promoted_object' => array('page_id' => $page_id),
'name' => 'My AdSet',
);
//...
Yeah. I got it. It has to be "act_"
So bad. The Script is really crappy. So many Errors. And it's created by facebook!

httprequest to curl in php 5.5.38 on Windows

I'm hoping someone can help me out. I inherited some code that I have no idea how it works and now that it broke I have to fix it.
I am running PHP 5.5.38 on Windows server 2012 and IIS 8.5. I have finally discovered that the php code is using httprequest which doesn't exist anymore in my version of php and with windows. How would I convert the following to use curl code, if it is even possible?
$http = new HttpRequest('https://my.securelink.com/external/readi/ssoRequest', HttpRequest::METH_POST);
$http->addHeaders(
array(
'READI_AccessKey' => $accesskey,
'READI_Timestamp' => $timestamp,
'READI_RequestSignature' => $mac
)
);
$http->addPostFields(
array(
'READIUsername' => 'myusername',
'LastName' => $_GET["lastn"],
'FirstName' => $_GET["firstn"],
'Email' => $_GET["em"],
'ForceNewAssessment' => false,
'InternalID' => $_GET["userid"],
'IncludeSettings' => ''
)
);
//Optional Post Field: 'READIUserID' => 'xxxxxx'
$response = $http->send()->getBody();
echo "<h3>===== Response ===== </h3>";
echo "<pre>";
echo $response;
echo "</pre>";
$arr = xml2array($response);
$rtn_status = getvaluebypath($arr,'sso/status');
$rtn_timestamp = getvaluebypath($arr,'sso/timestamp');
if($rtn_status == "success") {
$redirectURL = getvaluebypath($arr,'sso/redirectUrl');
echo "<h3>===== Access Link ===== </h3>";
echo "" . $redirectURL . "";
header( "Location: $redirectURL");
}
You can try adding the HttpRequest class as guyver4mk suggested (the link from Jiri Hrazdil's comment) if you don't want to change the whole code.
But since you asked how to convert the existing to cURL, try this:
$header = [
'READI_AccessKey: '.$accesskey,
'READI_Timestamp: '.$timestamp,
'READI_RequestSignature: '.$mac
];
$post = [
'READIUsername' => 'myusername',
'LastName' => $_GET["lastn"],
'FirstName' => $_GET["firstn"],
'Email' => $_GET["em"],
'ForceNewAssessment' => false,
'InternalID' => $_GET["userid"],
'IncludeSettings' => ''
];
$ch = curl_init();
$options = [
CURLOPT_URL => 'https://my.securelink.com/external/readi/ssoRequest',
CURLOPT_HTTPHEADER => $header,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $post,
CURLOPT_RETURNTRANSFER => 1
];
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if (!$response)
print_r(curl_error($ch));
curl_close($ch);

OpenSubtitles API 401 Unauthorized how to fix?

I'm trying to fetch subtitles from OpenSubtitles (http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC) like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Opensubtitles listing
function data($request){
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml\r\nUser-Agent: PHPRPC/1.0\r\n",
'content' => $request
)));
$server = 'http://api.opensubtitles.org/xml-rpc'; // api url
$file = file_get_contents($server, false, $context);
$response = xmlrpc_decode($file);
return $response;
}
//Get token
$request = xmlrpc_encode_request("LogIn", array('', '', 'eng', 'TemporaryUserAgent'));
$token = data($request)['token'];
//Get listing
$request = xmlrpc_encode_request("SearchSubtitles", array(
'imdb' => '0462499',
'sublanguageid' => 'eng',
'season' => '',
'episode' => '',
'token' => $token
));
$response = data($request);
var_dump($response);
?>
However I keep getting 401 Unauthorized. Does anyone know how to fix this problem? I know it's not a problem with the API because I am able to retrieve the token just fine.
Try using your username/password instead empty string.
And change UserAgent in TemporaryUserAgent in Header as written in
http://trac.opensubtitles.org/projects/opensubtitles/wiki/DevReadFirst
The second request should be in the following format:-
$request = xmlrpc_encode_request("SearchSubtitles", array($token, array(array('sublanguageid' => 'eng', 'imdbid' => 'your_imdbid'))));
Hope this helps.

POSTing JSON with GuzzleHttp\Client: returning 401 Unauthorized error

I'm trying to create a wrapper for a payment gateway api. I've chosen to use GuzzleHttp. Here is the basic code that I currently have. As the gateway expects input to be JSON formatted sent via HTTP POST, I tried two possible ways:
Using the json option and assigning a key-based array to it.
Explicitly setting content-type to application/json and sending a json formatted string via body.
Code:
$client = new Client([
'base_uri' => 'https://sandbox.gateway.com',
]);
$input = [
'merchant_id' => '12345-33445',
'security_key' => '**********',
'operation' => 'ping',
];
$clientHandler = $client->getConfig('handler');
$tapMiddleware = Middleware::tap(function ($request) {
foreach($request->getHeaders() as $h=>$v){
echo $h . ': ' . print_r($v) . PHP_EOL;
}
});
try {
$response = $client->post(
'/pg/auth',
[
'timeout' => 30,
'headers' => [
'Content-Type' => 'application/json',
'Cache-Control' => 'no-cache',
],
'body' => json_encode($input),
'debug' => true,
'handler' => $tapMiddleware($clientHandler)
]
);
print_r($response);
} catch(Exeption $e){
print_r($e);
}
Unfortunately, gateway got back with a 401 error although the credentials are correct. I suspect the way request is sent has an issue. I came to this conclusion as the headers printed from within the tap function are all arrays (especially content-type) instead of strings. Unlike what is described here http://guzzle.readthedocs.org/en/latest/request-options.html?highlight=request#json.
Array
(
[0] => GuzzleHttp/6.1.1 curl/7.43.0 PHP/5.5.29
)
User-Agent: 1
Array
(
[0] => sandbox.gateway.com
)
Host: 1
Array
(
[0] => application/json
)
Content-Type: 1
How about sending the request as suggested?
$client = new Client([
'base_uri' => 'https://sandbox.gateway.com',
]);
$client->request('POST', '/pg/auth', [
'timeout' => 30,
'debug' => true,
'json' => [
'merchant_id' => '12345-33445',
'security_key' => '**********',
'operation' => 'ping',
],
]);
For reference, see http://docs.guzzlephp.org/en/latest/request-options.html#json.

Categories