My alamofire request is coming back as a failure when i print the response in xcode however, the web service is actually performing this and everything is supposed to happen as it should apart from the fact its coming back as a failure
Alamofire.request(BASE_URL + "index.php/feed/like", method: .post, parameters: parameters, headers: headers).responseJSON { response in
let result = response.result
debugPrint(response)
print(result)
if (result.value != nil) {
let json = JSON(result.value!)
print(json)
if json["status"] == false {
showError(type: "generic")
} else {
let nolikes = Int(self.lblLikes.text!)! + 1
self.lblLikes.text = String(nolikes)
self.actionLike.image = UIImage(named: "ActionLiked")
}
}
}
this is my error
[Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 1." UserInfo={NSDebugDescription=Invalid value around character 1.}))
[Timeline]: Timeline: { "Request Start Time": 509902187.696, "Initial Response Time": 509902188.176, "Request Completed Time": 509902188.177, "Serialization Completed Time": 509902188.177, "Latency": 0.480 secs, "Request Duration": 0.480 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.481 secs }
and this is my php function in codeigniter
function like_post()
{
$post = $this->_post_args;
$post = $this->security->xss_clean($post);
$like = $this->Feed_model->likePost($post);
if($like == TRUE) {
$this->set_response([
'status' => TRUE,
'message' => 'SUCCESS'
], REST_Controller::HTTP_ACCEPTED);
} else {
$this->set_response([
'status' => FALSE,
'error' => 'ALREADY_LIKED'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
public function likePost($post)
{
$postid = $post['post_id'];
$userid = $post['user_id'];
$query = $this->db->query("SELECT * FROM `post_likes` WHERE `user_id` = '{$userid}' AND `post_id` = '{$postid}'");
if($query->num_rows() > 0) {
return false;
} else {
$insert = [
'user_id' => $userid,
'post_id' => $postid
];
$this->db->insert('post_likes', $insert);
$currpost = $this->db->query("SELECT * FROM `posts` WHERE `post_id` = '{$postid}'");
$likes = $currpost->likes;
$update = ['likes' => $likes + 1];
$this->db->update('posts', $update, "post_id = '{$postid}'");
return true;
}
}
the code will return false if the user has already performed this action so if i first click on the action it will come back as failure in the console but the php script will run inserting everything to the database etc however, if i click it again i will get the php failure response (so the request shows as successful but it failed)
Related
Hello as i am new to flutter, i want to fetch data from php api to flutter app with json data which have multiple data's in one file
my flutter code
Future<Album> fetchAlbum() async {
final response = await http.post(
Uri.parse('https://domain/folder/api.php'),
body: jsonEncode({
"description": 'description',
"naw": "homeprod",
}),
);
if (response.statusCode == 200) {
// If the server did return a 201 CREATED response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 201 CREATED response,
// then throw an exception.
throw Exception('Failed to create.');
}
}
class Album {
//final int productid;
String description;
Album({this.description = ""});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
//productid: json['product_id'],
description: json['description'],
);
}
}
this my php code on server
if($postjson['naw']=="homeprod"){
$prod = array();
$query = mysqli_query($mysqli, "SELECT * FROM product order by rand() limit 30");
while($getpost = mysqli_fetch_array($query))
{
$prod[] = array(
'description' => $getpost['description']
);
}
if($query) $result = json_encode(array('success'=>true, 'prodlists'=>$prod));
else $result = json_encode(array('success'=>false));
echo $result;
}
always flutter return with Null data type with sub type string.
Thank you in advance
I am trying to use webhook to receieve data from a sms service provider.the hooked URL is http://exmple.com/xy/myphp.php and my myphp.php is as follows:
<?php
$con = new mysqli("server","uname","pass","db");
error_reporting(0);
$request = $_REQUEST["data"];
$jsonData = json_decode($request,true);
foreach($jsonData as $key => $value)
{
// request id
$requestID = $value['requestId'];
$userId = $value['userId'];
$senderId = $value['senderId'];
foreach($value['report'] as $key1 => $value1)
{
//detail description of report
$desc = $value1['desc'];
// status of each number
$status = $value1['status'];
// destination number
$receiver = $value1['number'];
//delivery report time
$date = $value1['date'];
$sql="INSERT INTO `delivary_report`(`request_id`, `user_id`, `sender_id`,`date`,`receiver`,`status`,`description`) VALUES('$requestID','$userId','$senderId','$date','$receiver','$status','$desc')";
$res=$con->query($sql);
}
}
//echo $request;
?>
the sms service provider is saying that they can get 406 error. please tell me how to solve this issue. currently i am using godaddy shared server. the json formated data they are sending looks like the follows.
data=[
{
"requestId":"35666a716868323535323239",
"userId":"38229",
"report":[
{
"desc":"REJECTED",
"status":"16",
"number":"91XXXXXXXXXX",
"date":"2015-06-10 17:09:32.0"
}
],
"senderId":"tester"
},
{
"requestId":"35666a716868323535323239",
"userId":"38229",
"report":[
{
"desc":"REJECTED",
"status":"16",
"number":"91XXXXXXXXXX",
"date":"2015-06-10 17:09:32.0"
},
{
"desc":"REJECTED",
"status":"16",
"number":"91XXXXXXXXXX",
"date":"2015-06-10 17:09:32.0"
}
],
"senderId":"tester"
}
]
when i am trying to submit this function save() this shows "502 Bad Gateway The server returned an invalid or incomplete response. "we didn't do any changes recently in this existing working code. is this a code error or miss configuration of server? why i geting this error.?
function save()
{
$data = array('client_email' => $this->input->post('client_email'),'client_fname' => $this->input->post('client_fname'),'client_sname' => $this->input->post('client_sname'),'client_company' => $this->input->post('client_company'),'client_phone' => $this->input->post('client_phone')
);
$our_current_client = $this->input->post('currenct_client');
$this->order2model->form_update($data,$this->input->post('currenct_client'));
$other_services_var = '';
$count_otherss = 0;
if($this->input->post('otherservices')!='')
{
$otherservices = $this->input->post('otherservices');
$other_id = explode('_',$otherservices);
$other_services_var = $other_id[1];
$this->session->set_userdata('service', $other_id[1]);
}
if($other_services_var != '')
{
//$this->session->set_userdata('service', 'others_radio');
}
else
{
$this->session->set_userdata('service', $this->input->post('rb'));
$this->session->unset_userdata('cull');
$this->session->unset_userdata('cull_max');
$this->session->unset_userdata('cull_min');
$this->session->unset_userdata('cull_images');
$this->session->unset_userdata('lr_image_sub');
$this->session->unset_userdata('lr_image_del');
$this->session->unset_userdata('strength');
$this->session->unset_userdata('strength_images');
}
$rb = $this->input->post('rb');
if($rb=='wed_custom')
{
$cull = $this->input->post('cull_onoffswitch');
$strength = $this->input->post('str_onoffswitch');
$this->session->set_userdata('total_images_lr', $this->input->post('total_images_lr'));
$this->session->set_userdata('lr_image_sub', $this->input->post('lr_image_sub'));
$this->session->set_userdata('lr_image_del', $this->input->post('lr_image_del'));
if($cull=='on')
{
$this->session->set_userdata('cull', $this->input->post('cull_onoffswitch'));
$this->session->set_userdata('cull_max', $this->input->post('cull_max'));
$this->session->set_userdata('cull_min', $this->input->post('cull_min'));
$this->session->set_userdata('cull_images', $this->input->post('cull_images'));
$this->session->set_userdata('lr_image_sub', $this->input->post('lr_image_sub'));
$this->session->set_userdata('lr_image_del', $this->input->post('lr_image_del'));
}else{
$this->session->unset_userdata('cull');
$this->session->unset_userdata('cull_max');
$this->session->unset_userdata('cull_min');
$this->session->unset_userdata('cull_images');
}
if($strength=='on')
{
$this->session->set_userdata('strength', $this->input->post('str_onoffswitch'));
$this->session->set_userdata('strength_images', $this->input->post('strength_images'));
$this->session->set_userdata('total_images_lr', $this->input->post('total_images_lr'));
$this->session->set_userdata('lr_image_sub', $this->input->post('lr_image_sub'));
$this->session->set_userdata('lr_image_del', $this->input->post('lr_image_del'));
}else
{
$this->session->unset_userdata('strength');
$this->session->unset_userdata('strength_images');
}
}
$this->session->set_userdata('client_fname', $this->input->post('client_fname'));
$this->session->set_userdata('client_sname', $this->input->post('client_sname'));
$this->session->set_userdata('client_company', $this->input->post('client_company'));
$this->session->set_userdata('client_phone', $this->input->post('client_phone'));
$this->session->set_userdata('client_email', $this->input->post('client_email'));
$this->session->set_userdata('rush', $this->input->post('onoffswitch'));
$this->session->set_userdata('no_images', $this->input->post('no_images'));
$this->session->set_userdata('file_format', $this->input->post('file_format'));
$this->session->set_userdata('notes', $this->input->post('notes'));
$this->session->set_userdata('active_tab', $this->input->post('active_tab'));
$this->session->set_userdata('current_checked', $this->input->post('current_checked'));
$this->session->set_userdata('our_client', $our_current_client);
$this->session->set_userdata('item_details', $this->input->post('item_details'));
redirect('order3');
}
I am working on a project that previously done with another developer. This project based on PHP Yii framework and mobile side is Android to get JSON messages from the web services that provided in the website.
I'm stuck in this web service function "getStamp"
I don't know what are the JSON response messages. I mean what are the string Values that I'll hold for 'stampID', 'stampName', 'stampImg'.
These are the information that I have:
request parameters:
kioskid
accesstoken
tagid
eventid
checking = 0 or 1
for failed response:
status = 0
message = error message
for success response:
status = 1
tappedStamp = the obtain stamp ID after tapping the device (if checking not equal to 1)
message = the message of the obtained stamp (if checking not equal to 1)
collectedStamp = list of collected stamp ID
If you want to use 'getStamp' web service to do the checking on how
many stamps that have been collected by the user, then you pass
'checking' as 1. If you want to use that web service to collect the
stamp of the kiosk, then you pass 'checking' as 0.
So far as what I understand from the Code and explanation that 'collectedStamp' and 'tappedStamp' are JSON Object names of a JSON Arrays
I need to know these 3 Elements (I suppose to get it from some where the names are random not real I just make it to explain to you what need)
'stampID', 'stampName','stampImg'
{ "collectedStamp" : [ { "stampID" : "1",
"stampName" : "stamp1",
"stampImg": "stamp1.png"
},
{ "stampID" : "2",
"stampName" : "stamp2",
"stampImg": "stamp2.png"
},
],
"status" : "1"
}
{ "tappedStamp" : [ { "stampID" : "1",
"stampName" : "stamp1",
"stampImg": "stamp1.png"
},
{ "stampID" : "2",
"stampName" : "stamp2",
"stampImg": "stamp2.png"
},
],
"status" : "1"
}
For Android Implementation most likely I'll use the same code that I provided in this post
Errors when getting JSON result into ListView
if you see in the web service function in that link you'll find this
$list = array();
foreach($events as $row){
$list[] = array('id'=>$row->id, 'name'=>$row->eventname);
}
$response['status'] = '1';
$response['list'] = $list;
}
which means that that the JSON response['list'] Contains 'id' and 'name' objects
and these are the String values that I add it inside ListView Adapter
I need to know the equivalent to 'id' and 'name' in this web Service
getStamp() Web Service Function:
public function actionGetStamp(){
if(isset($_POST['kioskid']) && isset($_POST['accesstoken']) && isset($_POST['tagid']) && isset($_POST['eventid']) && isset($_POST['checking'])){
$response = array();
$kiosk = Kiosk::model()->findByAttributes(array('kioskid'=>$_POST['kioskid'], 'accesstoken'=>$_POST['accesstoken']));
if(($kiosk === null || $kiosk->eventid != $_POST['eventid']) && $_POST['accesstoken'] != 'REPOST_SYNC'){
$response['status'] = '0';
$response['message'] = 'Invalid Kiosk';
} else {
$eventStation = EventStation::model()->findByAttributes(array('eventid'=>$_POST['eventid'],'deviceid'=>$_POST['kioskid']));
if($eventStation === null){
$response['status'] = '0';
$response['message'] = 'Invalid Kiosk';
} else {
$tag = EventTag::model()->findByAttributes(array('tagid'=>$_POST['tagid'], 'eventid'=>$eventStation->eventid, 'status'=>'A'));
if($tag === null || $tag->joinon == null){
$response['status'] = '0';
$response['message'] = 'Tag is not registered yet.';
} else {
$sql = 'SELECT es.id, (CASE WHEN esc.stampid IS NULL THEN 0 ELSE 1 END) collected,
(CASE WHEN es.kioskid = :kioskid THEN 1 ELSE 0 END) tapped,
es.message
FROM tap_event_stamp es
LEFT JOIN tap_event_stamp_collection esc ON es.id = esc.stampid and esc.tagid = :tagid
WHERE es.eventid = :eventid AND es.isdeleted = 0
GROUP BY es.id ORDER BY es.id
';
$params = array(':eventid'=>$_POST['eventid'], ':kioskid'=>$eventStation->id, ':tagid'=>$tag->id);
$stamps = Yii::app()->db->createCommand($sql)->queryAll(true, $params);
if(sizeof($stamps) == 0){
$response['status'] = '0';
$response['message'] = 'Invalid Request';
} else {
$feature = EventFeatures::model()->findByAttributes(array('eventid'=>$_POST['eventid'],'featureid'=>3));
if($feature === null){
$response['status'] = '0';
$response['message'] = 'Invalid Request';
} else {
$info = json_decode($feature->info, true);
$random = false;
if(isset($info['STAMPSEQ'])){
$random = $info['STAMPSEQ'] == 'R';
}
$collected = array();
$response['status'] = $_POST['checking'] == 1 ? '1' : '0';
$duplicate = false;
foreach($stamps as $stamp){
if ($stamp['tapped'] == 1 && $_POST['checking'] != 1){
$response['tappedStamp'] = $stamp['id'];
$response['message'] = $stamp['message'];
$response['status'] = '1';
$duplicate = $stamp['collected'] == 1;
} elseif($stamp['collected'] == 1){
$collected[] = $stamp['id'];
continue;
} elseif(!$random && $_POST['checking'] != 1){
if( !isset($response['tappedStamp']) ){
$response['message'] = 'You have tapped a wrong kiosk';
}
break;
}
}
if( $response['status'] == '1' ){
$response['collectedStamp'] = $collected;
if(!$duplicate && $_POST['checking'] != 1){
$newRecord = new StampCollection();
$newRecord->eventid = $_POST['eventid'];
$newRecord->tagid = $tag->id;
$newRecord->kioskid = $eventStation->id;
$newRecord->stampid = $response['tappedStamp'];
$newRecord->collectedon = time();
$newRecord->save();
}
}
if( $response['status'] == '1' && Yii::app()->params['isOffline'] && $_POST['checking'] != 1){
$params = array();
$params['tagid'] = $_POST['tagid'];
$params['eventid'] = $_POST['eventid'];
$params['kioskid'] = $_POST['kioskid'];
$params['accesstoken'] = 'REPOST_SYNC';
$model = new PendingRequest();
$model->request_url = '/ws/getStamp';
$model->request_param = json_encode($params);
$model->createdon = time();
$model->issent = 0;
$model->save();
}
}
}
}
}
}
$this->_sendResponse(200, CJSON::encode($response));
} else {
$this->_sendResponse(400);
}
}
One more question:
How can I check the web service from the Browser and pass the parameter (this Project uses Yii Framework)? So I can get JSON message either from browser.
Update:
After using "POSTMAN REST Client" I got this message
if checking = 1
{"status":"1","collectedStamp":[]}
if checking = 0
this is the HTML Code I got
https://drive.google.com/file/d/0B0rJZJK8qFz9MENzcWxhU3NPalk/edit?usp=sharing
Im new to cakephp and have implemented the Webshop Solution Snipcart. When an order is processed by snipcart they send a webhook to our site. The webhook looks like this according to their documentation:
{
eventName: "order:completed",
mode: "Live",
createdOn: "2013-07-04T04:18:44.5538768Z",
content: {
token: "22808196-0eff-4a6e-b136-3e4d628b3cf5",
creationDate: "2013-07-03T19:08:28.993Z",
modificationDate: "2013-07-04T04:18:42.73Z",
status: "Processed",
paymentMethod: "CreditCard",
email: "customer#snipcart.com",
cardHolderName: "Nicolas Cage",
billingAddressName: "Nicolas Cage",
billingAddressCompanyName: "Company name",
billingAddressAddress1: "888 The street",
billingAddressAddress2: "",
billingAddressCity: "Québec",
billingAddressCountry: "CA",
billingAddressProvince: "QC",
billingAddressPostalCode: "G1G 1G1",
billingAddressPhone: "(888) 888-8888",
shippingAddressName: "Nicolas Cage",
shippingAddressCompanyName: "Company name",
shippingAddressAddress1: "888 The street",
shippingAddressAddress2: "",
shippingAddressCity: "Québec",
shippingAddressCountry: "CA",
shippingAddressProvince: "QC",
shippingAddressPostalCode: "G1G 1G1",
shippingAddressPhone: "(888) 888-8888",
shippingAddressSameAsBilling: true,
finalGrandTotal: 310.00,
shippingAddressComplete: true,
creditCardLast4Digits: "4242",
shippingFees: 10.00,
shippingMethod: "Livraison",
items: [{
uniqueId: "eb4c9dae-e725-4dad-b7ae-a5e48097c831",
token: "22808196-0eff-4a6e-b136-3e4d628b3cf5",
id: "1",
name: "Movie",
price: 300.00,
originalPrice: 300.00,
quantity: 1,
url: "https://snipcart.com",
weight: 10.00,
description: "Something",
image: "http://placecage.com/50/50",
customFieldsJson: "[]",
stackable: true,
maxQuantity: null,
totalPrice: 300.0000,
totalWeight: 10.00
}],
subtotal: 610.0000,
totalWeight: 20.00,
hasPromocode: false,
promocodes: [],
willBePaidLater: false
}
}
And the consume the webhooks looks like this:
<?php
$json = file_get_contents('php://input');
$body = json_decode($json, true);
if (is_null($body) or !isset($body['eventName'])) {
// When something goes wrong, return an invalid status code
// such as 400 BadRequest.
header('HTTP/1.1 400 Bad Request');
return;
}
switch ($body['eventName']) {
case 'order:completed':
// This is an order:completed event
// do what needs to be done here.
break;
}
// Return a valid status code such as 200 OK.
header('HTTP/1.1 200 OK');
My question is, how do I do this in CakePHP version 2.4. I've been looking for days now on the internet for a solution, but tho i'm inexperienced I can't find a proper solution.
Solved it:
public function webhooks(){
//check if POST
if ($this->request->is('post')) {
//Allow raw POST's
$url = 'php://input';
//decode
$json = json_decode(file_get_contents($url), true);
if (is_null($json) or !isset($json['eventName'])) {
// When something goes wrong, return an invalid status code
// such as 400 BadRequest.
header('HTTP/1.1 400 Bad Request');
return;
}
//do whatever needs to be done, in this case remove the quantity ordered from the stock in db.
switch ($json['eventName']) {
case 'order:completed':
$id = $json['content']['items'][0]['id'];
$quantity = $json['content']['items'][0]['quantity'];
$query = $this->Shop->findById($id, 'Shop.stock');
$stock = $query['Shop']['stock'];
$stock = $stock - $quantity;
$this->Shop->updateAll(array('Shop.stock' => $stock), array('Shop.id' => $id));
break;
}
header('HTTP/1.1 200 OK');
}
}
the only thing I would add to your answer is a few more "cake" ways of doing some things.
public function webhooks(){
//check if POST
if ($this->request->is('post') || $this->request->is('put')) {
//Allow raw POST's
$url = 'php://input';
//decode
$json = json_decode(file_get_contents($url), true);
if (empty($json) or empty($json['eventName'])) {
throw new BadRequestException('Invalid JSON Information');
}
//do whatever needs to be done, in this case remove the quantity ordered from the stock in db.
switch ($json['eventName']) {
case 'order:completed':
$id = $json['content']['items'][0]['id'];
$quantity = $json['content']['items'][0]['quantity'];
$shop = $this->Shop->find('first', array(
'conditions' => array(
'Shop.id' => $id,
),
'fields' => array(
'Shop.stock',
),
));
if (empty($shop)) {
throw new NotFoundException(__('Invalid Shop Content'));
}
$stock = $shop['Shop']['stock'];
$stock = $stock - $quantity;
$this->Shop->id = $id;
$this->Shop->saveField('stock', $stock);
break;
}