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!
Related
I'm trying to make an application that will use a JSON input. Below is some code that shows the problem when run. The problem being a syntax error; unexpected integer from the "etag" line ("$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",). When I remove the etag line it runs fine but otherwise I get an error. Can I remove the etag line (not needed anyway) before being parsed or get around it some other way? I unfortunately cant change what the API sends.
<?php
$json = '{
"Form": {
"Id": "1",
"InternalName": "SignUp",
"Name": "Sign Up"
},
"$version": 7,
"$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",
"Email": "test#email.com",
"Phone": "(123) 412-3412",
"CarrierServiceProvider": "Sprint",
"WTSKeywords": "Testing WTS",
"WTBKeywords": "Testing WTB",
"Id": "1-3",
"Email_IsRequired": false,
"Phone_IsRequired": false,
"CarrierServiceProvider_IsRequired": true
}';
$data = json_decode($json);
echo $data->Email;
echo "\n";
echo $data->WTBKeywords;
?>
Code should output: test#email.com Testing WTB
You json string has both ' and ", so you cannot simple use single or double quoted.
Use heredoc like this,
$json = <<<EOT
{
"Form": {
"Id": "1",
"InternalName": "SignUp",
"Name": "Sign Up"
},
"$version": 7,
"$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",
"Email": "test#email.com",
"Phone": "(123) 412-3412",
"CarrierServiceProvider": "Sprint",
"WTSKeywords": "Testing WTS",
"WTBKeywords": "Testing WTB",
"Id": "1-3",
"Email_IsRequired": false,
"Phone_IsRequired": false,
"CarrierServiceProvider_IsRequired": true
}
EOT;
$data = json_decode($json);
echo $data->Email;
echo "\n";
echo $data->WTBKeywords;
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
I got 2 JSON files extracted from the same db,
a:)
{
"hint_data": {
"locations": ["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB", "bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],
"checksum": 326195011
},
"route_name": ["", ""],
"via_indices": [0, 15],
"via_points": [
[25.299982, 55.376873],
[25.29874, 55.369179]
],
"found_alternative": false,
"route_summary": {
"end_point": "",
"start_point": "",
"total_time": 101,
"total_distance": 871
},
"route_geometry": "{_ego#m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli#hsEfFzn#QlTgNhwCs#fKwBjF",
"status_message": "Found route between points",
"status": 0
}
b:)
{
"alternative_names": [
["", ""]
],
"route_name": ["", ""],
"status_message": "Found route between points",
"route_geometry": "qo{o#wpslhBmFZwEpBgDzDeBlFWdGv#GCzEyBfIyEtEoNtEuMpAuHkAsCgC[mB{AgCuA{#uCa#}Cl#yBtB}#lDVhEcAtDmCdBcDx#iDDeDk#uBeBeB_CcGcXyFi^{Dg\\wBkP_Fs^wBiS_Ce[_D}UwAcKiBqIgI_TeLaUcMmP_IsHqf#_WyJeE}FMkDjIiTth#y|#loBq^vy#mu#fw#cUxOco#r^gb#zRoOjPsBfMq#rMjBdPnEpKlEnHJ~Dvn#la#nd#pT|f#lLv_#pRzLbHnb#fUxc#lMnaC~zAncBxnAkB|bB|CbmCl]rYxCzkCjwBzoBjxGl_G|fNhcMf~E~mE~pFt}EjbBlzAhvInyHfqDb~CblAw#poAzt#z}#bb#diD~dBxtEjgCfjDljBpuAfw#bpGngDhqF~yC~g#la#v~#ni#rbAjg#jPJlCFNdDGdDu#j#eAhBa#lCLdCaCjI_BtCy#vA_DvF}qAf}Bof#l{#{CnFoKdR}mAxBgM|TkJxPmLlSsf#|}#gf#x#kOzXmEfGmSx^kf#tw#mDtL}k#r~#ykCjjEau#niAee#bu#uUl\\}DpFzCrCr|#dt#|NbLroBx_BdZlV|DbDpBr~Anq#xm#r|#ls#|y#dq#}OXuMQcDhEoBgBeCCu[xXmBH",
"route_summary": {
"end_point": "",
"start_point": "",
"total_time": 824,
"total_distance": 15391
},
"found_alternative": true,
"alternative_summaries": [{
"end_point": "",
"start_point": "",
"total_time": 886,
"total_distance": 14967
}],
"via_points": [
[25.196808, 55.273754],
[25.139168, 55.187702]
],
"status": 0,
"via_indices": [0, 144],
"hint_data": {
"locations": ["TdMLAP____8AAAAADwAAAA8AAAA9AAAAbAAAAOtwBgAAAAAACXmAARxpSwMEAAEB", "4Q4AAGKyBgAAAAAACQAAAAAAAAAhAQAAAAAAAGUYAAAAAAAA4Zd_AfgYSgMGAAEB"],
"checksum": 326195011
},
"alternative_geometries": ["qo{o#wpslhBmFZwEpBgDzDeBlFWdGv#GCzEyBfIyEtEoNtEuMpAuHkAsCgC[mB{AgCuA{#uCa#}Cl#yBtB}#lDVhEcAtDmCdBcDx#iDDeDk#uBeBeB_CcGcXyFi^{Dg\\wBkP_Fs^wBiS_Ce[_D}UwAcKiBqIgI_TeLaUcMmP_IsHqf#_WyJeE}FMkDjIiTth#y|#loBq^vy#ec#vfAyeAfcCok#vtA}Wtx#uS|d#skAvfCgExJgJpTqH|O}#n~#wSve#qEhKkYdp#gB~DuUrk#_JdRsAhDmJlVqd#rcAuM|Zeg#zkAiKzUgIbS}B~EtDvBhr#a#dQ~J|rBpmAj_CfyAlAzD^lDgHnOyQlg#w[l|#}Q~d#eBB}Af#mAdAw#bBWpBJrBn#hBaAjGif#ptAk^rmAoVxy#cHjPmCHE|Bp[xRpc#ZfLvIzLlIreG~cEjrArz#rmAl|#lbDrzBjWlQ|xA~bAho#pc#d_#jWng#j^hNzJvGnEnPjLlAx#lgAhv#bGvCjkBvoAbjDr}BvfAx{#t\\rSfoDviC~zAjgAfOxIvAbAjwCtsBv|#|m#bD|BvLId_Dt|BtLlIxsAx_AfE~Crn#hc#rKvIh_BniApe#z\xIpGtoBpxAtEdDrQrMzjChlB~#lo#nwFpE|jBl|AzFzE|DfDvDrCjKfJr#n\\pLzKnBzzAdO~LhaFxaEzCdCnLpKbp#ti#nIjHdRzMjo#tg#~MvKpwCtdClw#bm#z[bWfr#vk#zCrCr|#dt#|NbLroBx_BdZlV|DbDpBr~Anq#xm#r|#ls#|y#dq#}OXuM`QcDhEoBgBeCCu[xXmBH"],
"alternative_indices": [0, 183]
}
And I am running this script on every JSON file.
Here is the script.
<?php
$json = '{"hint_data":{"locations":["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB","bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],"checksum":326195011},"route_name":["",""],"via_indices":[0,15],"via_points":[[25.299982,55.376873],[25.29874,55.369179]],"found_alternative":false,"route_summary":{"end_point":"","start_point":"","total_time":101,"total_distance":871},"route_geometry":"{_ego#m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli#hsEfFzn#QlTgNhwCs#fKwBjF","status_message":"Found route between points","status":0}';
$data = json_decode($json);
$totalTime = $data->route_summary->total_time;
var_dump($totalTime); // DUMPS 101
I am getting the first JSON file output correctly but I am getting an error in the 2nd one.
Please tell me what's wrong with the JSON file.
Your json is not valid.
The "alternative_geometries" property contains a string that is not properly encoded. (\x is not valid. If you want the slash, then it would need to be \\x)
Try validating it somewhere like this: http://jsonlint.com/
1) put data to text file
2) try again with:
<?php
$data = file_get_contents('./relative/path/to/file.json');
$data = json_decode($data);
$totalTime = $data->route_summary->total_time;
var_dump($totalTime);
it would be better to write data to files and put somewhere to download them to check the file.
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);
}
?>
In GitLab web hooks this is the json they give as an example.
{
"before": "95790bf891e76fee5e1747ab589903a6a1f80f22",
"after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"ref": "refs/heads/master",
"user_id": 4,
"user_name": "John Smith",
"project_id": 15,
"repository": {
"name": "Diaspora",
"url": "git#localhost:diaspora.git",
"description": "",
"homepage": "http://localhost/diaspora",
},
"commits": [
{
"id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
"message": "Update Catalan translation to e38cb41.",
"timestamp": "2011-12-12T14:27:31+02:00",
"url": "http://localhost/diaspora/commits/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
"author": {
"name": "Jordi Mallach",
"email": "jordi#softcatala.org",
}
},
{
"id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"message": "fixed readme",
"timestamp": "2012-01-03T23:36:29+02:00",
"url": "http://localhost/diaspora/commits/da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"author": {
"name": "Code Solution dev user",
"email": "gitlabdev#dv6700.(none)",
},
},
],
"total_commits_count": 4,
}
I've placed this in a file test.json.
I'm calling this with file_get_contents() then trying to decode but I'm getting nothing back at all.
$test = file_get_contents('test.json');
$json = json_decode($test);
echo "<pre>";
print_r($json);
echo "</pre>";
returns:
<pre></pre>
Any ideas why json_decode() is failing to decode?
It is because of a stray comma. You should check for errors:
if (json_last_error() != JSON_ERROR_NONE) {
die(json_last_error_msg());
}
If you have PHP <5.5.0 then you can use this compatibility function:
if ( ! function_exists('json_last_error_msg')) {
function json_last_error_msg() {
static $errors = array(
JSON_ERROR_NONE => null,
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);
$error = json_last_error();
return array_key_exists($error, $errors) ? $errors[$error] : "Unknown error ({$error})";
}
}
Actually it wasn't stray commas as the answerers suggested, JSONLint reported BOM artifacts from UTF-8, I'm assuming from copying and pasting.
Once I ran it through and removed the BOM artifacts it decoded properly.
Thanks to all for your help and suggestions.