Unexpected end of input error in react native - reactjs

I get an error prompt SyntaxError: Unexpected end of input when I try to the message from API.
Here is my code:
.then((response) =>response.json())
.then((response)=>{
alert(response[0].Message);
})
.catch((error) => {
alert("Error"+error);
});
If I change to the code below, it runs well with no errors, but it will not prompt any successful message.
try{
((response) =>response.json()),
((response)=>{
alert(response[0].Message);
})
}
catch{
((error) => {
alert("Error"+error);
})
}
Here is the api script:
<?php
$CN = mysqli_connect('localhost', 'root', '');
$DB = mysqli_select_db($CN, 'iostest');
$EncodedData = file_get_contents('php://input');
$DecodedData = json_decode($EncodedData, true);
$userid = $DecodedData['userid'];
$jid=$DecodedData['jid'];
$job=$DecodedData['job'];
$mcode=$DecodedData['mcode'];
$insertuserid = "insert into scan(user,job,jobid,machinecode) values ('$userid','$job','$jid','$mcode')";
$register = mysqli_query($CN, $insertuserid);
if ($register)
$Message = "Member has been registered successfully";
else
$Message = "Server Error... please try latter";
$Response[] = array("Message" => $Message);
echo json_encode($Response);
?>

Related

Sending JSON HTTP request using Guzzle HTTP: Result parameters are not as expected

