I want to post some data to my domain with retrofit. My post is successful but data that I sent is not received, seems empty. So, post received but data not. I think that maybe I should post body, not field, but I'm not sure.
interface
My interface is:
#POST("/test.php")
#FormUrlEncoded
fun odemeYapDao(
#Field("user_basket") userBasket: String,
#Field("email") email: String,
#Field("payment_amount") paymentAmount: String,
#Field("cc_owner") ccOwner: String,
#Field("card_number") cardNumber: String,
#Field("expiry_month") expiryMonth: String,
#Field("expiry_year") expiryYear: String,
#Field("cvv") cvv: String,
#Field("user_name") userName: String,
#Field("user_address") userAddress: String,
#Field("merchant_id") merchantId: String,
#Field("merchant_key") merchantKey: String,
#Field("merchant_salt") merchantSalt: String,
#Field("merchant_oid") merchantOid: String,
#Field("user_phone") userPhone: String,
) : Call<OdemeResponseTest>
Repo
My repo is:
fun odemeYapRepo() {
oDao.odemeYapDao(
"Amount: ","test#gmail.com","100",
"TEST","4355084355084358","12","24",
"000","UserNickname","Tokyo", "261220", "muMsJ2XHoQPygZTp", "coyPecbfxs6EN5CG",
"87U2GS48saHJ8S45", "05431234564"
).enqueue(object : Callback<OdemeResponseTest>{
override fun onResponse(
call: Call<OdemeResponseTest>,
response: Response<OdemeResponseTest>
) {}
override fun onFailure(call: Call<OdemeResponseTest>, t: Throwable) {}
})
}
PHP File
My Php file is:
<?php
$response = array();
if (isset($_POST['user_basket']) && isset($_POST['email']) && isset($_POST['payment_amount']) && isset($_POST['cc_owner'])
&& isset($_POST['card_number']) && isset($_POST['expiry_month']) && isset($_POST['expiry_year']) && isset($_POST['cvv'])
&& isset($_POST['user_name']) && isset($_POST['user_address']) && isset($_POST['merchant_id']) && isset($_POST['merchant_key'])
&& isset($_POST['merchant_salt']) && isset($_POST['merchant_oid']) && isset($_POST['user_phone'])){
$sepet = $_POST['user_basket'];
$email = $_POST['email'];
$payment_amount = $_POST['payment_amount'];
$cc_owner = $_POST['cc_owner'];
$card_number = $_POST['card_number'];
$expiry_month = $_POST['expiry_month'];
$expiry_year = $_POST['expiry_year'];
$cvv = $_POST['cvv'];
$user_name = $_POST['user_name'];
$user_address = $_POST['user_address'];
$merchant_id = $_POST['merchant_id'];
$merchant_key = $_POST['merchant_key'];
$merchant_salt = $_POST['merchant_salt'];
$merchant_oid = $_POST['merchant_oid'];
$user_phone = $_POST['user_phone'];
$user_basket = htmlentities(json_encode(array(
array($sepet, $payment_amount, 1)
)));
$response["success"] = 1;
echo json_encode($response);
print_r($_POST);
}else {
$response["success"] = 0;
echo json_encode($response);
}
?>
Related
background:
I am receiving transaction initialization parameters via POST for a payment service. Then I need to use those parameters to create a 'Deposit' object in PHP and then JSON serializes the deposited object and stores JSON to a variable.
I am trying to achieve that with the following code:
code:
//get parameters by POST and add to Deposit class
$user_id = echo $_POST["user"];
$tradingaccount_id = echo $_POST["trading_account"];
$fundprocessor_id = echo $_POST["func_processor"];
$paymentgateway_type = echo $_POST["payment_gateway_type"];
$paymentgateway_id = echo $_POST["payment_gateway_id"];
$amount = echo $_POST["deposit_amount"];
$client_ip = echo $_POST["user_ip"];
//Deposit class
var deposit = new Deposit
{
UserId = echo $user_id,
TradingAccountId = new Guid(echo $tradingaccount_id),
FundProcessorId = int (echo $fundprocessor_id),
PaymentGatewayId = echo $paymentgateway_id,
Amount = echo $amount,
ClientIp = echo $client_ip
//serialize data to JSON
function getJsonData(){
$var = get_object_vars($this);
foreach ($var as &$value) {
if (is_object($value) && method_exists($value,'getJsonData')) {
$value = $value->getJsonData();
}
}
return $var;
}
};
Question:
Is the above the correct way to do this?
Will $var variable contain the JSON serialized object?
If your Deposit class won't be implementing any additional logic, you can take a simpler approach:
$deposit = [];
$deposit['UserId'] = $_POST["user"];
$deposit['TradingAccountId'] = new Guid($_POST["trading_account"]);
$deposit['FundProcessorId'] = intval($_POST["func_processor"]);
$deposit['PaymentGatewayId'] = $_POST["payment_gateway_id"];
$deposit['Amount'] = $_POST["deposit_amount"];
$deposit['ClientIp'] = $_POST["user_ip"];
$json = json_encode($deposit);
Otherwise you should implement JsonSerializable in your class.
I am making an api that can help user update their info follow the input data. But when in input json have field "password" it will update successfully but when json don't have this field i can not update data in database. This is code i used to update data:
public function updateUserInfo(Request $request){
$postData = $request->all();
$data = json_decode($postData['postData'], true);
if(isset($data['password'])){
$data['password'] = bcrypt($data['password']);
}
$popData = $data['UserId'];
unset($data['UserId']);
$updateInfo = array();
foreach($data as $info){
if($info != null){
$updateInfo[] = $info;
}
}
$result = DB::update(GeneralFunctions::makeUpdateString($data, 'User', ' UserId = '.$popData), $updateInfo);
if($result != null && $result == true){
return response()->json(['success'=>true, 'data'=>'Update Successful']);
}else{
return response()->json(['success'=>false, 'error'=>'We have encountered an error, try again later!']);
}
}
This is the json when everything work fine:
$postData = '{ "UserId" : "1", "password":"12345", "UserName": "minhkhang", "Address": "11/200" }'
This is the json which will cause error because it is missing password field:
$postData = '{ "UserId" : "1", "UserName": "minhkhang", "Address": "11/200" }'
This is code i used to make update string follow input json:
public static function makeUpdateString($keyvalarr, $table, $where){
$stringSQL = 'UPDATE '.$table. ' SET ' ;
foreach($keyvalarr as $fieldname => $updateval){
if($updateval != null){
$stringSQL .= $fieldname.' = ? , ';
}
}
$stringSQL = substr($stringSQL, 0, -2);
if($where != null){
$stringSQL .= 'WHERE '.$where;
}
return $stringSQL;
}
Thank you.
The code in question here is:
if(isset($data['password'])){
$data['password'] = bcrypt($data['password']);
}
Check to see what
isset($data['password'])
is returning outside the if statement, if it is true for password being present in the JSON and not giving you an issue that sounds like what you'd expect, however check to see if that statement by itself is false without the if statement, make sure it isn't still jumping into that, it seems to be the only place your looking for 'password'
I've created a bot with #botfather and it's all okay . Now i want to set command from my host to telegram . i created a Bot.php in my root directory .
Bot.php
$string = json_decode(file_get_contents('php://input'));
function objectToArray( $object )
{
if( !is_object( $object ) && !is_array( $object ) )
{
return $object;
}
if( is_object( $object ) )
{
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
$result = objectToArray($string);
$user_id = $result['message']['from']['id'];
$text = $result['message']['text'];
if($text == 'Hi')
$text_reply = 'Hi';
if($text == 'Your name')
$text_reply = 'jJoe';
$token = '';
$text_reply = 'Got you Buddy.';
$url = 'https://api.telegram.org/bot'.tokenNumber.'/sendMessage?chat_id='.$user_id;
$url .= '&text=' .$text_reply;
$res = file_get_contents($url);
Now when i browse this :https://api.telegram.org/bot112186325:tokenNumber/setWebhook?url=https://partamsms.ir/bot.php
I get this : {"ok":true,"result":true,"description":"Webhook was set"}
But i can't run these commands in my telegram account .
How can i Run commands from my server ?
Thanks a million
According to your comment, you want something that will respond differently based on the message the user typed. So using your example code, you can change it to be something like this:
// NOTE: you can pass 'true' as the second argument to decode as array
$result= json_decode(file_get_contents('php://input'), true);
error_log(print_r($result, 1), 3, '/path/to/logfile.log');
$user_id = $result['message']['from']['id'];
$text = $result['message']['text'];
// TODO: use something like strpos() or strcmp() for more flexibility
switch (true)
{
case $text == '/hi':
$text_reply = 'Hello';
break;
case $text == '/yourname':
// TODO: use the getMe API call to get the bot information
$text_reply = 'jJoe';
break;
default:
$text_reply = 'not sure what you want?';
break;
}
$token = '';
$url = 'https://api.telegram.org/bot'.tokenNumber.'/sendMessage?chat_id='.$user_id;
$url .= '&text=' .$text_reply;
$res = file_get_contents($url);
So, this is pretty much a slight refactor of what you already had...if the issue is that your Bot.php script is not triggering, it is possibly because the page is not public. The webhook you specify to Telegram must be a publicly accessible URL. I tried to hit https://partamsms.ir/bot.php and I can't get to it.
An alternative is to use the getUpdates method instead and to cron the script to run every 5 seconds or so.
I'm trying to put a script together that will do some math for the user.
That works fine however when i try to put it in a session and try to show the value to the user it will only return 0 if its set to 0.
Does anybody know where i did wrong?
<?php
session_start();
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
$class1 = filter_var($_POST['class1'], FILTER_SANITIZE_STRING);
$class2 = filter_var($_POST['class2'], FILTER_SANITIZE_STRING);
$class3 = filter_var($_POST['class3'], FILTER_SANITIZE_STRING);
$class4 = filter_var($_POST['class4'], FILTER_SANITIZE_STRING);
$class5 = filter_var($_POST['class5'], FILTER_SANITIZE_STRING);
$class1C = $class1 * 35;
$class2C = $class2 * 5;
$class3C = $class3 * 7.5;
$class4C = $class4 * 26;
$class5C = $class5 * 2.5;
$totaal1 = $class1C + $class2C + $class3C + $class4C + $class5C;
$res = array($class1C, $class2C, $class3C, $class4C, $class5C, $totaal1);
foreach($res as $name => $var) {
$_SESSION[$name] = $var;
}
$result = array("error" => false, "html" => null);
$result["error"] = false;
$result["html"] = "<h3>Session information: var_dump($_SESSION[$class1C]) ($_SESSION[$class2C]) ($_SESSION[$totaal1])</h3>";
} else {
$result["error"] = true;
$result["html"] = "<h3>Error</h3>";
}
echo json_encode($result);
exit;
?>
You cannot call var_dump inside the double quoted string, and var_dump does not return anything: it only display things.
Even if you could, $class1C is not a valid index for $_SESSION
Keeping the same logic as your code, you may change your line to the following:
$result["html"] = "<h3>Session information:";
ob_start();
var_dump($_SESSION[0]); // contains $class1C
echo $_SESSION[1]; // contains $class2C
echo $_SESSION[5]; // contains $totaal1
$result["html"] .= ob_get_clean();
$result["html"] .= "</h3>";
EDIT:
If you want to use the indexes 'class2C', 'totaal1' etc.. you need to init $res as follow:
$res = array(
'class1C' => $class1C,
'class2C' => $class2C,
'class3C' => $class3C,
'class4C' => $class4C,
'class5C' => $class5C,
'totaal1' => $totaal1
);
Then, your loop to set $_SESSION will set correct indexes, and you will be able to use $_SESSION['class1C'] to get proper values.
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