PHP API sending POST requests - php

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

Related

Dialogflow ES PHP Client Library 500 (Internal Server Error)

Dialogflow and PHP newbie here.
I have created and implemented a mini button-based chatbot using Dialogflow ES PHP client library in one of my client's WordPress site.
Everything worked as expected in my local environment, but when I pushed my codes to the staging site, I got a 500 (Internal Server Error) in my DevTool. The Dialogflow console still got my initial intent from staging and responded accordingly with logs without any error, however.
This is the error shown in my server error.log
PHP Fatal error:
Uncaught Google\ApiCore\ApiException: {
"message": "Input text not set.",
"code": 3,
"status": "INVALID_ARGUMENT",
"details": []
}
thrown in /var/www/my-staging-domain.com/public/vendor/google/gax/src/ApiException.php on line 267, referer: https://my-staging-domain.com/
AJAX call frontend JS file
async function sendDataToDialogflow(text, sessionID) {
let result;
try {
result = await $.ajax({
url: /dialogflow.php,
type: "POST",
data: {
query: text,
lang: "en",
sessionId: sessionID,
},
success: function(res, status, xhr) {
setDialogflowResponse(res);
},
error: function(error) {
console.warn(error);
}
});
return result;
} catch (error) {
console.log(error);
}
}
My backend dialogflow.php file setting
<?php
namespace Google\Cloud\Samples\Dialogflow;
namespace Google\Protobuf;
use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;
use Google\Cloud\Dialogflow\V2\Context;
require $_SERVER['DOCUMENT_ROOT']. '/vendor/autoload.php';
if (isset($_POST) && isset($_POST["query"])) {
$query = $_POST["query"];
$lang = $_POST["lang"];
$sessionId = $_POST["sessionId"];
if (isset($_POST['query'])) {
detect_intent_texts($projectId,$query,$sessionId);
}
}
function detect_intent_texts($projectId, $text, $sessionId, $context = '', $parameters = '', $languageCode = 'en-US')
{
// -------------- new session --------------
$credential = array('credentials' => $_SERVER['DOCUMENT_ROOT'].'/client-secret.json');
$sessionsClient = new SessionsClient($credential);
$session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
//printf('Session path: %s' . PHP_EOL, $session);
// -------------- create text input --------------
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);
if($context !== '') {
// -------------- create context struct --------------
$contextStruct = new Struct();
$contextStruct->setFields($context['parameters']);
// -------------- create context input --------------
$contextInput = new Context();
$contextInput->setLifespanCount($context['lifespan']);
$contextInput->setName($context['name']);
$contextInput->setParameters($contextStruct);
}
if($parameters !== '') {
$paramStruct = new Struct();
$paramStruct->setFields($parameters['parameters']);
}
// -------------- create query input --------------
$queryInput = new QueryInput();
$queryInput->setText($textInput);
// -------------- get response and relevant info --------------
$response = ($parameters ? $sessionsClient->detectIntent($session, $queryInput) : $sessionsClient->detectIntent($session, $queryInput));
$responseId = $response->getResponseId();
$queryResult = $response->getQueryResult();
$fields = $queryResult->getParameters()->getFields();
$jsonString = $queryResult->serializeToJsonString();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$confidence = $queryResult->getIntentDetectionConfidence();
$fulfillmentText = $queryResult->getFulfillmentText();
$fulfillmentMessages = json_decode($queryResult->getFulfillmentMessages()[0]->serializeToJsonString(), true);
function get_field_value($field)
{
$kind = $field->getKind();
if ($kind == "string_value")
return $field->getStringValue();
else if ($kind == "number_value")
return $field->getNumberValue();
else if ($kind == "bool_value")
return $field->getBoolValue();
else if ($kind == "null_value")
return $field->getNullValue();
else if ($kind == "list_value") {
$list_values = $field->getListValue()->getValues();
$values = [];
foreach($list_values as $list_value)
$values[] = get_field_value($list_value);
return $values;
}
else if ($kind == "struct_value")
return $field->getStructValue();
}
$parameters = [];
foreach($fields as $key => $field) {
$parameters[$key] = get_field_value($field);
}
$returnResponse = array(
'responseId' => $responseId,
'fulfillmentText' => $fulfillmentText,
'fulfillmentMessages' => $fulfillmentMessages,
'queryText' => $queryText,
'parameters' => json_decode($jsonString)->parameters
);
echo json_encode($returnResponse);
$sessionsClient->close();
}
composer.json
{
"require": {
"google/cloud-dialogflow": "^0.29.0",
"google/protobuf": "^3.21",
"protobuf-php/protobuf": "^0.1.3",
"ext-bcmath": "*"
}
}
Any insights on this issue would be much appreciated!
I've updated staging from http to https, but this didn't fix the issue.
I've read through all the documents/questions on stackoverflow I could find, but in vain.

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.

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

