PHP Post Data Formatting - php

As per the Eventbrite API v3 documentation, the preferred way to submit the data is as JSON. I am attempting to update via ExtJS grid simple organizer data. The changes are not being processed.
The solution is in MODX and the updateFromGrid.class.php looks like this:
class UpdateOrganizerFromGridProcessor extends modProcessor {
public function initialize() {
$data = $this->getProperty('data');
if (empty($data)) return $this->modx->lexicon('invalid_data');
$data = $this->modx->fromJSON($data);
if (empty($data)) return $this->modx->lexicon('invalid_data');
$this->id = $data['id'];
$this->params = array ();
// build JSON content for form submission...cooking key names
$this->formData = array (
'organizer.name' => $data['name'],
'organizer.description.html' => $data['description'],
'organizer.logo.id' => $data['logo_id'],
);
$this->formJSON = $this->modx->toJSON($this->formData);
$this->args = array('id' => $this->id, 'params' => $this->params);
return parent::initialize();
}
public function process() {
// call to main class to save changes to the Eventbrite API
$this->mgr_client = new Ebents($this->modx);
$this->output = $this->mgr_client->postData('organizers', $this->args, $this->formJSON);
$response = json_decode(json_encode($this->output), true);
return $this->outputArray($response);
}
}
return 'UpdateOrganizerFromGridProcessor';
The json output from the above is:
{"organizer.name":"Joe Organizer","organizer.description":"Joe is the Uberest Organizer."}
And my post function is:
//send data to Eventbrite
function postData($method, $args, $JSONdata) {
error_log("JSON Payload : " . $JSONdata);
// Get the URI we need.
$uri = $this->build_uri($method, $args);
// Construct the full URL.
$request_url = $this->endpoint . $uri;
// This array is used to authenticate our request.
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n"
. "Accept: application/json\r\n",
'method' => 'POST',
'content' => $JSONdata,
'header' => "Authorization: Bearer " . $this->token
)
);
// Call the URL and get the data.
error_log("URL: " . $request_url);
error_log("Content: " . $options['http']['content']);
$resp = file_get_contents($request_url, false, stream_context_create($options));
// parse our response
if($resp){
$resp = json_decode( $resp );
if( isset( $resp->error ) && isset($resp->error->error_message) ){
error_log( $resp->error->error_message );
}
}
// Return it as arrays/objects.
return $resp;
}
function build_uri($method, $args) {
// Get variables from the $args.
extract($args);
// Get rid of the args array.
unset($args);
// Create an array of all the vars within this function scope.
// This should be at most 'method', 'id' and 'data'.
$vars = get_defined_vars();
unset($vars['params']);
// Put them together with a slash.
$uri = implode($vars, '/');
if (!empty($params)) {
return $uri ."?". http_build_query($params);
}
return $uri;
}
The post is working however there is no update to the data and the response back is the original data set. What am I missing here?

I figured it out. It was an issue with a missing slash right before the query string. I also removed the JSON data payload and am submitting as form encoded. The final class is below:
class UpdateOrganizerFromGridProcessor extends modProcessor {
public function initialize() {
$data = $this->getProperty('data');
if (empty($data)) return $this->modx->lexicon('invalid_data');
$data = $this->modx->fromJSON($data);
if (empty($data)) return $this->modx->lexicon('invalid_data');
$this->id = $data['id'];
$this->params = array (
'organizer.name' => $data['name'],
'organizer.description.html' => $data['description'],
'organizer.logo.id' => $data['logo_id'],
);
$this->args = array('id' => $this->id, 'data'=> '', 'params' => $this->params);
return parent::initialize();
}
public function process() {
// call to main class to save changes to the Eventbrite API
$this->mgr_client = new Ebents($this->modx);
$this->output = $this->mgr_client->postData('organizers', $this->args);
$response = json_decode(json_encode($this->output), true);
return $this->outputArray($response);
}
}
return 'UpdateOrganizerFromGridProcessor';

Related

Laravel returns 302 error when trying to send POST request to API route from Laravel Controller

