How to pass params for Vend Api? - json

I am trying to use VEND API but I have no clue how to pass parameters for doing various things. I found a set of codes in the API doc but can't get through it. Below is what I been up to.
<?php
/**
*
* A class made for utility methods around Vend's API
*
*
*/
class VendApiUtils {
/**
* A simple static method to call Vend API urls
*
* #param string $url
* #param string $username
* #param string $password
* #param array $params <OPTIONAL>
*/
public static function requestVendApiUrl($url, $username, $password, $params = array())
{
// is cURL installed?
if (!function_exists('curl_init')) {
throw new Exception('CURL is not installed!');
}
// Create a new cURL instance
$ch = curl_init();
$opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array('data' => json_encode($params)),
CURLOPT_TIMEOUT => 120,
CURLOPT_FAILONERROR => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_USERPWD => "$username:$password"
);
// Assign the cURL options
curl_setopt_array($ch, $opts);
// Get the response
$response = curl_exec($ch);
print_r($response);
// Close cURL
curl_close($ch);
// Execute the request & get the response
echo $response;
}
}
$your_domain='https://mydomain.vendhq.com';
$your_username='myuser';
$your_password='mypass';
$params = array('GET'=>'/api/stock_movements');
$response = VendApiUtils::requestVendApiUrl($your_domain, $your_username,$your_password, $params);
//echo $response;
?>
Any Help would be highly appreicated.
Regards,
Abnab

I'm not sure why you think the URL needs to go into the $params array; that looks to me like the place for, well, params. I think the function is intended to be used more like this:
// Fixed parts, same for any request
$domain='https://mydomain.vendhq.com';
$username='myuser';
$password='mypass';
// Variable parts, depending on what you want to do
$url = '/api/stock_movements';
$params = array('some_key' => 'some_value');
$response = VendApiUtils::requestVendApiUrl($domain . $url, $username, $password, $params);

Please check pyvend client library.

Related

Easiest way to display specific value from reddit comments .json file?

Is there a simple way to display on my website a specific value, for example "Gonna make this my new alarm ringtone" from following reddit comments .json file: https://www.reddit.com/r/funny/comments/mi0lic/.json
I've found a simple php script that works with reddit user .json files:
... $content = file_get_contents("https://www.reddit.com/user/joshfolgado/about.json");
$result = json_decode($content);
print_r( $result->data->subreddit->title ); ...
But I can't make this work using the comments .json file:
... $content = file_get_contents("https://www.reddit.com/r/funny/comments/mi0lic/.json");
$result = json_decode($content);
print_r( $result->data->children->data->title ); ...
Any other simple script that does the job is also welcome.
The issue can be found here:
print_r( $result->data->children->data->title ); ...
$result->data->children is an Array holding all the comments returned by the API.
We should 'search' all those comments (in your example, it's just 1) for the desired object.
Consider the following code example we're I've used array_filter to custom filter the objects found in $result->data->children array.
<?php
// Search string
$search = 'Gonna make this my new alarm ringtone';
// Get json using CURL
$json = getJson('t3_mi0lic');
// Search ->children
$res = array_filter($json->data->children, function ($child) use ($search) {
// Include if ->data->title qeuals search
return $child->data->title === $search;
});
// Show result
var_dump($res);
// Get JSON by $userId
function getJson($userId) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.reddit.com/api/info/?id=' . $userId,
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_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'
));
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response);
}

Post a not empty file to Dspace with Curl