Why this Ajax request returns as an error?

Here's my problem : I make an ajax request to a WordPress PHP function. Strange thing is : this response is returned as an error.
But in the error log, the responseText is the requested data (JSON as a string), the status is 200 and statusText is "OK".
Here's the request :
$.ajax({
type: "GET",
dataType: "json",
url: ajaxurl,
data: { action:'my_wp_function',username: settings.username, list: settings.list, hashtag: settings.hashtag, count: settings.count, exclude_replies: settings.hideReplies, lastID:settings.lastID }
}).done(function( res ) {
}).error(function(err) { console.log(err); }); // err.responseText = the requested data ...
S if all is OK, why is this request detected as if an error has occurred ?
EDIT, here's the PHP I request:
<?php
require_once("twitteroauth/twitteroauth.php");
require_once('config.php');
if (CONSUMER_KEY === '' || CONSUMER_SECRET === '' || CONSUMER_KEY === 'CONSUMER_KEY_HERE' || CONSUMER_SECRET === 'CONSUMER_SECRET_HERE') {
echo 'You need a consumer key and secret keys. Get one from dev.twitter.com/apps';
exit;
}
$username = filter_input(INPUT_GET, 'username', FILTER_SANITIZE_SPECIAL_CHARS);
$number = filter_input(INPUT_GET, 'count', FILTER_SANITIZE_NUMBER_INT);
$exclude_replies = filter_input(INPUT_GET, 'exclude_replies', FILTER_SANITIZE_SPECIAL_CHARS);
$list_slug = filter_input(INPUT_GET, 'list_slug', FILTER_SANITIZE_SPECIAL_CHARS);
$hashtag = filter_input(INPUT_GET, 'hashtag', FILTER_SANITIZE_SPECIAL_CHARS);
$lastID = filter_input(INPUT_GET, 'lastID', FILTER_SANITIZE_SPECIAL_CHARS);
if(CACHE_ENABLED) {
// Generate cache key from query data
$cache_key = md5(
var_export(array($username, $number, $exclude_replies, $list_slug, $hashtag), true) . HASH_SALT
);
$cache_path = dirname(__FILE__) . '/cache/';
foreach (glob($cache_path . '*') as $file) {
if (filemtime($file) < time() - CACHE_LIFETIME) {
unlink($file);
}
}
if(file_exists($cache_path . $cache_key)) {
header('Content-Type: application/json');
echo file_get_contents($cache_path . $cache_key);
exit;
}
}
function getConnectionWithToken($cons_key, $cons_secret, $oauth_token, $oauth_secret)
{
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_secret);
return $connection;
}
// Connect
$connection = getConnectionWithToken(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET);
// Get Tweets
if (!empty($list_slug)) {
$params = array(
'owner_screen_name' => $username,
'slug' => $list_slug,
'per_page' => $number
);
$url = '/lists/statuses';
}
else if($hashtag) {
if($lastID){
$params = array(
'max_id' => $lastID,
'count' => 100,
'q' => '#'.$hashtag.' filter:images',
'include_entities' => true
);
}
else {
$params = array(
'count' => 100,
'q' => '#'.$hashtag.' filter:images',
'include_entities' => true
);
}
$url = '/search/tweets';
} else {
$params = array(
'count' => $number,
'exclude_replies' => $exclude_replies,
'screen_name' => $username
);
$url = '/statuses/user_timeline';
}
// $rawTweets = $connection->get($url, $params);
// $tweets = array();
$tweets = $connection->get($url, $params);
// Return JSON Object
header('Content-Type: application/json');
$tweets = json_encode( $tweets);
if(CACHE_ENABLED) file_put_contents($cache_path . $cache_key, $tweets);
echo $tweets;
try like this
$.ajax({
url : _url,
type : "GET",
dataType : "JSON",
error : function(){
console.log("Cannot bring the core fields");
},
success : function (response){
console.info( response );
});

solr data can not be sent before solrcommit

What my problem is that I can not send array to solr machine in order to update. I am using codeigniter as a framework and here is my code:
$solrData = array();
$solrData['id'] = $this->data['profil_data']['id'];
$solrData['site'] = $this->data['profil_data']['site'];
$solrData['url_Domain'] = $this->data['profil_data']['url_Domain'];
$solrData['url_Page'] = $this->data['profil_data']['url_Page'];
$solrData['url_Profil'] = $this->data['profil_data']['url_Profil'];
$solrData['scr_Kobi_Rank'] = $this->data['profil_data']['scr_Kobi_Rank'];
$solrData['scr_A'] = $this->data['profil_data']['scr_A'];
$solrData['scr_B'] = $this->data['profil_data']['scr_B'];
$solrData['scr_C'] = $this->data['profil_data']['scr_C'];
$solrData['scr_D'] = $this->data['profil_data']['scr_D'];
$solrData['loc_City'] = $this->input->post('plakano');
$solrData['loc_Lat_Lon'] = $this->input->post('loc_Lat_Lon');
$solrData['com_Category'] = explode(',', $this->input->post('category'));
$urunData = $this->input->post('urun_list');
foreach($urunData as $row)
{
$ontoData = $this->m_onto->getOntoDataByOntoDataId($row);
$solrData['com_Products'][] = $ontoData['baslik'];
}
$hizmetData = $this->input->post('hizmet_list');
foreach($hizmetData as $row)
{
$ontoData = $this->m_onto->getOntoDataByOntoDataId($row);
$solrData['com_Services'][] = $ontoData['baslik'];
}
$solrData['com_Type'] = $this->input->post('sirketturu');
$solrData['com_Description'] = $this->input->post('description');
$solrData['com_Title_Selected'] = $this->input->post('title');
$solrData['com_Title_Long'] = $this->data['profil_data']['com_Title_Long'];
$solrData['crm_Tel'] = $this->input->post('tel');
$solrData['crm_Fax'] = $this->input->post('fax');
$solrData['crm_Email'] = $this->input->post('email');
$this->solr->updateSolrProfilData($solrData);
And solr process:
public function updateSolrProfilData($arrData)
{
if(count($arrData) == 0)
return FALSE;
$solrClientOptions = $this->solrClientOptionsYazProfil;
$solrClientOptionsCommit = $this->solrClientOptionsYazProfilCommit;
$solrClient = new SolrClient($solrClientOptions);
$solrDoc = new SolrInputDocument();
foreach($arrData as $firmaField => $firmaValue)
{
if(! is_array($firmaValue))
{
$solrDoc->addField($firmaField, $firmaValue);
}
else
{
foreach($firmaValue as $firmaField2 => $firmaValue2)
{
if($firmaValue2 != '')
{
$solrDoc->addField($firmaField, $firmaValue2);
}
}
}
}
try {
$this->_solrCommit($solrClientOptionsCommit);
} catch (Exception $e) {
echo $e->getMessage();
}
}
Solr Commit function:
private function _solrCommit($solrArr)
{
$urlCommit = 'http://' . $solrArr['hostname'] . ":" . $solrArr['port'] . '/' . $solrArr['path'] . "/update?stream.body=%3Ccommit/%3E&wt=json";
$output = file_get_contents($urlCommit);
$outputArr = json_decode($output, TRUE);
if ($outputArr['responseHeader']['status'] === 0)
return TRUE;
else
return FALSE;
}
And that is the options:
private $solrClientOptionsYazProfilCommit = array(
'hostname' => SOLR_HOST_YAZ,
'login' => '',
'password' => '',
'port' => SOLR_PORT,
'path' => 'solr/collection1'
);
Altough try-catch returns no error, the data can not be updated. Moreover, code sends solr commit succesfully. I checked the url but it is in correct form. What is wrong in here?
Dont use PHP/Pecl solr libs. If you can access solr via a URL then you should just use PHP and CURL:
static function doCurl($url, $username = null, $password = null) {
if (!function_exists('curl_init')) {
// throw error
}
$ch = curl_init();
$opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_TIMEOUT => 120,
CURLOPT_FAILONERROR => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY
);
if ($password != null && $username != null) {
$opts[CURLOPT_USERPWD] = "$username:$password";
}
curl_setopt_array($ch, $opts);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
usage is:
doCurl("http://hostNameHere:8983/solr/select/?q=solr&start=0&rows=10&indent=on", "user", "pass");
Your issue is that you are never issuing a command to Solr to add the document that you have built to your index. You are only issuing the commit command, which is executing successfully.
Since you are using PHP, I would recommend using the PHP SolrClient. This will save you from having to manually write all of the functions (add, delete, commit, etc.) yourself. In this case, you would need to call the addDocument function.

Categories