A 302 error is returned when I'm trying to post to API Route, only in the second Post, using the function insereTelefone. When I'm using the Postman, it's working properly, so I think the problem is with Route, but I don't know what. I'm a newbie at the Laravel, so I'm learning how to implement things.
Here is the controller who calls the POST API:
class IndexClientes extends Controller
{
public function index()
{
$request = Request::create('/api/clientes', 'GET');
$response = Route::dispatch($request);
$clientes = json_decode($response->getContent(), true);
return view('index', compact('clientes'));
}
public function create()
{
return view('formulariocliente');
}
public function store(Request $request)
{
$nome = $request->nome;
$cpf = $request->cpf;
$email = $request->email;
$numerosTelefone = $request->telefone;
$tiposTelefone = $request->tipoTelefone;
$request = Request::create('/api/clientes', 'POST', array(
"nome" => $nome,
"cpf" => $cpf,
"email" => $email
));
$responseInicial = Route::dispatch($request);
$response = json_decode($responseInicial->getContent(), true);
$status = json_decode($responseInicial->status(), true);
if ($status !== 200) :
echo "ERRO";
die();
endif;
$idCliente = $response['id'];
if (!empty($numerosTelefone)) :
$i = 0;
foreach ($numerosTelefone as $numeroTelefone) :
$tipoTelefone = (int)$tiposTelefone[$i];
$numeroTelefone = (int)$numeroTelefone;
if (!empty($tipoTelefone) && !empty($numeroTelefone)) :
return self::insereTelefone($idCliente, $tipoTelefone, $numeroTelefone);
endif;
$i++;
endforeach;
endif;
}
public function insereTelefone($idCliente, $tipoTelefone, $numTelefone)
{
$array = array(
"cliente_id" => $idCliente,
"telefone_tipo_id" => $tipoTelefone,
"numero" => $tipoTelefone
);
$request = Request::create('api/telefones', 'POST', $array);
$responseInicial = Route::dispatch($request);
$response = json_decode($responseInicial->getContent(), true);
$status = json_decode($responseInicial->status(), true);
return $status;
}
}
TelefonesController.php
public function store(Request $request)
{
$request->validate(
[
'cliente_id' => 'required',
'telefone_tipo_id' => 'required',
'numero' => 'required|max:11'
]
);
}
api.php
Route::apiResource('telefones', \App\Http\Controllers\TelefonesController::class);
A 302 response usually means your request is being redirected by laravel.
If you are expecting a json response, you need to set the Accept: 'application/json' header along with your request just after the line:
$request = Request::create('api/telefones', 'POST', $array );
$request->headers->set('Accept', 'application/json');
the first
Route::dispatch
was redirecting the page, when I'm was trying to run the second Route::dispatch Laravel returns 302, to solve this I'm using the
app()->handle()
in the function insereTelefone to back to handle the request.
public function insereTelefone($idCliente, $tipoTelefone, $numTelefone) {
$array = array(
"cliente_id" => $idCliente,
"telefone_tipo_id" => $tipoTelefone,
"numero" => $numTelefone
);
$request_telefone = Request::create('api/telefones', 'POST', $array );
$responseInicial = app()->handle($request_telefone);
$status = json_decode($responseInicial->status(),true);
return $status;
}

request body logic with JSON raw data

I am trying to send raw JSON data via Postman as required parameter.
My function works fine except that part. When I paste json data into postman it throws:
A non-empty request body is required.
I think there is a little modification needed but I can't find solution.
My code:
public function callApi(BaseRequest $request)
{
$token = $this->getTokenForRequest($request);
$method = $request->getMethod();
$client = new Client(['base_uri' => 'https://api-tst.testing.app/test/']);
$headers = [
'Authorization' => 'Bearer ' . $token,
'Ocp-Apim-Subscription-Key' => '1111112222',
'Content-Type' => 'application/json',
];
$request->getRequestParams();
$res = $client->request($method, $request->getUrl(), [
'headers' => $headers
]);
$res->getStatusCode();
$response = $res->getBody()->getContents();
return $response;
}
and form my BaseRequest:
public function getUrl()
{
return null;
}
public function getMethod()
{
return null;
}
/**
* #return array
*/
public function getRequestParams()
{
$data = [];
return $data;
}
And I am calling it in controller like:
public function testAll(Request $request)
{
$data = (string)$request->getContent();
$data = json_decode($data, true);
$response = $this->container->get('app')->myFunction($data);
dump($response);die;
}
Found it!
$res = $client->request($method, $request->getUrl(), [
'headers' => $headers,
'json' => $request->getRequestParams()
]);

Codeigniter - sending data via URL and getting response

