404 error occur while calling laravel API from ionic - laravel

i am trying to call API from ionic but it shows 404 error
here is my code for provider
remoteservice.ts
export class RemoteserviceProvider {
public headers = new Headers( { 'X-API-KEY' :
'xxxxxxxxx' });
public options = new RequestOptions({ headers: this.headers });
constructor(public http: Http) {
console.log('Hello RemoteserviceProvider Provider');
}
rec:any[]=[];
use:any[]=[];
login(credentials) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost/my/v1/adminlogin', credentials,
{headers: this.headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
Login.ts
doLogin() {
this.showLoader();
this.remoteService.login(this.loginData).then((result) => {
this.loading.dismiss();
this.responseData = result;
console.log(this.responseData);
if(this.responseData.message=='Login Success'){
localStorage.setItem('loginData', JSON.stringify(this.responseData));
if(this.responseData.user_type==1){
if(this.responseData.project_type==null){
this.presentToast('You are not assigned to any project');
}
else{
if(this.responseData.project_type=='Concrete'){
console.log(this.responseData.p_id)
this.navCtrl.setRoot(ConcretePage,
{p_id:this.responseData.p_id, s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
else if(this.responseData.project_type=='Bricks'){
this.navCtrl.setRoot(ProductionPage,
{p_id:this.responseData.p_id,s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
else{
this.navCtrl.setRoot(DailyReportPage,
{p_id:this.responseData.p_id,s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
}
My API code is laravel
index.php
<?php
//including the required files
require_once '../include/DbOperation.php';
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->hook('slim.before.dispatch', function () use ($app){
$headers = request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
$api_key = $headers['X-API-KEY'];
// this could be a MYSQL query that parses an API Key table, for example
if($api_key == 'xxxxxxxxxxxxxxx') {
$authorized = true;
} else if ($api_key == NULL) {
$response["error"] = true;
$response["message"] = '{"error":{"text": "api key not sent"
}}';
$app->response->headers['X-Authenticated'] = 'False';
$authorized = false;
$app->halt(401, $response['message']);
} else {
$response["error"] = true;
$response["message"] = '{"error":{"text": "api key invalid" }}';
$app->response->headers['X-Authenticated'] = 'False';
$authorized = false;
}
if(!$authorized){ //key is false
// dont return 403 if you request the home page
$req = $_SERVER['REQUEST_URI'];
if ($req != "/") {
$app->halt('403', $response['message']); // or redirect, or
other something
}
}
});
$app->post('/adminlogin', function () use ($app) {
$json = $app->request->getBody();
$input = json_decode($json, true);
$mobile= (int)$input['mobile'];
$password = (string)$input['password'];
$db = new DbOperation();
$response = array();
$response['report'] = array();
if ($db->adminLogin($mobile,$password)) {
$admin = $db->getAdmin($mobile);
$admin1 = $db->getassignedproject($mobile);
$admin2 = $db->getprojecttype($admin1['p_id']);
$admin4 = $db->updateadminlogin($mobile,$password);
$response['error'] = false;
$response['p_id']=$admin1['p_id'];
$response['id'] = $admin['u_id'];
$response['name'] = $admin['username'];
$response['date'] = date('Y-m-d');
$response['user_type'] = $admin['user_type'];
$response['project'] = $admin1['p_name'];
$response['project_type'] = $admin2['p_type'];
$response['location'] = $admin2['location'];
$response['message'] = "Login Success";
} else {
$response['error'] = true;
$response['message'] = "Invalid username or password";
}
echoResponse(200, $response);
});
while am calling API using /adminlogin this shows 404 error
i don't know where i did wrong.
Anyone can please give me some idea to overcome this.
Thanks in Advance

Related

Paypal Integration using vue, axios and laravel api throws 500 internal error

I am making a paypal integration webapp using vue and laravel api. Whenever i trigger post method it shows internal server error 500. Whenever i trigger post method using axios it only catches the error and doesnot complete the functionality i provided. I also dont know to use csrf token in vue . Anyone who can help me with this.
My Vue Code:
PayForPaypal() {
if(this.$refs.form.validate() === true){
let payPalData = {
price: this.plansData.price,
name: this.plansData.name,
}
axios.post("http://localhost:8000/api/payokay", payPalData, {
headers:{
}
}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
}
},
My laravel code:
public function store(Request $request)
{
DB::beginTransaction();
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item_1 = new Item();
$item_1->setName($request->name)
->setCurrency('USD')
->setQuantity(1)
->setPrice($request->price);
$item_list = new ItemList();
$item_list->setItems(array($item_1));
$amount = new Amount();
$amount->setCurrency('USD')
->setTotal($request->price);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
->setDescription('Awebly ' . $request->name);
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl('http://localhost:8080/Plans')
->setCancelUrl('http://localhost:8080/Plans');
$payment = new Payment();
$payment->setIntent('Sale')
->setPayer($payer)
->setRedirectUrls($redirect_urls)
->setTransactions(array($transaction));
try {
$payment->create($this->_api_context);
$payment_details = new PaymentDetail();
$payment_details->payment_method = 'Paypal';
$payment_details->plan = $request->name;
$payment_details->payment_id = $payment->getId();
$payment_details->amount = $request->price;
$payment_details->user_name = auth()->user()->name;
$payment_details->user_id=auth()->user()->id;
$payment_details->save();
} catch (\PayPal\Exception\PPConnectionException $ex) {
DB::rollBack();
if (Config::get('app.debug')) {
return response(
[
'message'=>'connection timeout'
]
);
} else {
return response(
[
'message'=>'error'
]
);
}
}
DB::commit();
foreach ($payment->getLinks() as $link) {
if ($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
if (isset($redirect_url)) {
return redirect($redirect_url);
}
return response(
[
'message'=>'unknown error occurred'
]
);
}
I dont know what is the mistake. Any help are appreciated.

Call to undefined function GuzzleHttp\\Psr7\\build_query()

I have searched online but could not get a solution. I know I have done some small mistakes. I generated my code with openapi-generator. I had a directory at nova-components root named as RegistroImprese I made another directory SevenData and moved all RegistroImprese into this new directory. I have gone through quite a lot of problems but fixed them. Until then my code was working fine. But now it's throwing an exception that query_build is undefined but this same function was working fine earlier. Nothing has helped me. Any help would be appreciated.
public function apiRegistroImpresePostRequest($request = null)
{
$resourcePath = '/api/RegistroImprese';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json'],
['application/json-patch+json', 'application/json', 'text/json', 'application/_*+json']
);
}
// for model (json/xml)
if (isset($request)) {
if ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($request));
} else {
$httpBody = $request;
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
foreach ($formParamValueItems as $formParamValueItem) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValueItem
];
}
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'POST',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
This problem was solved by using Query::build. After Guzzle 7.2 build_query()was deprecated.

Check if record exists Before Insertion using laravel

I want to check record is_featured is a column name if any product is is_featured 1 is already exist error message should be shown Trying to assign an already assigned featured
how can i do that please help me thanks.
https://ibb.co/1Zv2KBW
controller
public function featured(Request $request)
{
if ($request->id) {
$featured = $request->input('is_featured');
$assignFeature = Product::where('is_featured', '=', $featured)->first();
if ($assignFeature) {
abort(405, 'Trying to assign an already assigned featured');
}
} else {
$response['is_featured'] = false;
$response['message'] = 'Oops! Something went wrong.';
$id = $request->input('id');
$featured = $request->input('is_featured');
$featureditem = Product::find($id);
if ($featureditem->update(['is_featured' => $featured])) {
// form helpers.php
logAction($request);
$response['is_featured'] = true;
$response['message'] = 'product featured updated successfully.';
return response()->json($response, 200);
}
return response()->json($response, 409);
}
}
ajax script
$('.postfeatured').change(function () {
var $this = $(this);
var id = $this.val();
var is_featured = this.checked;
if (is_featured) {
is_featured = 1;
} else {
is_featured = 0;
}
axios
.post('{{route("product.featured")}}', {
_token: '{{csrf_token()}}',
_method: 'patch',
id: id,
is_featured: is_featured,
})
.then(function (responsive) {
console.log(responsive);
})
.catch(function (error) {
console.log(error);
});
});
remove this abort()
if ($assignFeature) {
//abort(405, 'Trying to assign an already assigned featured'); //remove this
$response['is_featured'] = false;
$response['message'] = 'Trying to assign an already assigned featured.';
return response()->json($response, 200);
}
Try this:
$product_created_status = $product->wasRecentlyCreated ? 1 : 0 ;
if product is already created it returns 0, else returns 1

AJAX POST request not working with XMLHttpRequest in Laravel

I'm using XMLHttpRequest to avoid using JQuery and I wanna make an Ajax request to delete an object but I keep getting redirected back and getting FOUND (302) HTTP errors.
This is my code:
function deleteGuia(urlToSend) {
var borra = confirm('¿Está seguro de borrar la guía?');
if (!borra) {
return;
}
var req = new XMLHttpRequest();
var csrfToken = document.querySelector('meta[name="csrf-token"]').content;
req.open("POST", urlToSend, true);
req.setRequestHeader('X-CSRF-TOKEN', csrfToken);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (this.readyState === this.DONE) {
console.log(this.responseURL);
}
if (req.status != 200) {
var msg = JSON.parse(req.response);
alert(msg.error);
} else {
alert('Exitoso');
}
}
}
var data = new FormData();
var guia = "{{$guia ?? ''}}";
var estado = "{{$tipo ?? ''}}";
data.append("guia", guia);
data.append("tipo", estado);
req.send(data);
}
</script>
This one's the controller function:
public function eliminarGuia(Request $request) {
$request->validate([
'guia' => 'required|numeric',
'tipo' => 'required'
]);
$guia = (int)$request->input('guia');
$tipo = $request->input('tipo');
\Log::info('Guia' . $guia . ' Tipo: '. $tipo);
if (strtoupper($tipo) === 'ENTREGA'){
$borra_guia = Guia::where('guia', $guia)->where('estado', $tipo)->delete();
$borra_ciclos = Device::where('guia_recepcion', $guia)->delete();
if(!$borra_guia) {
return response(400)->json(['error', 'La guía no se encontró.']);
}
} else if (strtoupper($tipo) === 'REVERSA') {
$borra_guia = Guia::where('guia', $guia)->where('estado', $tipo)->delete();
$devices = Device::where('guia_reversa', $guia)->get();
if (!$borra_guia){
return response(400)->json(['error', 'La guía no se encontró.']);
}
foreach($devices as $device)
{
if (!$device->fecha_recepcion) {
$device->delete();
} else {
$device->guia_reversa = 0;
$device->fecha_reversa = null;
$device->save();
}
}
} else {
return response(400)->json(['error', 'La guía no se encontró.']);
}
return response(200);
}
web.php
Route::post('borrar_guia', 'VistasController#eliminarGuia')->name('borrar_guia');
There's no redirection at all. Why might that be happening? I don't know what else to add. The controller should return a 200 code when it delets an existing object in the database but it's getting a 200 from the redirection.

Check customer email is already exist in magento using ajax prototype

I want to check customer email is already exist or not using ajax prototype. I tried lots of things but it is not working. I write my code like this.
<script type="text/javascript">
//<![CDATA[
var dataForm = new VarienForm('form-validate', true);
Validation.add('validate-emaila', 'Email already exist', function(v) {
var url = '/customer/account/checkEmail/email?email=' + encodeURIComponent(v);
var ok = false;
new Ajax.Request(url, {
method: 'get',
asynchronous: false,
onSuccess: function(transport) {
alert(transport.responseText);
var obj = response = eval('(' + transport.responseText + ')');
validateTrueEmailMsg = obj.status_desc;
if (obj.ok === false) {
Validation.get('validate-email').error = validateTrueEmailMsg;
ok = false;
} else {
ok = true; /* return true or false */
}
},
onFailure: function(){ alert('something wrong') },
onComplete: function() {
if ($('advice-validate-email-email')) {
$('advice-validate-email-email').remove();
}
if ($('advice-validate-email-email_address')) {
$('advice-validate-email-email_address').remove();
}
if ($('advice-validate-email-billing:email')) {
$('advice-validate-email-billing:email').remove();
}
if ($('advice-validate-email-shipping:email')) {
$('advice-validate-email-shipping:email').remove();
}
if ($('advice-validate-email-_accountemail')) {
$('advice-validate-email-_accountemail').remove();
}
}
});
return ok;
});
//]]>
</script>
I called a function In customer/accountcontroller
public function checkEmailAction()
{
$bool = 0;
$email = $this->getRequest()->getParam('email');
$customer = Mage::getModel('customer/customer');
$customer->loadByEmail($email);
if ($customer->getId()) {
$bool = 1;
}
$jsonStatus = 200;
$info = array( "status" => $bool);
$this->getResponse()->setBody(json_encode($info))->setHttpResponseCode($jsonStatus)->setHeader('Content-type', 'application/json', true);
return $this;
}
I am getting wrong response from php function. it is returning full page html. instead of 0 or 1.
I have tried lots of thing but giving same response. Can any one tell me what is wrong in this?
it is wrong code for checking customer.You need to add website id to customer load
First need to change customer check url move from customer accountcontroller.php to checkout onepagecontroller.php. Because magento cannot easly add to accountcontroller.php
url ='<?php echo $this->getUrl('checkout/onepage/checkEmail', array('_secure'=>true)); ?>'
var request = new Ajax.Request(
url,
{
method:'get',
parameters: {email:encodeURIComponent(v)}
onSuccess: function(transport)
{
if(transport.status == 200)
{
var data = transport.responseText.evalJSON();
if(data.success==true){
}
}
}
}
);
In checkout onepagecontroller.phpadd the below code
public function forcecheckAction()
{
$response=array();
$email = $this->getRequest()->getParam('email');
try{
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email); //load customer by email i 
/* if customer has ,then login */
if($customer->getId()>0){
$response['success'] = true;
}else{
$response['success'] = false;
}
}catch(Exception $e)
{
$response['success'] = false;
$response['message'] = $e->getMessage();
}
$this->getResponse()->setBody(Zend_Json::encode($response));
}

Resources