I am posting a file to dspace through dspace api, I am doing this with an action in php. With postman I send a form-data with the file, filename, bitstream id and token.
I am getting the temp file path with $_FILES and sending it by postfields curl option, but the file uploads empty, or with weird data, without its content.
public function actionSubirBitstream()
{
if (Yii::$app->request->isPost) {
$body = $_POST;
$prefijo = '/rest/items/';
$host = ConfiguracionDspace::find()->where("clave='host'")->one()->valor;
$puerto = ConfiguracionDspace::find()->where("clave='puerto'")->one()->valor;
$token = $body['token'];
$id = $body['id'];
$final = '/bitstreams';
$name = $body['name'];//nombre del archivo sin espacios
$params = "?name=$name";
$url = $host . ':' . $puerto . $prefijo . $id . $final . $params;
$file = $_FILES['file']['tmp_name'];
//$path = $body['path'];
//$file = new CURLFILE("$path");
$headers = array("Content-Type: application/json", 'Accept: application/json', "rest-dspace-token: " . $token);
$curl = curl_init($url);
$options = array(
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('file'=> $file,'name' => $name),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
}
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => array('photo'=> new CURLFILE('/C:/Users/pfile3.jpeg'),'name' => $name),
this is the example of uploading a file with form key as photo and another key name
in your screen shot you have id and token in form data but in code its not inside POSTFIELDS
in postman you can generate equalent code of request in any language , try generating the PHP equalent code and see if it works:
To do this just click code link under the request url after saving the request
I already post the file by the $_FILE variable, But what I needed to do was to use CURLFILE to create a new file, and give it the temp path of the file in the server
$file = $_FILES['file']['tmp_name'];
and this in the postfields
CURLOPT_POSTFIELDS => array('file'=> new CURLFile("$file"),'name' => $name),
Thanks for the help friends
Here the code:
public function actionSubirBitstream()
{
if (Yii::$app->request->isPost) {
$body = $_POST;
$prefijo = '/rest/items/';
$host = ConfiguracionDspace::find()->where("clave='host'")->one()->valor;
$puerto = ConfiguracionDspace::find()->where("clave='puerto'")->one()->valor;
$token = $body['token'];
$id = $body['id'];
$final = '/bitstreams';
$name = $body['name'];//nombre del archivo sin espacios
$params = "?name=$name";
$url = $host . ':' . $puerto . $prefijo . $id . $final . $params;
$file = $_FILES['file']['tmp_name'];
//$path = $body['path'];
//$file = new CURLFILE("$path");
$headers = array("Content-Type: application/json", 'Accept: application/json', "rest-dspace-token: " . $token);
$curl = curl_init($url);
$options = array(
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('file'=> new CURLFile("$file"),'name' => $name),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
}
The posted files with the rigth size(finally)
The form data I send by Postman, no need to use the field path

Use JSON in Symfony controller

I'm looking for a way to execute a little bit of JSON from my Symfony (2.6 btw) controller, moreover than an other action (post data into database)
In fact, there is an register page with a controller which put data into database and then, redirect user to another page. But i need that my controller execute too a little bit of JSON to use Mailchimp API.
I've found a lot of docs about how to render JSON response, but, it seems to me that it's not what i want to be.
There is my controller
public function registerAction(Request $request)
{
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.registration.form.factory');
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$user = $userManager->createUser();
$user->setEnabled(true);
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$form = $formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
if ($form->isValid()) {
// Gestion du type d'utilisateur et ajout du role
$user_type = $form->get('user_profile')->get('type')->getData();
$new_role = $this->roles[$user_type];
$event = new FormEvent($form, $request);
$user = $event->getForm()->getData();
$user->addRole($new_role);
$user->getUserProfile()->setEmail($user->getEmail());
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_registration_confirmed');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
return $this->render('FOSUserBundle:Registration:register.html.twig', array(
'form' => $form->createView(),
));
}
There is my JSON request
{
"email_address": "$email",
"status": "subscribed",
"merge_fields": {
"FNAME": "$name",
"LNAME": "$lastname",
"DATE": "$date"
}
}
So, how can i do to execute this JSON with this controller ?
Thank you in advance for your help (and sorry for my excellent english)
You probably want to create the JSON from an array rather than try to pass variables. Try:
$data = [
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $name,
'LNAME' => $lastname,
'DATE' => $date,
],
];
$json = json_encode($data);
Then I'm assuming this data gets sent to MailChimp in a POST request? If so, you could use Guzzle to send the data to MailChimp:
First add the guzzle dependency in composer by running:
composer require guzzlehttp/guzzle
Then send the data:
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://MAILCHIMP_URL', ['body' => $data]);
To send JSON instead of raw data, do the following:
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://MAILCHIMP_URL', ['json' => $data]);
Depending on the response status, you can then handle the logic afterwards.
You can achieve this also using JsonResponse (Symfony\Component\HttpFoundation\JsonResponse)
use Symfony\Component\HttpFoundation\JsonResponse;
...
// if you know the data to send when creating the response
$data = [
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $name,
'LNAME' => $lastname,
'DATE' => $date,
]
];
$response = new JsonResponse($data);
return $response;
More details here https://symfony.com/doc/current/components/http_foundation.html

How to get configuration params in Controller Console in Yii2 Framework

How to get configuration params in Console Controller in Yii2 Framework
I try below code but its not working
Yii::$app->params['params_1']
Try This:
Code in config/params.php
<?php
return array(
'apptitle' => 'stackOverlfow',
//Define PARAMS as you need.
);
?>
You can use PARAM as below:
\Yii::$app->params['apptitle'];
Example:
echo "App title is:". \Yii::$app->params['apptitle'];
As you mentioned Basic Template Of Yii.
config/web.php
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
.
.
.
],
'params' => $params,
];
return $config;
?>
config/params.php
<?php
$params = [
'params_1' => 'YourValue'
];
return $params;
?>
SomeWhere.php
<?=Yii::$app->params['params_1'];?>
Seems that you insert your param to other conf params.php.
My helper function:
/**
* Get param value from config file.
* Получение параметра из конфигурационного файла
*
* #param string $param_name название пареметра
*
* #return string|ApicoServerErrorHttpException Значение параметра
* #throws \Exception
*/
public static function yiiparam($param_name)
{
if (isset(\Yii::$app->params[$param_name])) {
return \Yii::$app->params[$param_name];
} else {
$msg = "Can not find param in configuration file. have been search by param = " . VarDumper::export($param_name);
\Yii::error($msg, __METHOD__);
throw new ServerErrorHttpException();
}
}

write custom query with zend framework 2

I want to perform a custom query in zf2. Now I have a Album controller and AlbumTable. Inside AlbumTable, I want to perform an join operation. But I am unable to do this.Please give me some suggation.
below my code:
namespace WebApp\Table;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Sql;
new Zend\Db\Adapter\Adapter;
class UserTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function searchUser($search)
{
$search = "mehedi";
$adapter = new Adapter();
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('foo');
$select->join('profiles', 'user.user_id = profiles.ownerId', array('name'));
$select->where(array('id' => 2));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
return $results;
}
}
The issue is you are trying to instantiate your Adapter with no parameters, when it requires at least a driver :
$adapter = new Adapter(); // Bad
$adapter = new Adapter($driver); // ..
You should use the ServiceManager to get your Adapter, did you start with the Skeleton Application?
It should have already been injected into the TableGateway for you..
$adapter = $this->getAdapter();
An example of instantiating an Adapter:
$config = $serviceLocator->get('Config');
$adapter = new Adapter($config['db']);
where you specify your setup inside your config, local.php will do:
return array(
/**
* Database Config
*/
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=dbname;host=localhost',
'username' => 'root',
'password' => 'password',
),
I got some solution of this problem with helping all of here.
$adapter = $this->tableGateway->getAdapter();
/* $adapter variable is used to fetch Adapter
configuration from serivce manager. */
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('foo');
$select->join('profile', 'foo.skillId = profile.id', array('name'));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
/* if you want you can see your
desired output in here. */
foreach ($results as $person) {
echo "<pre>";
print_r($person);
}
return $results;
It's because the join method expects an array for the join table. Also I personally would prefix the tables in the query, something like this:-
$search = "mehedi";
$adapter = new Adapter();
$sql = new Sql($adapter);
$select = $sql->select();
// PREFIXED THE foo table f
$select->from(array('f' =>'foo'));
// PREFIXED THE profiles table p
$select->join(array('p' => 'profiles'), 'user.user_id = profiles.ownerId', array('name'));
$select->where(array('id' => 2));
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
return $results;