Creating a bolt extension and trying to access request variables. I have set up an endpoint GET /api/session, which for now should just return the request:
public function initialize()
{
$this->app->get("/api/session", array($this, 'getSession'))
->bind('getSession');
}
public function getSession(Request $request)
{
$response = $this->app->json(array('request' => $request));
return $response;
}
But the response is:
"request": {
"attributes": { },
"request": { },
"query": { },
"server": { },
"files": { },
"cookies": { },
"headers": { }
}
There were headers sent, and I've tested it with queries too, but nothing is returned in the response. How do I get the full response? Full code is available at: https://github.com/babaggeii/bolt-extension-restapi
Related
I am trying to populate a already built php database using axios requests, however i keep receiving 422 error and I don't understand what I am missing. Could you please help me :)
This is the error that i get:
xhr.js:177 POST URL/data 422 (Unprocessable Entity)
This is the Post request schema of the DB:
"post": {
"summary": "Post new data row",
"description": "Post new data row",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "string",
"example": "{\"test\":1}"
},
"type": {
"type": "string",
"example": "1"
},
"status": {
"type": "integer",
"example": 1
}
},
"required": [
"data",
"type"
]
}
}
}
},
"responses" :{
"422": {
"description": "Error",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": "Invalid input"
}
This is my code,
I have several switch cases and they should all work in the same manner:
case "rezervariContact" : {
const {type, titlu, description, phone, email} = this.state;
const contactData = {
type: this.state.type,
data:{
type,
data :{
titlu, description, phone, email
}
},
status:true
}
data = {...contactData};
}
}
await axios({
method: "post",
headers: { "Content-Type": "application/json",
'Accept': '*/*' },
body:data,
url : 'http://xxxxxxxxx.ro/data'
})
.then(function (response) {
console.log("RespResolved::",response.config.params);
})
.catch(function (response) {
console.log("catchErrResp::",response);
});
}
Please if you can spot something let me know.
422 probably means your inputted data is invalid.
The reason for this depends on the server. You could try referring to any documentation for the API/server you are trying to reach.
Check document on http://xxxxxxxxxx.ro/data! It means your post data is valid but server can not hand it correctly!
I've been trying to finish my server side implementation of the PayPal Smart Button and got stuck with capturing the transaction. I'm using a Sandbox account. I'm not sure if the problem is the order ID.
The response I get when trying to capture a transaction:
Fatal error: Uncaught PayPalHttp\HttpException:
{"name":"RESOURCE_NOT_FOUND",
"details[{"field":"order_id",
"value":"$orderId",
"location":"path",
"issue":"INVALID_RESOURCE_ID",
"description":"Specified resource ID does not exist. Please check the resource ID and try again."}],
"message":"The specified resource does not exist.",
"debug_id":"df5cdbddfc1ea",
"links":[{"href":"https://developer.paypal.com/docs/api/orders/v2/#error-INVALID_RESOURCE_ID",
"rel":"information_link","method":"GET"}]} in /usr/local/ampps/www/shop-files/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php:215
Stack trace: #0 /usr/local/ampps/www/shop-files/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php(100): PayPalHttp\HttpClient->parseResponse(Object(PayPalHttp\Curl))
#1 /usr/local/ampps/www/shop-files/capture-transaction.php(29): PayPalHttp\HttpClient->execute(Object(PayPalCheckoutSdk\Orders\OrdersCaptureRequest))
#2 /usr/local/ampps/www/shop-files/capture-transaction.php(62): Sample\CaptureIntentExamples\CaptureOrder::captureOrder('$orderId', in /usr/local/ampps/www/shop-files/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php on line 215
The response I get when creating a transaction:
{
"id": "1XB529992P492602W",
"intent": "CAPTURE",
"status": "CREATED",
"purchase_units": [
{
"reference_id": "default",
"amount": {
"currency_code": "GBP",
"value": "12.00"
},
"payee": {
"email_address": "sb-lxq8v1263761#business.example.com",
"merchant_id": "SUHPR7WSYJPJQ"
}
}
],
"create_time": "2020-10-14T08:36:00Z",
"links": [
{
"href": "https://api.sandbox.paypal.com/v2/checkout/orders/1XB529992P492602W",
"rel": "self",
"method": "GET"
},
{
"href": "https://www.sandbox.paypal.com/checkoutnow?token=1XB529992P492602W",
"rel": "approve",
"method": "GET"
},
{
"href": "https://api.sandbox.paypal.com/v2/checkout/orders/1XB529992P492602W",
"rel": "update",
"method": "PATCH"
},
{
"href": "https://api.sandbox.paypal.com/v2/checkout/orders/1XB529992P492602W/capture",
"rel": "capture",
"method": "POST"
}
]
}
My php code for creating a transaction:
<?php
namespace Sample\CaptureIntentExamples;
session_start();
require __DIR__ . '/vendor/autoload.php';
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
require 'paypal-client.php';
class CreateOrder {
public static function createOrder() {
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = self::buildRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
echo json_encode($response->result, JSON_PRETTY_PRINT);
return $response;
}
private static function buildRequestBody() {
return array(
'intent'=>'CAPTURE',
'application_context'=>
array(
'return_url'=>'https://localhost/basket.php',
'cancel_url'=>'https://localhost/basket.php'
),
'purchase_units'=>
array(
0=>
array(
'amount'=>
array(
'currency_code'=>'GBP',
'value'=>$_SESSION['total']
)
)
)
);
}
}
if (!count(debug_backtrace()))
{
CreateOrder::createOrder(true);
}
?>
Code for capturing a transaction:
<?php
namespace Sample\CaptureIntentExamples;
require __DIR__ . '/vendor/autoload.php';
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
require 'paypal-client.php';
class CaptureOrder
{
public static function captureOrder($orderId)
{
$request = new OrdersCaptureRequest($orderId);
$client = PayPalClient::client();
$response = $client->execute($request);
echo json_encode($response->result, JSON_PRETTY_PRINT);
return $response;
}
}
if (!count(debug_backtrace()))
{
CaptureOrder::captureOrder('$orderId', true);
}
?>
JavaScript:
createOrder: function(data) {
return fetch('/shop-files/create-order.php', {
method: 'post',
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
onShippingChange: function(data, actions) {
if (data.shipping_address.country_code !== "GB") {
return actions.reject();
}
return actions.resolve();
},
onApprove: function(data) {
return fetch('/shop-files/capture-transaction.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
}).then(function(res) {
return res.json();
}).then(function(orderData) {
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart();
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
if (errorDetail.description) msg += '\n\n' + errorDetail.description;
if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
return alert(msg);
}
alert('Transaction completed by ' + orderData.payer.name.given_name);
});
}
}).render('#paypal-button-container');
This is your problem line:
CaptureOrder::captureOrder('$orderId', true);
You are literally sending the text string inside the single quotes: '$orderId' to PayPal. The $ and those 7 letters are going to PayPal. You are not sending the contents of your $orderId variable.
Get rid of your string quotes:
CaptureOrder::captureOrder($orderId, true);
By the way, a detail about PHP (and incidentally, shell languages like bash) you may not be aware of:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
ref: https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing
Basically, double quotes and single quotes behave differently in this respect.
This is what I added to my code for capturing a transaction to get the order's ID, right below require 'paypal-client.php';:
// Get JSON row data from the request
$json = file_get_contents('php://input');
// Convert JSON string into array
$data = json_decode($json, true);
// Get the value of the key 'orderID'
$orderId = $data['orderID'];
I'm not sure if the comments explain exactly what is happening, so any correction would be most welcome.
Also the JavaScript code is a bit different with this:
body: JSON.stringify({
orderID: data.orderID
})
added just below
headers: {
'content-type': 'application/json'
},
It's working now. Many thanks Preston PHX for pointing me in the right direction again.
Using php, how can I fetch specific data from dialogflow fulfillment JSON request and store the data into a php variable?
Here is the JSON response I 'm getting from my dialogflow agent
{
"responseId": "e9106589-2a41-47c4-bdde-8f3cee8f40da",
"queryResult": {
"queryText": "switch on cfl",
"action": "input.switchoncfl",
"parameters": {
"makeRequest": "cfl_on"
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"platform": "ACTIONS_ON_GOOGLE",
"simpleResponses": {
"simpleResponses": [
{
"textToSpeech": "Sure. Turning CFL on... Anything else can I help you with?",
"displayText": "Sure. Turning CFL on..."
}
]
}
}
],
"intent": {
"name": "projects/smarthome-cf277/agent/intents/5be27f38-105d-4854-b62d-ec3a6de80cc7",
"displayName": "1.1-Switch_on_CFL"
},
"intentDetectionConfidence": 1,
"languageCode": "en"
},
"originalDetectIntentRequest": {
"payload": {}
},
"session": "projects/smarthome-cf277/agent/sessions/ca0261aa-913f-96f1-b5aa-7755637d5ab7"
}
And here is my php code
<?php
header("Content-Type: application/json");
ob_start();
$content = json_decode(file_get_contents('php://input'),true);
$action = $content['parameters']['makeRequest'];
ob_end_clean();
?>
I want to store cfl_on value to $action variable. How can I do that? this php code does not work.
You just missed out the "queryResult" layer of the object.
$action = $content['queryResult']['parameters']['makeRequest'];
ORIGINAL REQUEST: I'm trying to implement the push notifications following the documentation: https://developers.google.com/actions/assistant/updates/notifications
I'm using Dialogflow with webhooks (in PHP) and the documentation is giving example in nodeJS
Right now, i'm blocked because of the Update permission, here's my Webhook response :
{
"source": "webhook",
"payload": {
"google": {
"expectUserResponse": true,
"systemIntent": {
"intent": "actions.intent.PERMISSION",
"data": {
"#type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
"permissions": [
"UPDATE"
]
},
"updatePermission": {
"intent": "notification.simple.text"
}
}
}
}
}
When I do the simulation, asks me a permission for a push, but not for the intent I specified.
I'm quiet sure that the problem is the updatePermission, something must be wrong with that:
Is it the field name?
In intent, i put the intent name that i filled in dialogflow, maybe do i have to an use action? Is it in the good format ?
If someone can help me or just give me an example of a clean response for an update permission.
Thanks!
Solution
I just found why, my json wasn't good, the updatePermissionValueSpec must be into data object.
{
"source": "webhook",
"payload": {
"google": {
"expectUserResponse": true,
"systemIntent": {
"intent": "actions.intent.PERMISSION",
"data": {
"#type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
"permissions": [
"UPDATE"
],
"updatePermissionValueSpec": {
"intent": "notification_simple_text"
}
}
}
}
}
}
I believe updatePermission should be named updatePermissionValueSpec.
Example response:
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "PLACEHOLDER"
}
}
]
},
"systemIntent": {
"intent": "actions.intent.PERMISSION",
"data": {
"#type": "type.googleapis.com/google.actions.v2.PermissionValueSpec",
"permissions": [
"UPDATE"
],
"updatePermissionValueSpec": {
"intent": "intent_name"
}
}
}
}
}
All,
I have an AJAX request, which makes a JSON request to a server, to get the sync status. The JSON Request and responses are as under: I want to display a JQuery UI progressbar and update the progressbar status, as per the percentage returned in the getStatus JSON response. If the status is "insync", then the progressbar should not appear and a message should be displayed instead. Ex: "Server is in Sync". How can I do this?
//JSON Request to getStatus
{
"header": {
"type": "request"
},
"payload": [
{
"data": null,
"header": {
"action": "load",
}
}
]
}
//JSON Response of getStatus (When status not 100%)
{
"header": {
"type": "response",
"result": 400
},
"payload": [
{
"header": {
"result": 400
},
"data": {
"status": "pending",
"percent": 20
}
}
]
}
//JSON Response of getStatus (When percent is 100%)
{
"header": {
"type": "response",
"result": 400
},
"payload": [
{
"header": {
"result": 400
},
"data": {
"status": "insync"
}
}
]
}
Assuming you want your progress bar/message to be placed in a div named "loadingDiv":
$(document).ready(function() {
var myLoadingDiv = $("#loadingDiv");
myLoadingDiv.progressbar({disabled:true});
$.getJSON("getStatus.php", function(data) {
if (data.payload.data.status == "insync") {
myLoadingDiv.progressbar("disable");
myLoadingDiv.html("Server is in Sync");
}
else if (data.payload.data.status == "pending") {
myLoadingDiv.progressbar("enable");
myLoadingDiv.progressbar("value", data.payload.data.percent);
}
else {
//something else if there are any other status'
}
});
});