Cannot create an article with Bexio API in PHP - php

I try to post an article to Bexio via the Bexio API: https://docs.bexio.com/resources/article/
There is also a sample for PHP: https://docs.bexio.com/samples/
I updated the scopes in the config.php to allow read and write articles.
I updates the bexioConnector.class.php so i can get Articles (works):
public function getArticles($urlParams = array()) {
return $this->call('article', $urlParams);
}
public function call($ressource, $urlParams = array(), $postParams = array(), $method = Curl::METHOD_GET) {
$url = $this->api_url . "/" . $this->org . "/" . $ressource;
$data = $this->curl->call($url, $urlParams, $postParams, $method, $this->getDefaultHeaders());
return json_decode($data, true);
}
So i can use now this code to get all articles (works):
$bexioProducts = $con->getArticles(array('order_by' => 'id'));
Now i want to create articles with the POST method.
So i added this function to the bexioConnector.class.php
public function postArticle($postParams = array(), $urlParams = array()) {
return $this->call('article', $urlParams, $postParams, Curl::METHOD_POST);
}
So i use this code to create a product:
$con->postArticle(array(
'intern_code' => "SKU-3214"
)
);
But this ends in an error:
{"error_code":415,"message":"Could not parse the data."}
I have tried a lot but i always get the same error message.
What could i have don possibly wrong?

I found the error. I need to encode it as a json first.
So i changed my postArticle function:
public function postArticle($postParams = array(), $urlParams = array()) {
$json = json_encode($postParams);
return $this->call('article', $urlParams, $json, Curl::METHOD_POST);
}

Related

Extract path from generateUrl php symfony

Pretty basic question and I am sorry for that but I haven't find the answer to my problem yet
I have an getArticleUrl method that returns $this->urlGenerator->generate($article);
In my function, all I need to do is to append the query params to the articleUrl
public function articleController(Request $request, string $uuid)
{
$queryParams = $request->query->all();
$articleUrl = $this->getArticleUrl($uuid);
$redirectUrl = append somehow the query params;
return new RedirectResponse($redirectUrl, 301);
}
I tried to use the generate method again but it didn't work as I supposed it already has the domain in it and it will duplicate it
$redirectUrl = $this->urlGenerator->generate($articleUrl, $queryParams, UrlGeneratorInterface::ABSOLUTE_URL);
or perhaps I could get only the path from $articleUrl and call the generate for the new path and that could work, but it didn't
public function articleController(Request $request, string $uuid)
{
$queryParams = $request->query->all();
$articleUrl = $this->getArticleUrl($uuid);
$parsed = parse_url($articleUrl);
$path = $parsed['path'];
if ($path) {
$redirectUrl = $this->urlGenerator->generate($path, $queryParams);
} else {
$redirectUrl = $articleUrl;
}
return new RedirectResponse($redirectUrl, 301);
}
You could use http_build_query
public function articleController(Request $request, string $uuid)
{
$queryParams = $request->query->all();
$articleUrl = $this->getArticleUrl($uuid);
$redirectUrl = $articleUrl . '?' . http_build_query($queryParams);
return new RedirectResponse($redirectUrl, 301);
}
More Info: https://www.php.net/manual/en/function.http-build-query.php

redirect to 404 page instead of Fatal error: Uncaught ArgumentCountError: Too few arguments to function

I made an MVC framework for training, and I get this error and I'm not sure what is wrong with my function.
when I open link like this :
http://mvctrav.com/posts/show/6 it show me the post but when deleting the id like this http://mvctrav.com/posts/show/ it shows me the error
My error looks like this:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Posts::show(), 0 passed in C:\xampp\htdocs\trav\app\libraries\Core.php on line 51 and exactly 1 expected in C:\xampp\htdocs\trav\app\controllers\Posts.php:124 Stack trace: #0 C:\xampp\htdocs\trav\app\libraries\Core.php(51): Posts->show() #1 C:\xampp\htdocs\trav\public\index.php(4): Core->__construct() #2 {main} thrown in C:\xampp\htdocs\trav\app\controllers\Posts.php on line 124
and my function is :
public function show($id)
{
$post = $this->postModel->getPostById($id);
$user = $this->userModel->getUserById($post->user_id);
$data = [
'post' => $post,
'user' => $user
];
$this->view('posts/show', $data);
}
this is my Core class:
<?php
class Core
{
protected $currentController = 'Pages';
protected $currentMethod = 'index';
protected $params = [];
public function __construct()
{
//print_r($this->getUrl());
$url = $this->getUrl();
// Look in controllers for first value
if (file_exists('../app/controllers/' . ucwords($url[0]) . '.php')) {
// If exists, set as controller
$this->currentController = ucwords($url[0]);
// Unset 0 Index
unset($url[0]);
}
// Require the controller
require_once '../app/controllers/' . $this->currentController . '.php';
// Instantiate controller class
$this->currentController = new $this->currentController;
// Check for second part of url
if (isset($url[1])) {
// Check to see if method exists in controller
if (method_exists($this->currentController, $url[1])) {
$this->currentMethod = $url[1];
// Unset 1 index
unset($url[1]);
}
}
// Get params
$this->params = $url ? array_values($url) : [];
// Call a callback with array of params
call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
}
public function getUrl()
{
$url = isset($_GET['url']) ? $_GET['url'] : "/";
$url = filter_var(trim($url, "/"), FILTER_SANITIZE_URL);
$url = explode('/', $url);
return $url;
}
}
my problem is: link http://mvctrav.com/posts/show to be not found or redirecting to specific page instead of showing the error
Thank you for trying to help!
I think you need to edit show() function to be like this:
public function show($id = null)
{
$post = $this->postModel->getPostById($id);
$user = $this->userModel->getUserById($post->user_id);
$data = [
'post' => $post,
'user' => $user
];
if ($user !== false && null !== $id) {
$this->view('posts/show', $data);
} else {
header('Location:'.'404.php');
}
}
1- this error means that you don't pass the parameter to the function you call it. id of the post in your case. you should explain your code in view page
2- for generating 404 pages is to use http_response_code:
<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();
die() is not strictly necessary, but it makes sure that you don't continue the normal execution.
for 2 you can see How can I create an error 404 in PHP?

