I am kind of new with laravel and currently I am working on an android application where I have to call a laravel controller.
I was trying to call a function (just returning a string, the name of the function is androidTest) from android but each time it ended up throwing an exception
java.io.FileNotFoundException:http://192.168.0.104/LaravelAjaxRes/public/getRequest
I checked the URL properly, its perfectly ok. I also disabled CSRF verification but still it did not work!
Can anyone tell what I am missing and is there any tutorial or something that can help me? Thanks in advance.
Controller code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
class getRegistrationData extends Controller
{
public function index(Request $request)
{
if($request->ajax()){
$data = json_encode($request->all());
$parse = json_decode($data);
$teachers_name_array = $this->splitTeacherName($parse->teacher);
$teacher_id = $this->getTeacherID($teachers_name_array);
DB::table('lessons')->insert(
['title' => $parse->title, 'description' => $parse->description,'teacher_id' => $teacher_id]
);
}
else{
}
}
public function getTeachersData(Request $request)
{
if($request->ajax()){
$teachers = DB::table('teachers')->select('firstname', 'lastname')->get();
return $teachers;
}
else{
//$teachers = DB::table('teachers')->select('firstname', 'lastname')->get();
}
}
public function androidTest()
{
echo 'Some Text';
}
public function splitTeacherName($teacher_full_name)
{
return explode(" ", $teacher_full_name);
}
public function getTeacherID($teachers_name_array)
{
$matchNames = ['firstname' => $teachers_name_array[0], 'lastname' => $teachers_name_array[1]];
$result = DB::table('teachers')->select('id')->where($matchNames)->get();
foreach ($result as $t_id)
{
$teacher_id = $t_id->id;
}
return $teacher_id;
}
public function getLessonData(Request $request)
{
if($request->ajax()){
$lessons =
DB::select(DB::raw('SELECT d1.* ,d2.* from teachers d1 INNER JOIN lessons d2 where d1.id = d2.teacher_id'));
return $lessons;
}
else{
return null;
}
}
}
route code:
`Route::get('/', function () {
return view('welcome');
});
Route::post('/register','getRegistrationData#index');
Route::get('/getRequest','getRegistrationData#androidTest');
Route::get('/getLessonRequest','getRegistrationData#getLessonData');`
Related
I tried to get a collection of documents from firestore via firebase function.firebase function console displays the json data of documents and returned that data to android app but firebase function callable gets null value.can you help me how to receive the documents data in android app.
I even followed this Question for answer but still i receive null value in my app.
export const getproducts = functions.https.onCall((data, context)=>{
let productarray = [];
const productref = admin.firestore().collection("Products")
.orderBy("product_id").limit(2);
productref.get()
.then((DataSnapshot) => {
productarray=DataSnapshot.docs.map((doc) => {
return doc.data();
});
console.log("products returned.", JSON.stringify(productarray));
return JSON.stringify(productarray);
}).catch((error)=> {
throw new functions.https.HttpsError("unknown", error.message, error);
});
});
my code for retreiving the data from android app
mFunctions = FirebaseFunctions.getInstance();
return mFunctions
.getHttpsCallable("getproducts")
.call()
.addOnSuccessListener(new OnSuccessListener<HttpsCallableResult>() {
#Override
public void onSuccess(HttpsCallableResult httpsCallableResult) {
try {
Gson g = new Gson();
String json = g.toJson(httpsCallableResult.getData());
ProductModel productModel = g.fromJson(json,ProductModel.class);
Log.e("getproducts",productModel.getProduct_id()); //i get null value here.
} catch (Exception e) {
Log.d("Error", e.toString());
}
}
});
document that displayed in console:
10:49:59.240 AM
getproducts
products returned. [{"cutted_price":100,"dress_color":"blue","product_id":"000001"},{"cutted_price":500,"dress_color":"gray","product_id":"000002"}]
Your Cloud Function is missing a return statement.
// ...
productref.get()
.then((DataSnapshot) => {
// ...
should be
// ...
return productref.get() // <----
.then((DataSnapshot) => {
// ...
This question already has answers here:
Why does my function that calls an API or launches a coroutine return an empty or null value?
(4 answers)
Closed 1 year ago.
What I am trying to do: Simply return data from Firebase Cloud Function.
The function is used to create a payment order in the payment gateway's server.
My required data about the order's details are present in the function(err,data) (see below), but I need this data sent back to my Android app.
Problem I faced: I could see the data printed in the Firebase console's log but it doesn't return to my Android app.
My Firebase Cloud Function:
const functions = require("firebase-functions");
exports.order = functions.https.onCall((amnt, response) => {
const Ippopay = require('node-ippopay');
const ippopay_instance = new Ippopay({
public_key: 'YOUR_PUBLIC_KEY',
secret_key: 'YOUR_SECRET_KEY',
});
ippopay_instance.createOrder({
amount: amnt,
currency: 'DOLLAR',
payment_modes: "cc,dc,nb,cheque",
customer: {
name: "Test",
email: "test#gmail.com",
phone: {
country_code: "42",
national_number: "4376543210"
}
}
}, function (err, data) {
return data.order.order_id;
});
});
My Android client-side code:
public class Payment extends AppCompatActivity implements IppoPayListener {
Button pay;
EditText amount;
private FirebaseFunctions mFunctions;
TextView order_data;
String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
pay=findViewById(R.id.pay_button);
amount=findViewById(R.id.user_amount);
order_data=findViewById(R.id.data_text);
pay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("PAY Button clicked", "yes");
mFunctions = FirebaseFunctions.getInstance("us-central1");
mFunctions.getHttpsCallable("order").call(5).continueWith(new Continuation<HttpsCallableResult, Object>() {
#Override
public Object then(#NonNull Task<HttpsCallableResult> task) throws Exception {
HttpsCallableResult result=task.getResult();
if(result !=null)
{
data=result.getData().toString();
return result.getData().toString();
}
return null;
}
});
order_data.setText(data);
onPaymentClick();
}
});
}
/* ... */
}
I'm a Beginner so there's a high possibility of some dead silly mistakes. :)
Based on what your code looks like at the moment, you have a mix of code from a Callable Cloud Function and the older HTTP Request Cloud Function.
To return data from a callable Cloud Function, you should return a Promise, a method of running asynchronous code that returns a value. Older JavaScript and many other languages use callbacks instead, which is what you have here.
In it's simplest form, this callback-based method:
someModule.doSomething(input, function (err, result) {
// check for errors and handle result
});
would be converted to use Promises using:
new Promise((resolve, reject) => {
someModule.doSomething(
input,
(err, result) => err ? reject(err) : resolve(result) // short form of "if error, reject with an error, otherwise resolve (succeed) with result"
)
});
For errors to be handled correctly by clients, you need to wrap any errors in a functions.https.HttpsError.
Combining this together gives:
const functions = require("firebase-functions");
exports.order = functions.https.onCall((amnt, context) => {
const Ippopay = require('node-ippopay');
return new Promise((resolve, reject) => {
const ippopay_instance = new Ippopay({
public_key: 'YOUR_PUBLIC_KEY',
secret_key: 'YOUR_SECRET_KEY',
});
ippopay_instance.createOrder({
amount: amnt,
currency: 'DOLLAR',
payment_modes: "cc,dc,nb,cheque",
customer: {
name: "Test",
email: "test#gmail.com",
phone: {
country_code: "42",
national_number: "4376543210"
}
}
}, function (err, data) {
if (err) {
// something went wrong, send error back to caller
reject(new functions.https.HttpsError('unknown', 'Ippopay threw an unexpected error', err));
return;
}
// successful, send data back to caller
resolve(data.order.order_id);
});
});
});
You should also make sure you make use of context.auth to restrict access to this function. You wouldn't want to bill the wrong customer.
Im working on my first Ionic + Firebase project, and im not understanding this:
Im searching and getting an object from firebase, I can access its details on html and show it to the user.
But now I need to save the createdBy field on that object so I can use it to search for its creator on firebase.
But when I try to access that info its always undefined. Why is that? Any tips on how to fix this?
export class VisitDetailsPage implements OnInit {
public trips: Observable<HomeTripCardsModel>;
public trip: HomeTripCardsModel;
public buddyInfo;
public targetBuddyId: any;
constructor(private router: Router, private navCtrl: NavController,
public fireStorageService: FireStorageService,
private route: ActivatedRoute, public db: AngularFirestore) {
}
ngOnInit() {
const tripId: string = this.route.snapshot.paramMap.get('id');
this.db.collection('users').get()
.subscribe(querySnapshot => {
querySnapshot.forEach(doc => {
this.trips = this.fireStorageService.getTripDetail(tripId, doc.id);
this.trips.forEach((element: HomeTripCardsModel) => {
if (element?.id === tripId) {
this.trip = element;
this.targetBuddyId = element.createdBy;
}
});
});
});
// buddy
console.log(this.trip?.createdBy); // returns undefined
console.log('saved ', this.targetBuddyId) // returns undefined
}}
Data is loaded from Firebase asynchronously. If you set some breakpoints and run in the debugger, or add a log inside the subscribe method, you'll see that your console.log(this.trip?.createdBy) runs before this.trip = element has ever been run. So at that point, it indeed doesn't have a value yet.
For this reason, all code that needs data from the database, needs ot be inside the subscribe callback:
this.db.collection('users').get()
.subscribe(querySnapshot => {
querySnapshot.forEach(doc => {
this.trips = this.fireStorageService.getTripDetail(tripId, doc.id);
this.trips.forEach((element: HomeTripCardsModel) => {
if (element?.id === tripId) {
this.trip = element;
this.targetBuddyId = element.createdBy;
}
});
// buddy
console.log(this.trip?.createdBy); // returns undefined
console.log('saved ', this.targetBuddyId) // returns undefined
});
});
I am using firebase cloud functions as serverside for Paypal payment. Documentations are not obvious to understand.
when I am trying to send an object from android app to firebase cloud functions, nothing has happened. I think I added it wrong. so how can I pass an object from android app to the function??
public void payout(String PayerID,String paymentId) {
// Create the arguments to the callable function.
JSONObject postData = new JSONObject();
try {
postData.put("PayerID", PayerID);
postData.put("paymentId",paymentId);
} catch (JSONException e) {
e.printStackTrace();
}
mFunctions
.getHttpsCallable("payout")
.call(postData)
.continueWith(new Continuation<HttpsCallableResult, Object>() {
#Override
public Object then(#NonNull Task<HttpsCallableResult> task)
throws Exception {
return null;
}
});
}
///////////////////////////////////////////
exports.payout=functions.https.onRequest((req,res)=>{
const sender_batch_id = Math.random().toString(36).substring(9);
const payReq=JSON.stringify({
sender_batch_header: {
sender_batch_id: sender_batch_id,
email_subject: "You have a nice payment"
},
items: [
{
recipient_type: "EMAIL",
amount: {
value: 0.90,
currency: "USD"
},
receiver: "amrmahmoudM#app.com",
note: "Thank you very much.",
sender_item_id: "item_3"
}
]
});
paypal.payout.create(payReq,(error, payout)=>{
if (error) {
console.warn(error.res);
res.status('500').end();
throw error;
}else{
console.info("payout created");
console.info(payout);
res.status('200').end();
}
});
});
exports.process = functions.https.onRequest((req, res) => {
const paymentId = req.body.paymentId;
var payerId = {
payer_id: req.body.PayerID
};
return paypal.payout.execute(paymentId, payerId, (error, payout) => {
if (error) {
console.error(error);
} else {
if (payout.state === 'approved') {
console.info('payment completed successfully, description: ',
payout.transactions[0].description);
const ref=admin.firestore().collection("Users").doc(payerId);
ref.set({'paid': true});
} else {
console.warn('payment.state: not approved ?');
}
}
}).then(r =>
console.info('promise: ', r));
});
The problem comes from the fact that in your Android app you call an HTTPS Callable Function (via mFunctions.getHttpsCallable("payout")) but your Cloud Function is not an HTTPS Callable Function but a "simple" HTTPS Function.
HTTPS Callable Functions are written like:
exports.payout = functions.https.onCall((data, context) => {
// ...
});
while HTTPS Functions are written like:
exports.payout = functions.https.onRequest((req,res)=> {
// ...
})
So you should adapt the code of your Cloud Function according to the documentation: https://firebase.google.com/docs/functions/callable
Note that another option could be to write to the database (Real Time database or Firestore) and trigger the Cloud Function with an onWrite or onCreate trigger. The advantage of this approach is that you directly save the information of the payment in the database.
I am working on a ionic project and trying to use LokiJS. Below is my code,
controller,
$scope.test ={birthdays:[]};
$ionicPlatform.ready(function() {
BirthdayService.initDB();
BirthdayService.getAllBirthdays().then(function(birthdays){
console.log("birthdays=",birthdays);// gives empty array second run...
//var bday1 = {Name:"abrj",Date:new Date()};
//var bday2 = {Name:"abrj2",Date:new Date()};
//BirthdayService.addBirthday(bday1);
//BirthdayService.addBirthday(bday2); added birthdays during the first run.
});
});
I am using cordova-fs-adapter and cordova-file-plugin.
below is my service for adapter integration,
(function() {
angular.module('starter').factory('BirthdayService', ['$q', 'Loki', BirthdayService]);
function BirthdayService($q, Loki) {
var _db;
var _birthdays;
function initDB() {
var fsAdapter = new LokiCordovaFSAdapter({"prefix": "loki"});
_db = new Loki('birthdaysDB',
{
autosave: true,
autosaveInterval: 1000, // 1 second
adapter: fsAdapter
});
};
function getAllBirthdays() {
return $q(function (resolve, reject) {
var options = {
birthdays: {
proto: Object,
inflate: function (src, dst) {
var prop;
for (prop in src) {
if (prop === 'Date') {
dst.Date = new Date(src.Date);
} else {
dst[prop] = src[prop];
}
}
}
}
};
_db.loadDatabase(options, function () {
_birthdays = _db.getCollection('birthdays');
if (!_birthdays) {
_birthdays = _db.addCollection('birthdays');
}
resolve(_birthdays.data);
});
});
};
function addBirthday(birthday) {
console.log("Birthdays=",_birthdays);
_birthdays.insert(birthday);
};
function updateBirthday(birthday) {
_birthdays.update(birthday);
};
function deleteBirthday(birthday) {
_birthdays.remove(birthday);
};
return {
initDB: initDB,
getAllBirthdays: getAllBirthdays,
addBirthday: addBirthday,
updateBirthday: updateBirthday,
deleteBirthday: deleteBirthday
};
}
})();
In first run I am inserting two documents into the birthdays collections.On second run when I trying to check whether they have persisted, they weren't. I know I am doing something wrong.Do suggest.Local storage also gets cleared everytime i rerun(ionic run android)?!