Getting error when hit blockcypher api laravel - php

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.

Related

Guzzle async POST requests not being sent

I'm trying to make 4 async search calls (POST HTTP request) to search 4 database tables at the same time, then wait for all of them to finish (asynchronously), combine the results and return them to the user.
Here is my code:
public static function async_search($search_words)
{
$curl = new CurlMultiHandler();
$client = new Client([
'base_uri' => 'https://mytestapi.com/',
'timeout' => 0,
]);
$finished_promisesArr = array(
'search1' => 0,
'search2' => 0,
'search3' => 0,
'search4' => 0,
);
$bodyArr = array(
'search_words' => $search_words,
);
$search1_promise = $client->requestAsync('POST', 'search1', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
echo 'got response';
$finished_promisesArr['search1'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search1'] = 1;
}
);
$search2_promise = $client->requestAsync('POST', 'search2', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
$finished_promisesArr['search2'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search2'] = 1;
}
);
$search3_promise = $client->requestAsync('POST', 'searchCompanies', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
$finished_promisesArr['search3'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search3'] = 1;
}
);
$search4_promise = $client->requestAsync('POST', 'searchCompaniesByIndustries', array(
'form_params' => $bodyArr,
))->then(
function(ResponseInterface $response) {
$finished_promisesArr['search4'] = 1;
},
function (RequestException $e) {
$finished_promisesArr['search4'] = 1;
}
);
$promisesAggregate = GuzzleHttp\Promise\all([$search1_promise, $search2_promise, $search3_promise, $search4_promise]);
foreach ($promisesAggregate as $agg) {
$curl->tick();
}
$keep_running = true;
while ($keep_running) {
$all_processes_finished = true;
foreach ($finished_promisesArr as $promise => $status) {
if (!$status) {
$all_processes_finished = false;
}
}
if ($all_processes_finished) {
$keep_running = false;
}
}
return array();
}
Please ignore the empty array in the result and the fact that I'm not doing anything with the response.
I've got logs on the server methods and they're not even being called, and the loop continues to run infinitely.
Note that when I use the request method instead of requestAsync I do get the correct result.
Any ideas here?
Thank's!
Just call $promisesAggregate->wait() after you get it from GuzzleHttp\Promise\all function.
It means the same as your code, but does it right (your wait code calls ->tick() only once and this is the mistake).

PHP API sending POST requests

I have this function that connects to an external API:
function ICUK_Request($url, $method = 'GET', $body = NULL) {
$client = new IcukApiClient();
$client->username = "user";
$client->key = "pass";
$client->encryption = "SHA-512";
$req = new IcukApiRequest();
$req->url = $url;
$req->method = $method;
if(!is_null($body)) {
$req->body = $body;
}
$res = $client->send($req);
if ($res->success) {
$obj = json_decode($res->response);
}
else {
throw new Exception('There was an error contacting the API.');
}
return $obj;
}
the API docs are telling me to send the POST request like this:
POST /domain/registration/new/
{
"domain_name": "domain.co.uk",
"hosting_type": "NONE",
"registration_length": 1,
"auto_renew": false,
"domain_lock": false,
"whois_privacy": false,
"contact_registrant_id": 1
}
so i tried this:
$arr = array(
"domain_name" => "domain.co.uk",
"hosting_type" => "NONE",
"registration_length" => 1,
"auto_renew" => false,
"domain_lock" => false,
"whois_privacy" => false,
"contact_registrant_id" => 1
);
ICUK_Request("/domain/registration/new", "POST", $arr);
but thats giving me a response in the API Logs saying:
{
"exception_message": "Internal API exception occured",
"exception_type": "InternalApiException"
}
im not sure if this would be anything generic and if anyone can help on how to POST the data?
Send it as json:
$values = json_encode($arr);
ICUK_Request("/domain/registration/new", "POST", $values);

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);

mongodb update exception 'document fragment is too large'

Updating my collection record field with 'MongoBinData', exception is triggered:
"document fragment is too large: 21216456, max: 16777216"
I find some web discussion about 'allowDiskUse:true' for aggregate, but nothing ubout 'update'.
Here a part of code in PHP:
try {
$criteria = array( '_id' => $intReleaseId);
$fileData = file_get_contents( $_FILES[ $fileKey]["tmp_name"]);
$mongoBinData = new MongoBinData( $fileData, MongoBinData::GENERIC)
$docItem['data'] = $mongoBinData;
$docItem['fileType'] = $strFileType;
$docItem['fileSize'] = $intFileSize;
$docItem['fileExtension'] = $strFileExtension;
$docItem['fileName'] = $strFileName;
$options = array( "upsert" => true,
'safe' => true, 'fsync' => true,
'allowDiskUse' => true ); // this option doesn't change anything
$reportJson = self::GetCollection('releases')->update( $criteria, $docItem, $options);
...
MongoDb release is db version v3.0.6
Some idea ?
Self resolved.
Use gridFS is immediate and simple.
$_mongo = new MongoClient();
$_db = $_mongo->selectDB($_mDbName);
$_gridFS = $_db->getGridFS();
/* */
function saveFileData($intReleaseId, $binData) {
$criteria = array( '_id' => $intReleaseId);
// if exist or not, remove previous value
try {
$_gridFS->remove( $criteria);
}
catch(Exception $e) {}
// store new file content
$storeByteCompleted = false;
try {
$reportId = $_gridFS->storeBytes(
$binData,
array("_id" => $intReleaseId));
if ($reportId == $intReleaseId) {
$storeByteCompleted = true;
}
catch(Exception $e) {}
return $storeByteCompleted;
}
function loadFileData($intReleaseId) {
$gridfsFile = null;
$binData = null;
try {
$gridfsFile = $_gridFS->get($intReleaseId);
}
catch(Exception $e) {}
if ($gridfsFile != null) {
$binData = $gridfsFile->getBytes()
}
return $binData;
}
That's all.

PHP YouTube API, get upload status

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;

Categories