I a trying to validate that the customer is above 20 thru Klarna Checkout.
They have a built in function for validating, see here https://developers.klarna.com/en/se/kco-v2/checkout/use-cases#validate-checkout-order
The checkout.php page looks like this
Accept: application/vnd.klarna.checkout.aggregated-order-v2+json
Authorization: Klarna pwhcueUff0MmwLShJiBE9JHA==
Content-Type: application/vnd.klarna.checkout.aggregated-order-v2+json
{
"purchase_country": "se",
"purchase_currency": "sek",
"locale": "sv-se",
"cart": {
"items": [
{
"reference": "123456789",
"name": "Klarna t-shirt",
"quantity": 2,
"unit_price": 12300,
"discount": 1000,
"tax_rate": 2500
},
{
"type": "shipping_fee",
"reference": "SHIPPING",
"name": "Shipping fee",
"quantity": 1,
"unit_price": 4900,
"tax_rate": 2500
}
]
},
"merchant": {
"id": "0",
"terms_uri": "http://example.com/terms.php",
"checkout_uri": "https://example.com/checkout.php",
"confirmation_uri": "https://example.com/thankyou.php?sid=123&klarna_order={checkout.order.uri}",
"push_uri": "https://example.com/push.php?sid=123&klarna_order={checkout.order.uri}",
"validation_uri": "https://example.com/klarna_validation.php"
}
}
When a customer cliks "buy now" the klarna_validation.php script runs, and sends a return to Klarna with a HTTP status 202 OK or 303 SEE OTHER.
Below are my klarna_validation.php
<?php
$pno = $_POST['customer']['date_of_birth'];
$birthdate = new DateTime("$pno");
$today = new DateTime();
$interval = $today->diff($birthdate);
$interval2 = $interval->format('%y');
if($interval2 <= "20"){
header("Location: https://example.com/too_young.php?$pno", true, 303);
exit;
} else {
http_response_code(200);
}
?>
According to Klarna: POST request will be sent to the merchant.validation_uri. The body of the request will contain the current order information. The structure of the order information is identical to the result of fetching the order, as you saw in render the checkout.
The thing is that i don't get any data with
$_POST['customer']['date_of_birth']; it's empty.
To validate that this $_POST['customer']['date_of_birth']; is empty i have included it in the URL of the too_young.php page, like this (too_young.php?$pno). When landing on too_young.php the $pno is empty! (The urls looks like this too_young.php?)
Does anyone have an idea of what i am doing wrong?
Finally we got it to work!
We just had to add this code to the validate file:
$post_data = json_decode(file_get_contents('php://input'), true);
Like this:
<?php
$post_data = json_decode(file_get_contents('php://input'), true);
$pno = $post_data['customer']['date_of_birth'];
$birthdate = new DateTime("$pno");
$today = new DateTime();
$interval = $today->diff($birthdate);
$interval2 = $interval->format('%y');
if($interval2 < "60"){
header("Location: https://example.com/too_young.php?$pno&$interval2", true, 303);
exit;
} else {
http_response_code(200);
}
?>
Related
Want to send the json data to my url, when the json is received i receive all the json data on the url and not the data from 'resolvedQuery'
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true);
$results = $update['result']['resolvedQuery'];
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data" . urlencode(json_encode($update));
Json Data
{
"id": "4ed272a3-b9a4-4f18-a67e-10e12e4f4149",
"timestamp": "2017-12-10T10:07:54.282Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "turn livingroom light on",
"action": "",
"actionIncomplete": false,
"parameters": {
"power-toggle": "on",
"room": "livingroom"
},
"contexts": [],
"metadata": {
"intentId": "19764ecc-715c-4b25-960f-9845f2aef1f9",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 503,
"intentName": "lights"
},
"fulfillment": {
"speech": "Ok, Turning livingroom light on",
"messages": [
{
"type": 0,
"speech": "Ok, Turning livingroom light on"
}
]
},
"score": 1
},
"status": {
"code": 206,
"errorType": "partial_content",
"errorDetails": "Webhook call failed. Error: Webhook response was empty.",
"webhookTimedOut": false
},
"sessionId": "395d3517-05da-42ac-9037-dadac519ab0b"
}
How do i get data from 'resolvedQuery' and send it to my URL
In the code you provided, you have the following line of code
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data"
. urlencode(json_encode($update));
You are appending to the URL parameter message the results of json_decode($update_response, true). $update_response contains all the decoded JSON data posted by the HTTP request which is not what you want.
I believe what you want is a new parameter called resolved-query to be set to the results of json_decode($result, true).
Try chaninging your $url variable to the following:
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data&resolved-query="
. urlencode(json_encode($result));
URL will be set to the following string:
https://autoremotejoaomgcd.appspot.com/sendmessage?
key=APA91bEq&
message=Data&
resolved-query=turn+livingroom+light+on
Using smsgateway.me to send a message I use the default code with my own variables which are working fine. However, sometimes the SMS does not send and I would like to store the SMS in the database if failed.
To do so I think I need a value from the $result array, but I dont know how to start. I tried many different codes without any result.
Can anywone please tell me how to get an if sent ok -> do something / else do something else based on the code and variables below?
Thanks a lot!
Documentation here
Here is the default code (with default variables) that sends a message:
<?php
include "smsGateway.php";
$smsGateway = new SmsGateway('demo#smsgateway.me', 'password');
$deviceID = 1;
$number = '+44771232343';
$message = 'Hello World!';
$options = [
'send_at' => strtotime('+10 minutes'), // Send the message in 10 minutes
'expires_at' => strtotime('+1 hour') // Cancel the message in 1 hour if the message is not yet sent
];
//Please note options is no required and can be left out
$result = $smsGateway->sendMessageToNumber($number, $message, $deviceID, $options);
?>
Success content:
{
"success": true,
"result": {
"success": [
{
"id": "308",
"device_id": "4",
"message": "hello world!",
"status": "pending",
"send_at": "1414624856",
"queued_at": "0",
"sent_at": "0",
"delivered_at": "0",
"expires_at": "1414634856",
"canceled_at": "0",
"failed_at": "0",
"received_at": "0",
"error": "None",
"created_at": "1414624856",
"contact": {
"id": "14",
"name": "Phyllis Turner",
"number": "+447791064713"
}
}
],
"fails": [
]
}
}
error content:
{
"success": true,
"result": {
"success": [
],
"fails": [
"number": "+44771232343"
"message": "hello world!",
"device": 1
"errors": {
"device": ["The selected device is invalid"],
}
]
}
}
This did the trick if failed:
if (isset($result['response']['result']['fails'][0]['number']) === TRUE) {
echo 'failed';
else{
echo 'success';
}
this works on success:
if(isset($result['response']['result']['success'][0]['id']) === TRUE){
echo 'success';
}else{
echo 'failed';
}
Thanks Michael, your reply helped me to change it a bit and figure it out!
As Facebook changed their API and deprecated the old one, I need to get data (likes count, share count, comment count) about single pages.
I figured out how to get data over Facebook graph (example link):
https://graph.facebook.com/?fields=og_object{likes.limit(0).summary(true)},share&ids=http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9
But now I don't know how to echo single data (likes count) in php. I tried with json, but had no sucsess:
$json = file_get_contents($xml);
$json_output = json_decode($json);
Any suggestions how to make this work?
The API Explorer adds the Access Token automatically, but you have to add it manually in your URL:
https://graph.facebook.com/?fields=og_object{likes.limit(0).summary(true)},share&ids=http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9&access_token=xxx
Result:
{
"http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9": {
"og_object": {
"likes": {
"data": [
],
"summary": {
"total_count": 0,
"can_like": true,
"has_liked": false
}
},
"id": "949055545223224"
},
"share": {
"comment_count": 0,
"share_count": 346
},
"id": "http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9"
}
}
The results of json_decode() are Objects.
So you can easily browse through like this:
<?php
$url = 'https://graph.facebook.com/?fields=og_object{likes.limit(0).summary(true)},share&ids=http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9';
$json = file_get_contents($url);
$json_output = json_decode($json);
foreach( $json_output as $site=>$data ){
echo $site."\n";
echo $data->og_object->likes->summary->total_count;
}
?>
I got a question about Google Cloud Messaging...
I send GCM to Google for 3 Registration IDs, then Google replies that 2 of the Registration IDs has been sent successfully and one not, because the Registration ID was wrong!
But it doesn't tell me which Registration ID has not been sent...
Now here's my question:
how can I parse the Google GCM response to get that which Registration ID has not been sent? Does Google has an API or something so that I can give it "multicat_id" and it tells me which Registration ID had a problem?
Any help would be so much appreciated, I'm just so confused :)
It's based on the order :
Suppose you send this :
{ "collapse_key": "score_update",
"time_to_live": 108,
"delay_while_idle": true,
"data": {
"score": "4x8",
"time": "15:16.2342"
},
"registration_ids":["4", "8", "15", "16", "23", "42"]
}
And get this response from Google :
{ "multicast_id": 216,
"success": 3,
"failure": 3,
"canonical_ids": 1,
"results": [
{ "message_id": "1:0408" },
{ "error": "Unavailable" },
{ "error": "InvalidRegistration" },
{ "message_id": "1:1516" },
{ "message_id": "1:2342", "registration_id": "32" },
{ "error": "NotRegistered"}
]
}
This means that the 3rd registration ID that you sent (15) is invalid and the 6th (42) is not registered. Both should be removed from your DB.
Here's how I did it:
$gcm_result = $gcm->send_notification($registration_ids, $message);
$jsonArray = json_decode($gcm_result);
if(!empty($jsonArray->results)){
$remove_ids = array();
for($i=0; $i<count($jsonArray->results);$i++){
if(isset($jsonArray->results[$i]->error)){
if($jsonArray->results[$i]->error == "NotRegistered"){
$remove_ids[$i] = "'".$registration_ids[$i]."'";
}
}
}
if(!empty($remove_ids)){
$remove_ids_string = implode(', ',$remove_ids);
include_once SCRIPTS.'gcm_server_php/db_functions.php';
$dbf = new DB_Functions();
$res = $dbf->deleteUsers($remove_ids_string);
echo count($remove_ids)." users have unregistered from notifications since the last one was sent out.";
}
}
Based on what I read here:
http://developer.android.com/google/gcm/http.html#error_codes
http://developer.android.com/google/gcm/server-ref.html#error-codes
I've developed as follows (not tested yet):
$result = $gcm->send_notification($registration_ids, $message);
$jsonArray = json_decode($result);
if($jsonArray->canonical_ids != 0 || $jsonArray->failure != 0){
if(!empty($jsonArray->results))
{
for($i = 0 ; $i<count($jsonArray->results) ; $i++){
$result = $jsonArray->results[$i];
if(isset($result->message_id) && isset($result->registration_id))
{
// You should replace the original ID with the new value (canonical ID) in your server database
}
else
{
if(isset($result->error))
{
switch ($result->error)
{
case "NotRegistered":
case "InvalidRegistration":
// You should remove the registration ID from your server database
break;
case "Unavailable":
case "InternalServerError":
// You could retry to send it late in another request.
break;
case "MissingRegistration":
// Check that the request contains a registration ID
break;
case "InvalidPackageName":
// Make sure the message was addressed to a registration ID whose package name matches the value passed in the request.
break;
case "MismatchSenderId":
// Invalid SENDER_ID
break;
case "MessageTooBig":
// Check that the total size of the payload data included in a message does not exceed 4096 bytes
break;
case "InvalidDataKey":
// Check that the payload data does not contain a key that is used internally by GCM.
break;
case "InvalidTtl":
// Check that the value used in time_to_live is an integer representing a duration in seconds between 0 and 2,419,200.
break;
case "DeviceMessageRateExceed":
// Reduce the number of messages sent to this device
break;
}
}
}
}
}
}
Here is a link to the demo: http://davidwalsh.name/xbox-api
I created a php file with the following content..
<?php
// Settings
$gamertag = 'RyanFabbro';
$profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamertag.'.json';
// Get information about me
$info = file_get_contents($profileUrl);
// To JSON
$json = json_decode($info);
$user = $json->user;
?>
Here is what its supposed to look like when i load the file (except with my gamertag data)
{
"status": {
"is_valid": "yes",
"is_cheater": "no",
"tier": "gold"
},
"profile": {
"gamertag": "dwalsh83",
"gamerscore": 300,
"reputation": 20,
"gender": "male",
"motto": "Watch your head.",
"name": "David Walsh",
"location": "Madison, WI, US",
"bio": "There is, and only can be, Call of Duty.",
"url": "http:\/\/live.xbox.com\/en-US\/Profile?gamertag=dwalsh83",
"avatar_tile": "http:\/\/image.xboxlive.com\/global\/t.fffe07d1\/tile\/0\/2000b",
"avatar_small": "http:\/\/avatar.xboxlive.com\/avatar\/dwalsh83\/avatarpic-s.png",
"avatar_large": "http:\/\/avatar.xboxlive.com\/avatar\/dwalsh83\/avatarpic-l.png",
"avatar_body": "http:\/\/avatar.xboxlive.com\/avatar\/dwalsh83\/avatar-body.png",
"launch_team_xbl": "no",
"launch_team_nxe": "no",
"launch_team_kin": "no"
}
}
But it is not displaying anything, what am i doing wrong?
When I go to http://www.xboxleaders.com/api/profile/ryanfabbro.json, it displays fine.
Uodate*
i tryd doing this in a php file
<?php
// Settings
$gamertag = 'RyanFabbro';
$profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamertag.'.json';
// Get information about me
$info = file_get_contents($profileUrl);
// To JSON
$json = json_decode($info);
$user = $json->user;
$user = $json->profile;
$user = $json->data;
$profile = $json->data;
?>
<img src="<?php echo $profile->avatar_body; ?>" alt="<?php echo $profile->gamertag; ?>" class="avatar" />
this resulted in the page still being blank so when i viewed the source all it returned was
<img src="" alt="" class="avatar" />
update 2 #ae14 & 2g
i also tried (all in 1 php file)
<?php
// Settings
$gamertag = 'RyanFabbro';
$profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamertag.'.json';
// Get information about me
$info = file_get_contents($profileUrl);
// To JSON
$json = json_decode($info);
$user = $json->data;
?>
<?php echo $user->name ?>
which still resulted in a blank page, is that what you were meaning i should do? i also tried this same way with 2g suggestion to no avail
It looks like you need to use
$user = $json->Data
to get the user information
This is my PHP file :
<?php
// Settings
$gamertag = urlencode('yourgamertagwithspaceetcetc..');
$profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamertag;
// Get information about me
$info = file_get_contents($profileUrl);
echo $info;
// To JSON
$json = json_decode($info);
$user = $json->Data;
echo $user->Gamertag;
?>
I've to use urlEncode beacause my gamertag had a spaces inside. I suggest you to test the final url on the browser before start the php file.
For test use $user->Gamertag because Name's property it's always blank.. I don't know why.
This is JSON Data returned from the service
"Data": {
"Tier": "gold",
"IsValid": 1,
"IsCheater": 0,
"IsOnline": 0,
"OnlineStatus": "Last seen 11\/10\/2012 playing Modern Warfare® 3",
"XBLLaunchTeam": 0,
"NXELaunchTeam": 0,
"KinectLaunchTeam": 0,
"AvatarTile": "https:\/\/avatar-ssl.xboxlive.com\/avatar\/xxxxxxxx\/avatarpic-l.png",
"AvatarSmall": "http:\/\/avatar.xboxlive.com\/avatar\/xxxxxx\/avatarpic-s.png",
"AvatarLarge": "http:\/\/avatar.xboxlive.com\/avatar\/xxxxxx\/avatarpic-l.png",
"AvatarBody": "http:\/\/avatar.xboxlive.com\/avatar\/xxxxxxx\/avatar-body.png",
"Gamertag": "xxxxxxxxxxxxxxxxx",
"GamerScore": 4165,
"Reputation": 20,
"Name": "",
"Motto": "",
"Location": "",
"Bio": ""
},
"Stat": "ok",
"In": 2.273,
"Authed": "false",
"AuthedAs": null
You can access using the same method for the Gamertag... simpy call
$user->AvatarSmall
I don't had php installed on my machine so first I've downloaded the PHP 5.4.8 for Windows and I've used the Built-in web server of this release Here more info.
Hope can help you