what i am trying to do is send some data to a url and get a response like "success" that indicates that data is received in codeigniter. Do i need to configure an api in the codeigniter to test that. I tried the following code but not getting the expected result. To mention I am pretty new in codeigniter and php.
controller xmlPost.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class XmlPost extends CI_controller
{
public function index()
{
$this->load->model('xml_model','message');
$this->message->source = "14045" ;
$this->message->dst = "08887654657";
$this->message->msg = "Hi, this is test";
$this->message->url = 'http://localhost/codeigniter1/index.php/receive';
$data = $this->message->Send();
echo $data;
}
}
?>
and the model is xml_model.php
<?php
Class Xml_model extends CI_Model {
var $source; //Source address
var $dst; //Destination
var $msg; // Message
var $url;
var $api_url;
function __construct() {
parent::__construct();
}
function Send(){
$this->api_url = 'http://localhost/codeigniter1/index.php/receive';
$params = $this->source.'&destinationaddr='.$this->dst.'&shortmessage='.urlencode($this->msg).' '.urlencode($this->url).'';
$post_data = array(
"sourceaddr" => $params,
);
$stream_options = array(
'http' => array(
'method' => 'POST',
),
);
$context = stream_context_create($stream_options);
$response = file_get_contents($this->api_url, null, $context);
return $response;
}
}
?>
After url encoing Space[ ] can encoded as + sign.you have to manually replace as %20,then after execute your URL.
public function sendSMS($mobile,$code)
{
$stream_options = array(
'http' => array(
'method' => 'GET',
),
);
$context = stream_context_create($stream_options);
$url="http://api.smsbrain.in/1.2/appsms/send.php?user=satish123&passwd=123456&senderId=SATISH&recipients=".$mobile."&message=Your%20Verification%20code%20for%20facebook%20is%20".$code.".";
//echo "URL".$url;
$response = file_get_contents($url, null, $context);
echo print_r($response);
}

why coinbase callback url not working?

i have the below code for button creation.
public function createButton($name, $price, $currency, $custom=null, $options=array(),$callback)
{
// $callback=$this->generateReceiveAddress("http://www.tgigo.com");
// print_r($callback);exit;
$params = array(
"name" => $name,
"price_string" => $price,
"price_currency_iso" => $currency,
"callback_url"=>"http://www.tgigo.com"
);
if($custom !== null) {
$params['custom'] = $custom;
}
foreach($options as $option => $value) {
$params[$option] = $value;
}
return $this->createButtonWithOptions($params);
}
public function createButtonWithOptions($options=array())
{
$response = $this->post("buttons", array( "button" => $options ));
if(!$response->success) {
return $response;
}
$returnValue = new stdClass();
$returnValue->button = $response->button;
$returnValue->embedHtml = "<div class=\"coinbase-button\" data-code=\"" . $response->button->code . "\"></div><script src=\"https://coinbase.com/assets/button.js\" type=\"text/javascript\"></script>";
$returnValue->success = true;
return $returnValue;
}
and i have the below response for above code.
{"success":true,"button":{"code":"675cda22e31b314db557f0538f8ad27e","type":"buy_now","style":"buy_now_large","text":"Pay With Bitcoin","name":"Your Order #1234","description":"1 widget at $100","custom":"my custom tracking code for this order","callback_url":"http://www.tgigo.com","price":{"cents":100000,"currency_iso":"BTC"}}}
using this code payment process completed,but not redirected to the call back url.
any one please help me.
Thanks in advance :)
The callback_url parameter is for a callback that receives a POST request behind the scenes when payment is complete. The user's browser is not redirected there. You probably want success_url.
https://coinbase.com/api/doc/1.0/buttons/create.html

CakePHP change DATABASE_CONFIG variables, based on user input for custom datasource

I am looking for a way to access and change the DATABASE_CONFIG variables, based on user input. Using CakePHP I created a custom datasource, based on the one provided in the docs, to access an external API. The API returns a JSON string containing the 12 most recent objects. I need to be able to change the page number in the API request to get the next 12 results, as well as accept a free text query entered by the user.
app/Config/Database.php
class DATABASE_CONFIG {
public $behance = array(
'datasource' => 'BehanceDatasource',
'api_key' => '123456789',
'page' => '1',
'text_query' => 'foo'
);
}
app/Model/Datasource/BehanceDataSource.php
App::uses('HttpSocket', 'Network/Http');
class BehanceDatasource extends DataSource {
public $description = 'Beehance datasource';
public $config = array(
'api_key' => '',
'page' => '',
'text_query' => ''
);
public function __construct($config) {
parent::__construct($config);
$this->Http = new HttpSocket();
}
public function listSources($data = null) {
return null;
}
public function describe($model) {
return $this->_schema;
}
public function calculate(Model $model, $func, $params = array()) {
return 'COUNT';
}
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] === 'COUNT') {
return array(array(array('count' => 1)));
}
$queryData['conditions']['api_key'] = $this->config['api_key'];
$queryData['conditions']['page'] = $this->config['page'];
$queryData['conditions']['page'] = $this->config['text_query'];
$json = $this->Http->get('http://www.behance.net/v2/projects', $queryData['conditions']);
$res = json_decode($json, true);
if (is_null($res)) {
$error = json_last_error();
throw new CakeException($error);
}
return array($model->alias => $res);
}
}
Is there anyway to access and change the $behance array, or is there another way to go about accessing an external API with cakePHP that I am totally missing?

Categories