Variable usable in Service

I am a beginner in php. I have a WadoService service and a StudiesRestController controller. I want to use controller data in the service.
public function getPatientAction(Request $request, $studyUID)
{
$studyRepository = new StudyRepository(
$this->get('nexus_db'),
$this->get('logger'),
$this->get('translator')
);
$study = $studyRepository->getStudy($studyUID);
if (!$study) {
throw new NotFoundHttpException("No study found with studyuid $studyUID");
}
$patientInfo = new RestResponse(
SerializerBuilder::create()
->build()
->serialize($study->getPatient(), 'json')
);
return $patientInfo;
}
Is this possible? I have tried to put this in the function getPatientAction()without result:
/* #var $wadoService WadoService */
$wadoService = $this->container->get(WadoService::SERVICE_NAME);
$wadoService = new RestResponse(
SerializerBuilder::create()
->build()
->serialize($study->getPatient(), 'json')
);
To pass a variable from your controller to your service, you do it it like that :
$wadoService = $this->container->get(WadoService::SERVICE_NAME)->yourServiceMethod($yourVari);

call a helper function in controller in codeigniter

I created a helper for visit hits and it contains a function which inserts some data in to the database:
hits_counter_helper.php :
function count_hits($options = array())
{
//Determine whether the user agent browsing your site is a web browser, a mobile device, or a robot.
if ($this->agent->is_browser())
{
$agent = $this->agent->browser() . ' ' . $this->agent->version() . ' - ' . $this->agent->platform();
}
elseif ($this->agent->is_robot())
{
$agent = $this->agent->robot();
}
elseif ($this->agent->is_mobile())
{
$agent = $this->agent->mobile();
}
else
{
$agent = 'Unidentified User Agent';
}
//Detect if the user is referred from another page
if ($this->agent->is_referral())
{
$referrer = $this->agent->referrer();
}
// correcting date time difference by adding 563 to it.
$date = date('Y-m-j H:i:s', strtotime(date('Y-m-j H:i:s')) + 563);
$data = array (
'page_Address' => current_url(),
'user_IP' => $this->input->ip_address(),
'user_Agent' => $agent,
'user_Referrer' => $referrer,
'hit_Date' => $date
);
$this->db->insert('counter', $data);
}
once I auto loaded the helper and called this function in my controller as:
My_controller.php:
public function index() {
count_hits();
//index code here
}
The problem is that I am getting a blank page and other codes does not run I think. What am I doing wrong?!
Add the following code to the beginning of your helper function:
//get main CodeIgniter object
$CI =& get_instance();
Replace all $this with $CI in your function.
and then load the helper function wherever you want in your controller like this:
count_hits();

YouTube API: Get full playlist

I'm trying to understand recursion :) Well, specifically fetching a full YouTube playlist using Google's PHP Client Library.
This is my function in my class called YTFunctions. It first gets called with a valid, authenticated YouTube_Service object and a playlistId. Then, it should theoretically call itself over and over again as long as the PlaylistItems response has a nextPageToken and then append that to its outputs which should contain all objects (videos) contained in the playlist. For some reason, it just return an empty array.
public static function getFullPlaylistByID($youtube, $playlistId, $pageToken) {
$params = array(
'maxResults' => 50,
'playlistId' => $playlistId,
);
if ($pageToken !== false) {
$params['pageToken'] = $pageToken;
}
$playlistResponse = $youtube->playlistItems->listPlaylistItems('snippet,contentDetails', $params);
error_log(count($playlistResponse['items']));
$playlistItems = $playlistResponse['items'];
if (isset($playlistResponse['nextPageToken'])) {
$playlistItems = array_merge($playlistItems, YTFunctions::getFullPlaylistByID($youtube,$playlistId, $playlistResponse['nextPageToken']));
} else {
}
return $playlistItems;
}
I am clearly missing something here, any help would be greatly appreciated.
Tobias Timpe
here my class that will get all playlistItems
<?php
class yt{
public $DEVELOPER_KEY = '{DEVELOPER_KEY}';
public $client;
public $youtube;
public function __construct(){
$this->client = new Google_Client();
$this->client->setDeveloperKey($this->DEVELOPER_KEY);
$this->youtube = new Google_YoutubeService($this->client);
}
public function getPlaylistItems($playlist, $maxResults, $nextPageToken = ''){
$params = array(
'playlistId' => $playlist,
'maxResults' => $maxResults,
);
// if $nextPageToken exist
if(!empty($nextPageToken)){
//insert $nextPageToken value into $params['pageToken']
$params['pageToken'] = $nextPageToken;
}
$youtubeFeed = $this->youtube->playlistItems->listPlaylistItems('id,snippet,contentDetails', $params);
// function for looping our feed and entry
$this->setFeed($youtubeFeed);
//check if nextPageToken are exist
if(!empty($youtubeFeed['nextPageToken'])){
$insert = $this->getPlaylistItems($playlist, $maxResults, $youtubeFeed['nextPageToken']);
// return to function if nextPageToken are exist
return $insert;
}
}
}
$yt = new yt();
?>
and than use our class
$yt->getPlaylistItems('PL0823049820348','25');

Categories