I want to send a JSON request to an endpoint but the results that I get don't match the parameters requested.
This is the array
$datas = [
"institutionCode" => $institutionCode,
"brivaNo" => $brivaNo,
"custCode" => $custCode
];
This is the response using Guzzle HTTP
try {
$response = $client->request($verb, $endpoint,
[
"headers" =>
[
"Authorization" => "Bearer " . $token,
"BRI-Timestamp" => $timestamp,
"BRI-Signature" => $signature,
],
"json" => $datas
]
);
return $response;
}
catch (\GuzzleHttp\Exception\RequestException $e) {
return $e->getResponse();
}
This is the response from the endpoint
{
"status": false,
"errDesc": "Institution Code Tidak Boleh Kosong",
"responseCode": "03",
"data": {
"{\"institutionCode\":\"J104408\",\"brivaNo\":\"77777\",\"custCode\":\"7878787878\"}": ""
}
}
Why does the "data" not match the data array I have given above and instead creates a new pattern with a backslash in it?
This is the native way using cURL PHP
if there is someone can turn it into a Guzzle Http, it will help me,
after I tried this code, it also didn't help at all
$institutionCode = "J104408";
$brivaNo = "77777";
$custCode = "123456789115";
$payload = "institutionCode=".$institutionCode."&brivaNo=".$brivaNo."&custCode=".$custCode;
$path = "/v1/briva";
$verb = "DELETE";
$base64sign = generateSignature($path,$verb,$token,$timestamp,$payload,$secret);
$request_headers = array(
"Authorization:Bearer " . $token,
"BRI-Timestamp:" . $timestamp,
"BRI-Signature:" . $base64sign,
);
$urlPost ="https://sandbox.partner.api.bri.co.id/v1/briva";
$chPost = curl_init();
curl_setopt($chPost, CURLOPT_URL,$urlPost);
curl_setopt($chPost, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($chPost, CURLOPT_POSTFIELDS, $payload);
curl_setopt($chPost, CURLINFO_HEADER_OUT, true);
curl_setopt($chPost, CURLOPT_RETURNTRANSFER, true);
$resultPost = curl_exec($chPost);
$httpCodePost = curl_getinfo($chPost, CURLINFO_HTTP_CODE);
curl_close($chPost);
$jsonPost = json_decode($resultPost, true);
return $jsonPost;

Display Progress message after calling api url

we select checbox & onclick button "Show Status" , I am calling external webservice api url & updating the "status" column [4th in below image] values in Database.....
once we got success response we are displaying alert message....
Requirement :
but now i want to display Progress like "1% completed , 2 % completed" , so on.... :
status page
<button type= "button" id="show_status" >Show Status</button>
script
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function()
{
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var jsonString = JSON.stringify(selected);
$.ajax
({
type: "POST",
url: "api.php",
data: {data : jsonString},
success: function(response)
{
response = $.parseJSON(response);
alert("completed");
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
}
});
});
api.php
<?php
$data = json_decode(stripslashes($_POST['data']));
$response = array();
foreach($data as $id){
$post_data['username']='a';
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
//print_r($orderResults); die;
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
echo json_encode($response);
?>
Please try this script and code
$('#show_status').click(function()
{
var selected = [];
$('.assigneeid-order:checked').each(function(){
selected.push($(this).val());
$('.assigneeid-order').prop('checked', false);
});
var count = selected.length
var perPlush = 100/count;
var per = 0;
for (var i = 0; i <= count; i++) {
$.ajax
({
type: "POST",
url: "api.php",
data: {id : selected[i]},
success: function(response)
{
response = $.parseJSON(response);
$.each(response, function(index, val)
{
$("#"+index+"").html(val);
$("#"+index+"").html(val.status);
});
per = per + perPlush;
console.log(Math.round(per) + " % Complated");
$("#progress").html(Math.round(per) + " % Complated");
}
});
}
});
Your api.php file
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
require_once("dbcontroller.php");
$db_handle = new DBController();
$id = $_POST['id']; //960856092
$response = array();
$orderid = $id;
$hide = '';
$post_data['awb']=$orderid;
$url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "http://plapi.ecomexpress.in/track_me/api/mawbd/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec ($ch);
curl_close($ch);
$orderResults=$xml=simplexml_load_string($output);
if($orderResults){
foreach($orderResults->object as $child)
{
$status=(string)$child->field[10];
break;
}
$statusfinal = str_replace('<field type="CharField" name="status">','',$status);
if($statusfinal!='')
{
$sqlecom = "UPDATE do_order set in_transit='".$status."' where tracking_id=".$orderid;
//echo $sqlecom;
$db_handleecom = new DBController();
$resultecom = $db_handleecom->executeUpdate($sqlecom);
}
$response[$orderid] = [ 'status' => $status ];
}
else{
$response[$orderid] = ['status' => 'Order already placed'];
}
echo json_encode($response);
?>

Session issues in cakephp 2.x with facebook sdk in production

I am trying to use Facebook PHP sdk with cakephp 2.x for login purpose.
And it is working with debug mode 1 or 2 but it is not working with debug mode 0.
It seems session is not working properly in production.
I search about it on the web many times but not get the right solution for me.
I read these two threads in detail but did not cope with the problem.
https://github.com/facebook/php-graph-sdk/issues/473
How do I integrate Facebook SDK login with cakephp 2.x?
I use these two functions in AppController for login.
public function beforeFilter()
{
$this->disableCache();
$this->Facebook = new Facebook(array(
'app_id' => 'appId',
'app_secret' => 'appSecret',
'default_graph_version' => 'v2.7',
));
$this->Auth->allow(['.....']);
}
public function login()
{
if (!session_id()) {
session_start();
}
$this->loadModel("User");
$user_id = $this->Session->read('Auth.User.id');
$fb = $this->Facebook->getRedirectLoginHelper();
$permissions = ['email']; // Optional permissions
$callback_url = HTTP_ROOT . 'login';
$fb_login_url = $fb->getLoginUrl($callback_url, $permissions);
$this->set('fb_login_url', $fb_login_url);
if (!empty($user_id)) {
//redirect to profile page if already logged in
$this->redirect(... . );
}
//local login request
if ($this->request->is('post')) {
......
}
// when facebook login is used
elseif ($this->request->query('code')) {
try {
$accessToken = $fb->getAccessToken();
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$this->Session->setFlash('Graph returned an error: ' . $e->getMessage(), 'error');
$this->redirect($this->referer());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$this->Session->setFlash('Facebook SDK returned an error: ' . $e->getMessage(), 'error');
$this->redirect($this->referer());
}
if (!isset($accessToken)) {
if ($fb->getError()) {
header('HTTP/1.0 401 Unauthorized');
$this->Session->setFlash("Error: " . $fb->getError() . "\n", 'error');
$this->Session->setFlash("Error Code: " . $fb->getErrorCode() . "\n", 'error');
$this->Session->setFlash("Error Reason: " . $fb->getErrorReason() . "\n", 'error');
$this->Session->setFlash("Error Description: " . $fb->getErrorDescription() . "\n", 'error');
$this->redirect($this->referer());
} else {
header('HTTP/1.0 400 Bad Request');
$this->Session->setFlash('Bad request', 'error');
$this->redirect($this->referer());
}
}
// Logged in
$oAuth2Client = $this->Facebook->getOAuth2Client();
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
$tokenMetadata->validateAppId('1200125790051089'); // Replace {app-id} with your app id
$tokenMetadata->validateExpiration();
if (!$accessToken->isLongLived()) {
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
$this->Session->setFlash('Error getting long-lived access token: ' . $helper->getMessage() . "</p>\n\n", 'error');
$this->redirect($this->referer());
}
}
$_SESSION['fb_access_token'] = (string) $accessToken;
$fb_access_token = (string) $accessToken;
if (isset($accessToken)) {
try {
// Returns a `Facebook\FacebookResponse` object
$response = $this->Facebook->get('/me?fields=id,first_name,last_name,email', $accessToken);
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
$this->Session->setFlash('Graph returned an error: ' . $e->getMessage(), 'error');
$this->redirect($this->referer());
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
$this->Session->setFlash('Facebook SDK returned an error: ' . $e->getMessage(), 'error');
$this->redirect($this->referer());
}
$fb_user = $response->getGraphUser();
// We will varify if a local user exists first
$local_user = $this->User->find('first', array(
'conditions' => array('facebook_id' => $fb_user['id']),
));
// If exists, we will log them in
if ($local_user) {
$this->Auth->login($local_user['User']);
} else {
// we will create new user with facebook_id and log them in
$data['User'] = array(.........);
// You should change this part to include data validation
$new_user = $this->User->save($data);
$this->Auth->login($new_user['User']);
}
// redirect to profile page here
}
}
}
I've had some issues with the SDK and CakePHP 2.x as well. I wrote a small handler that lets the SDK make use of CakeSession.
You can find it here:
https://github.com/WrDX/FacebookCakeSessionPersistentDataHandler

