PHP YouTube API, get upload status - php

I'm having a heck of a time trying to get the status of a uploaded video to YouTube. I've followed the bellow URL to setup a CRON job that would send videos to YouTube, get a response; preferably with the YouTube ID so I can save this in a database. Down side is I can not get this to work.
http://framework.zend.com/manual/1.12/en/zend.gdata.youtube.html
My Code: (Which is basically copy and past from the above URL)
function upload($filename, $options = array()) {
$default = array_merge(
array(
'username' => 'USERNAME',
'password' => 'PASSWORD',
'service' => 'youtube',
'client' => null,
'source' => 'YouTube Component',
'loginToken' => null,
'loginCaptcha' => null,
'authenticationURL' => 'https://www.google.com/accounts/ClientLogin',
'applicationId' => 'YouTube Component',
'clientId' => 'YouTube Component',
'developerKey' => 'DEVELOPERS-KEY',
'content_type' => 'video/quicktime',
'title' => null,
'description' => null,
'category' => null,
'tags' => null,
),
(array)$options
);
extract($default);
$this->controller->Zend->loadClass('Zend_Gdata_YouTube');
$this->controller->Zend->loadClass('Zend_Gdata_ClientLogin');
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username,
$password,
$service,
$client,
$source,
$loginToken,
$loginCaptcha,
$authenticationURL
);
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource($filename);
$filesource->setContentType($content_type);
$filesource->setSlug($filename);
$myVideoEntry->setMediaSource($filesource);
$myVideoEntry->setVideoTitle($title);
$myVideoEntry->setVideoDescription($description);
$myVideoEntry->setVideoCategory($category);
$myVideoEntry->SetVideoTags($tags);
$myVideoEntry->setVideoPrivate();
$uploadUrl = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';
try {
$newEntry = $yt->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
echo $httpException->getRawResponseBody();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
try {
$control = $myVideoEntry->getControl();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}
if ($control instanceof Zend_Gdata_App_Extension_Control) {
if ($control->getDraft() != null && $control->getDraft()->getText() == 'yes') {
$state = $myVideoEntry->getVideoState();
if ($state instanceof Zend_Gdata_YouTube_Extension_State) {
print 'Upload status: ' . $state->getName() .' '. $state->getText();
} else {
print 'Not able to retrieve the video status information' .' yet. ' . "Please try again shortly.\n";
}
}
}
}
The above works in every way, minus the fact that I always get "Not able to retrieve the video status information...". What am I doing wrong? I've been staring at this for hours so I imagine its something simple that I've missed.

I wasn't to terribly far off with completing this. The answer was to replace all of the return code with (customized a bit because I need a return value as this is a CakePHP component.):
$state = $newEntry->getVideoState();
if ($state) {
$response['id'] = $newEntry->getVideoId();
} else {
$response['error'] = "Not able to retrieve the video status information yet. " .
"Please try again later.\n";
}
return $response;

Related

PHP: Converting WP_ERROR to Exception