Catch db error with Doctrine\DBAL\Exception

I want to catch any error (ie: foreign key error) from an insert statement or any other. How can I achive that with use Doctrine\DBAL\Exception?
I have this when I do the insert:
$db->beginTransaction();
try {
$db->insert('bbc5.produccionpry',$datos);
$datos['propryid'] = $db->lastInsertId();
$db->commit();
// $db = null;
$resp[] = $datos;
} catch (Exception $e) {
$error = array_merge($error, array('error' => $e->errorInfo()));
$db->rollback();
throw $e;
}
But, that doesn't prevent the concrete5 to return a website telling about the error, so, I don't want that website to be shown, I want to catch the error in an array() in order to return it via echo json_encode($error)
I'm not using the controller for a page, I'm using it for managing RESTful calls from my JavaScript App with this code:
return fetch(`/scamp/index.php/batchprodpry/${maq}`, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state.a)
})
I'm using ReactJS
Thank you
Don't throw the exception.
Instead of throwing the exception, just get the exceptions message $e->getMessage() from the DBALException $e object and encode it as a JSON string. Important: Put an exit; after the echo to assure that no further code is executed.
use Doctrine\DBAL\DBALException;
try {
$db->insert('bbc5.produccionpry',$datos);
$datos['propryid'] = $db->lastInsertId();
$db->commit();
$resp[] = $datos;
}
catch(DBALException $e){
$db->rollback();
echo \Core::make('helper/json')->encode($e->getMessage());
exit;
}
If this code is inside a page controller you could do this:
try {
$db->insert('bbc5.produccionpry',$datos);
$datos['propryid'] = $db->lastInsertId();
$db->commit();
$resp[] = $datos;
}
catch(DBALException $e){
$this->error->add($e->getMessage());
}
if($this->error->has()) {
// All variables that have been set in the view() method will be set again.
// That is why we call the view method again
$this->view();
return;
}
And concrete5 will take care of displaying an appropriate error message.
Or you could save the $e->getMesssage() in the session and call it inside the view:
$session = \Core::make('session');
// ...
catch(Exception $e){
$session->set('error', $e->getMessage());
}
And in the view:
// html
<?php
$session = \Core::make('session');
if($session->has('error')) {
$m = $session->get('error');
?>
<div id="session_error" class="alert alert-danger">
×
<div id="session_error_msg">
<?php print $m ?>
</div>
</div>
<?php
}
$session->remove('error');
?>
//html
Since you have throw $e in your catch block you throw this exception further which means that it is (probably) handled by global exception listener. Once you throw exception you exit your code immediately, so a solution for you is just remove throw $e line and you should be good

Single Signon with Magento account from drupal

I have custom Magento script file as below which does login by just passing email and password to that PHP file.
It works fine when i'm making a call from browser.
But, I want to make this call through Drupal Module which i have created.
As i expected call is happening from Drupal module and i'm getting success message too. But login is not happening.
My hunch is that magento have some login restrictions which happening outside magento root folder.
Please find the source below.
Drupal directory - /www/drupal/
Magento directory - /www/drupal/store/
/www/drupal/store/api_config.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
require_once (dirname(dirname(realpath(__FILE__))).'/store/app/Mage.php');
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name' => 'frontend'));
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$response = array();
/www/drupal/store/api_login.php
<?php
require_once "api_config.php";
$session = Mage::getSingleton('customer/session');
//$session->start();
if (isset($_GET['email']) && !empty($_GET['email']) && isset($_GET['password']) && !empty($_GET['password'] )) {
if (!filter_var($_GET['email'], FILTER_VALIDATE_EMAIL) === false) {
$email = $_GET['email'];
$password = $_GET['password'];
try {
if ($session->login($email, $password )) {
$response['status'] = 'success';
$response['data'] = array($_GET);
$response['message'] = array('User loggedin Successfully.');
} else {
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('User login failed.');
}
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
} catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
$value = Mage::helper('customer')->getEmailConfirmationUrl($email);
$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', $value);
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
break;
default:
$message = $e->getMessage();
}
//$session->addError($message);
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array($message);
echo $message;
$session->setUsername($email);
} catch (Exception $e) {
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array($e);
// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
}
} else {
//$session->addError('Login and password are required.');
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('Invalid Email address');
}
} else {
//$session->addError('Login and password are required.');
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('Login and password are required.');
}
print_r(json_encode($response, JSON_FORCE_OBJECT));die;
?>
/www/drupal/sites/all/modules/single_signon/single_signon.module
<?php
function single_signon_user_login(&$edit, $account) {
//store variable values
$postData = array();
$postData['email'] = $account->mail;
$postData['password'] = $edit['input']['pass'];
$inc = 1; //count of registration
if (!empty($postData['email']) && !empty($postData['password'])) {
// use of drupal_http_request
$data = http_build_query($postData, '', '&');
//$url = url('http://127.0.0.1/drupal/store/api_login.php?'.$data);
//$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
//print_r($url);
// the actual sending of the data
$JSONresponse = drupal_http_request('http://127.0.0.1/drupal/store/api_login.php?email=john#example.com&password=password');
//print_r($JSONresponse);die;
$response = json_decode($JSONresponse->data, true);
if ($response['status']=='success') {
$inc+=1;
$message = 'Logged in successfully('.$inc.')';
drupal_set_message($message, $type = 'status', $repeat = FALSE); //message goes here
} else {
$message = 'Logged in failed. Due to '.$response['message'].'('.$inc.')';
drupal_set_message($message, $type = 'error ', $repeat = FALSE);
}
} else {
$message = 'Not able to log inside store('.$inc.')';
drupal_set_message($message, $type = 'status', $repeat = FALSE); //message goes here
}
}
?>
Any suggestions for findings to solve this mystery would be really helpful.
I'm not sure to understand it well : You have a php script using data send in the URL (GET) to connect a user in a session. And you would like the Drupal server to use it to connect directly to your Magento.
I think your code is working, but unfortunately it could not help the user to connect to Magento.
As this is the Drupal server asking for the connection, it would be the Drupal server session that will be connected and not the navigation user one.
If the user have to be connected, in his navigator, to the Magento server, it has to be the navigator witch must call the Magento script directly.
It could be done in an iframe or via Ajax I think.
I think you can also find some other solutions, as OAuth, but it will need a lot more of coding.
EDIT
I found some interesting subject about your problem :
Getting logged in user ID from Magento in external script - multiple session issue?
Magento Session from external page (same domain)
Magento external login will not create session cookie
I think you have to manually create the Magento session cookie on the user navigator, from the Drupal script.
You'll need to send back to Drupal the SessionID from Magento, using this method (I think, you'll have to verify) :
$response['sessionId'] = $session->getEncryptedSessionId();
And inside the Drupal script, you'll have to record a new cookie with the Magento session information. Maybe you have to have a look at a working Magento cookie to see how it is defined and what is its name.
if ($response['status']=='success') {
...
setcookie('frontend', $response['sessionId'], time() + 3600 * 24 * 180, '/');
...
}
You'll probably have to declare, in the settings of Magento, the path for cookies at '/'.
Can you give an example of the structure of the session cookie from Magento ?

Resources