I'm currently struggling to add error handling for the following case. An error is raise when a $db database is trying to write into it when it has --read-only access. This causes the following error on WP Engine.
WordPress database error INSERT command denied to user 'readonly'#'xx.xxx.xx.xx' for table 'responses' for query INSERT INTO `responses`
I wan't for this error to not break the application so I'm trying to add error handling. However, when I raise an Exception is not being caught. I know that WP_ERROR are different, so how to I convert an WP_ERROR to an exception?
function drools_request($data, $uid) {
try {
$db = _get_db();
$insertion = $db->insert("requests", [
"uid" => $uid,
"data" => json_encode($data),
]);
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database:');
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
This is what I tried so far without success. Here I check for is_wp_error() if this condition is true I throw an exception. However, this did not work. I thought this is how one would go about handling a WP_ERROR, but I wonder if there is another way to handle this type of errors. Here is the full class:
<?php
namespace StatCollector;
function drools_request($data, $uid) {
try {
$db = _get_db();
$insertion = $db->insert("requests", [
"uid" => $uid,
"data" => json_encode($data),
]);
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database:');
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
function drools_response($response, $uid) {
try {
$db = _get_db();
$insertion = $db->insert("responses", [
"uid" => $uid,
"data" => json_encode($response),
]);
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database:');
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
function results_sent($type, $to, $uid, $url = null, $message = null) {
try {
$db = _get_db();
$insertion = $db->insert("messages", [
"uid" => $uid,
"msg_type" => strtolower($type),
"address" => $to,
"url" => $url,
"message" => $message
]);
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database:');
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
function peu_data($staff, $client, $uid) {
try {
if (empty($uid)) {
return;
}
$db = _get_db();
if (! empty($staff)) {
$insertion = $db->insert("peu_staff", [
"uid" => $uid,
"data" => json_encode($staff)
]);
}
if( is_wp_error( $insertion ) ) {
throw new \Exception('Error writing to the database:');
}
if (! empty($client)) {
$insertion = $db->insert("peu_client", [
"uid" => $uid,
"data" => json_encode($client)
]);
}
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database:');
}
}
catch(\Exception $e){
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
function response_update() {
$uid = $_POST['GUID'];
$url = $_POST['url'];
$programs = $_POST['programs'];
if (empty($uid) || empty($url) || empty($programs)) {
wp_send_json(["status" => "fail","message" => "missing values"]);
return wp_die();
}
try {
$db = _get_db();
$insertion = $db->insert("response_update", [
"uid" => $uid,
"url" => $url,
"program_codes" => $programs
]);
wp_send_json(["status" => "ok"]);
wp_die();
if( is_wp_error($insertion) ) {
throw new \Exception('Error writing to the database.');
}
}
catch(\Exception $e)
{
echo 'Error writing to the database: ', $e->getMessage(), "\n";
}
}
wpdb::insert does not return WP_Error on error. On error it returns boolean false. The error printing is done inside of wpdb::query itself, but you can disable that by setting suppress_errors to true, and then gracefully get the previous error with the last_error property.
$db->suppress_errors(true);
//Note: If you still want to log the errors to your server log
//use $db->hide_errors(); instead.
$insertion = $db->insert("requests", [
"uid" => $uid,
"data" => json_encode($data),
]);
if( $insertion === false ) {
throw new \Exception('Error writing to the database: ' . $db->last_error);
}

Getting error when hit blockcypher api laravel

Here is my code:
public static function test(){
try{
$apiContext = ApiContext::create(
'test', 'bcy', 'v1',
new SimpleTokenCredential('my_token'),
array( 'mode' => 'sandbox','log.LogEnabled' => false, 'log.FileName' => 'BlockCypher.log', 'log.LogLevel' => 'DEBUG') );
$input = new \BlockCypher\Api\TXInput();
$input->addAddress("input_address");
$output = new \BlockCypher\Api\TXOutput();
$output->addAddress("output_address ");
$output->setValue(1000); // Satoshis
/// Tx
$tx = new \BlockCypher\Api\TX();
$tx->addInput($input);
$tx->addOutput($output);
$request = clone $tx;
$txClient = new TXClient($apiContext);
try {
$output = $txClient->create($tx);
} catch (Exception $ex) {
dd("Created TX", "TXSkeleton", null, $request, $ex);
exit(1);
}
dd("Created TX", "TXSkeleton", $output->getTx()->getHash(), $request, $output);
return $output;
}
catch (\BlockCypher\Exception\BlockCypherConnectionException $ex) {
echo $ex->getData();
die;
}
}
This is what I use to create CreateTransaction api but when I change the mode from bcy to btc it gives error for checking url get/post
code source :: click here
And here the response I'm getting also it came in catch so it's a error I have create api for generate address and create input address from there and make account on block.io and make a address for out from there to use in this api beside from these my account on blockcypher in free and nothing purchase in it
{
"errors":[
{
"error":"Unable to find a transaction to spend for address CCrB7dvBT1bqNfWxupKPH9v8yN7xukmqUF."
},
{
"error":"Error building transaction: Address 33cjwDAyNeAPVUMWqh9hdRxdmwdTE4kyTx is of unknown size.."
},
{
"error":"Not enough funds after fees in 0 inputs to pay for 0 outputs, missing -22200."
},
{
"error":"Error validating generated transaction: Transaction missing input or output."
}
],
"tx":{
"block_height":-1,
"block_index":-1,
"hash":"d21633ba23f70118185227be58a63527675641ad37967e2aa461559f577aec43",
"addresses":[
],
"total":0,
"fees":0,
"size":10,
"preference":"low",
"relayed_by":"116.193.163.150",
"received":"2017-11-14T10:20:43.757719705Z",
"ver":1,
"double_spend":false,
"vin_sz":0,
"vout_sz":0,
"confirmations":0,
"inputs":[
],
"outputs":[
]
}
}
I am working it on test purpose so use test main
I have installed it from github
I find one way of doing this thing here is my code
<?php
try
{
$apiContext = ApiContext::create(env('BlockCypher_net') , env('BlockCypher_cn') , env('BlockCypher_v') , new SimpleTokenCredential(env('BlockCypher_key')) , array(
'log.LogEnabled' => true,
'log.FileName' => 'BlockCypher.log',
'mode' => 'sandbox',
'log.LogLevel' => 'DEBUG'
));
$input = new BlockCypherApiTXInput();
$input->addAddress($user['address']);
$output = new BlockCypherApiTXOutput();
$output->addAddress($data['address12']);
$value_btc = 100000000 * ($data['btc12'] + 1 * ($data['btc12'] / 100));
// dd($value_btc);
$output->setValue($value_btc);
$tx = new BlockCypherApiTX();
$tx->addInput($input);
$tx->addOutput($output);
$request = clone $tx;
$params = array(
'includeToSignTx' => 1,
'script_type' => 'mutlisig-n-of-m',
);
$txClient = new TXClient($apiContext);
try
{
$txSkeleton = $txClient->create($tx, $params);
$privateKeys = array(
$user['private']
);
$txSkeleton = $txClient->sign($txSkeleton, $privateKeys);
$txSkeleton = $txClient->send($txSkeleton);
return array(
'success' => 0
);
// dd($txSkeleton->getTx()->getHash());
}
catch(BlockCypherExceptionBlockCypherConnectionException $ex)
{
return array(
'success' => 0,
'msg' => $ex->getData()
);
}
return $txSkeleton->getTx()->getHash();
}
catch(BlockCypherExceptionBlockCypherConnectionException $ex)
{
return array(
'success' => 0,
'msg' => $ex->getData()
);
}
it's work for me hope it will help you drop comment if get any error.

Adding more details to webhook

I am using Instamojo for my laravel app.
I have a form with input name like vtype, vname, name, phone, date, price.
My instamojo index.php looks like this --
<?php
use App\Vname;
$vname = Vname::find($request->vname);
$api = new Instamojo\Instamojo(config('instamojo.api_key'), config('instamojo.auth_token'), 'https://test.instamojo.com/api/1.1/');
try {
$response = $api->paymentRequestCreate(array(
"purpose" => "Online Vazhipad",
"amount" => $vname->price,
"buyer_name" => $request->name,
"phone" => $request->phone,
"send_email" => true,
"email" => Auth::user()->email,
"allow_repeated_payments" => false,
"redirect_url" => url('/online_vazhipad/thankyou')
"webhook" => url('/online_vazhipad/webhook')
));
$pay_ulr = $response['longurl'];
header("Location: $pay_ulr");
exit();
}
catch (Exception $e) {
print('Error: ' . $e->getMessage());
}
?>
and my webhook file looks like this -
<?php
$data = $_POST;
$mac_provided = $data['mac'];
unset($data['mac']);
$ver = explode('.', phpversion());
$major = (int) $ver[0];
$minor = (int) $ver[1];
if($major >= 5 and $minor >= 4){
ksort($data, SORT_STRING | SORT_FLAG_CASE);
}
else{
uksort($data, 'strcasecmp');
}
$mac_calculated = hash_hmac("sha1", implode("|", $data), config('instamojo.private_salt'));
if($mac_provided == $mac_calculated){
echo "MAC is fine";
if($data['status'] == "Credit"){
// Payment was successful my database code will be placed here
}
else{
return 'failed';
}
}
else{
echo "Invalid MAC passed";
}
?>
I wanted to add more information to my database like vtype and vname, but I dont know how to get the data from the form to here.
From the documentation i came to know that, the post request we get from instamojo only contains this much.
Please help me.

How to update a new atribute in Magento with CSV file thorugh API

I have a big numbers from Products in Magneto and i must add EAN Numbers to all the Products.
How could i update the new attribute from the CSV file through API.i want to update the EAN numbers from a ssh server through API SOAP.
This is not a full solution for you, but it is definitely a starting point for you. Good Luck
$productData = array(
'additional_attributes' => array(
'single_data' => array(
array(
'key' => 'ean',
'value' => 'value',
),
),
),
);
$productId = '1000000';
$soap = new SoapConnection('1','2','3');
echo $soap->_catalogProductUpdate($productId,$productData);
class SoapConnection
{
protected $soap_client;
protected $session_id;
function __construct($soap_host, $api_user, $api_pass)
{
try{
echo "Connecting to $soap_host\n";
$this->soap_client = new SoapClient( $soap_host, array('trace' =>true,
'connection_timeout' => 30,
'cache_wsdl' => WSDL_CACHE_NONE,
'keep_alive' => false
));
$this->session_id = $this->soap_client->login( $api_user, $api_pass);
echo "Connected with session id ".$this->session_id."\n";
return true;
} catch (SoapFault $e) {
echo "Soap Exception connecting to $soap_host: ". $e->getMessage(). "\n";
var_dump($this->soap_client->__getLastRequest()); var_dump($this->soap_client->__getLastResponse());
return false;
}
}
function _catalogProductUpdate($sku, $args)
{
try
{
return $this->soap_client->catalogProductUpdate($this->session_id, $sku, $args);
} catch (SoapFault $e) {
echo "Soap Exception _catalogProductUpdate: ". $e->getMessage(). "\n";
return false;
}
}
}
EDIT:
here is how to read a csv:
$file = fopen("my file path .csv","r");
while($row = fgetcsv($file))
{
$row[0];//column1
$row[1];//column2 etc etc etc
}
fclose($file);

Fatal error: Call to undefined method stdClass::stream_publish()

Well I am trying to post on facebook's wall but I get this error:
Fatal error: Call to undefined method stdClass::stream_publish()
The code I am trying is this
<?php
define('FB_APIKEY', '<Your Api Key>');
define('FB_SECRET', '<Secret>');
define('FB_SESSION', '<Session>');
require_once('facebook.php');
echo "post on wall";
echo "<br/>";
try {
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
$message = '';
$attachment = array(
'name' => $_POST["name"],
'href' => $_POST["href"],
'description' => $_POST["description"],
'media' => array(array('type' => 'image',
'src' => $_POST["src"],
'href' => $_POST["href"])));
$action_links = array( array('text' => 'Visit Us', 'href' => '<link to some place here>'));
$attachment = json_encode($attachment);
$action_links = json_encode($action_links);
$target_id = "<Target Id>";
$session_key = FB_SESSION;
if( $facebook->api_client->stream_publish($message, $attachment, $action_links, null, $target_id)) {
echo "Added on FB Wall";
}
} catch(Exception $e) {
echo $e . "<br />";
}
?>
Well, as it is written in the error message there is no method "stream_publish" in $facebook->api_client.
Consult the manual of the library you are using to connect to the facebook.
If $facebook->api_client is not an object, then the line:
$facebook->api_client->session_key = FB_SESSION;
Will make php silently cast $facebook->api_client to an object of type stdClass. Which, later on down the code, will cause the Fatal error: Call to undefined method stdClass::stream_publish() that you are getting.
Try changing:
...
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
...
to catch for when api_client is false (or, perhaps, not an object):
...
$facebook = new Facebook(FB_APIKEY, FB_SECRET);
if (!( $facebook->api_client )) {
//throw error
echo 'Need to sort this bit out';
exit;
}
$facebook->api_client->session_key = FB_SESSION;
$facebook->api_client->expires = 0;
...
And then, if that does throw an error, you'd need to investigate why $facebook->api_client is null.

Categories