I setup future payment in my laravel app with stripe. However, after following stripe integration from stripe official doc I encountered this error response.
Here's my script:
<script>
var stripeSetupIntent = function (stripe, setupIntent) {
const email = document.getElementById("stripe-email").value;
stripe.confirmCardSetup(setupIntent.client_secret,
{
payment_method: {
card: card,
billing_details: {
name: email,
},
},
}
).then(function(result) {
if (result.error) {
// Display error.message in your UI.
console.log('Error: ', result.error)
// var displayError = document.getElementById("card-errors");
// displayError.textContent = result.error.message;
} else {
console.log('Sucess')
// The setup has succeeded. Display a success message.
}
});
};
var getSetupIntent = function(stripe) {
axios.post('/api/createcustomerinstripe').then(function (response) {
console.log('getSetupIntent: ', response.data.setupIntent)
stripeSetupIntent(stripe, response.data.setupIntent)
})
};
$(document).ready(function () {
let stripe = null;
//get stripe public key
axios.get('/api/stripe-key').then(function (response) {
stripe = Stripe(response.data.publicKey);
const elements = stripe.elements();
const card = elements.create('card');
card.mount('#card-element');
})
var button = document.getElementById("savecard");
button.addEventListener("click", function(event) {
event.preventDefault();
// changeLoadingState(true);
getSetupIntent(stripe)
});
})
</script>
Backend code:
Controller:
public function getStripeKey()
{
$publicKey = env('STRIPE_KEY');
$data = [
'message' => 'Stripe key successfully retrieved.',
'publicKey' => $publicKey
];
return response()->json($data, 200, [], JSON_PRETTY_PRINT);
}
public function CreateCustomerInStripe()
{
Stripe::setApiKey(env('STRIPE_SECRET'));
$customer = Customer::create([
'email' => auth()->user()->email
]);
$setupIntent = SetupIntent::create([
'customer' => $customer->id
]);
$data = [
'message' => 'A new SetupIntent was created.',
'setupIntent' => $setupIntent
];
return response()->json($data, 200, [], JSON_PRETTY_PRINT);
}
Backend code web:
Route::get('stripe-key', 'api\StripePaymentController#getStripeKey')->name('stripe.key');
Route::post('createcustomerinstripe', 'api\StripePaymentController#CreateCustomerInStripe')->name('createcustomerinstripe');
I use the stripe documentation here https://stripe.com/docs/payments/save-and-reuse#web-test-integration
stripe version:
<script src="https://js.stripe.com/v3/"></script>
laravel version:
https://laravel.com/docs/7.x/billing
Related
I am using FullCalendar in laravel 8 project and I use it to display all the events from the database.
This is the code:
My controller
public function index(Request $request, $id) {
$patient = [];
$listOfPatients = [];
$appointments = [];
//apply permission constraits
$patient = Patient::find($id);
$listOfPatients = Patient::all();
$appointments = appointments::all();
$this->authorize('view', $patient);
// $appointments = $patient->remarks()->get()->sortBy([['id', 'desc']]);
if($request->ajax()) {
$data = appointments::whereDate('start', '>=', $request->start)
->whereDate('end', '<=', $request->end)
->get(['id', 'title', 'description', 'start', 'end']);
return response()->json($data);
}
return view('patient.appointments', [ "appointments" => $appointments, "patient" => $patient, "listOfPatients" => $listOfPatients]);
}
My js
$(document).ready(function () {
var SITEURL = "{{ url('/') }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#full_calendar_events').fullCalendar({
editable: false,
editable: false,
eventSources: [
{
url: '/{id}/appointments',
color: '#65a9d7', // an option!
textColor: '#3c3d3d' // an option!
}
],
});
});
I also got this error:
jquery.min.js:4 GET http://127.0.0.1:8000/%7Bid%7D/appointments?start=2022-02-27&end=2022-04-10&_=1648373948124 404 (Not Found)
I am looking to download an image stored on a server into my React Native app.
I had a function that looked like this:
public function image(Request $request, $id)
{
$company = Company::find($id);
$filePath = storage_path() . '/app/' . $company->image;
return response()->file($filePath);
}
And it returned nothing I could read within the app when I tried the following function:
setCompany = async () => {
let company = await AsyncStorage.getItem('currentCompany');
company = JSON.parse(company);
if (company.image !== null) {
let image = await getCompanyPicture({company_id: company.id});
console.log('Here: ', image);
// This is blank, react native returns a warning about data not being of a readable type
}
this.setState({company});
};
I am able to get the image in base_64 using this method:
public function image(Request $request, $id)
{
$company = Company::find($id);
$file_path = storage_path('/app/' . $company->image);
if (file_exists($file_path)) {
$fileData = file_get_contents($file_path);
$fileEncode = base64_encode($fileData);
return response()->json(['status' => 'success', 'data' => ['file' => $fileEncode, 'file_path' => $file_path]]);
}
return response()->json(['status' => 'failure', 'data' => ['file' => null, 'file_path' => $file_path]]);
}
Here is my Axios method too just in case:
export const sendRequest = async (url, data, token, method) => {
let headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Method': 'POST, GET, DELETE, PUT',
};
if (typeof token !== 'undefined' && token !== 'undefined' && token.length) {
headers.Authorization = 'Bearer ' + token;
}
if (method === 'get' && data) {
url +=
'?' +
Object.keys(data)
.map((value) => {
return value + '=' + data[value];
})
.join('&');
data = null;
}
return await axios({
headers: headers,
method: method ? method : 'post',
url: url,
data: data,
})
.then((response) => {
return response;
})
.then((json) => {
return json.data;
})
.catch((error) => {
console.error(error);
if (
error.message !== 'Network Error' &&
error.response.status !== 500 &&
error.response.status !== 413
) {
return error.response.data;
} else if (error.message === 'Network Error') {
return {
status: 'error',
message: 'Unable to connect to server',
};
} else if (error.response.status === 500) {
return {
status: 'error',
message: 'Internal Server Error',
};
} else if (error.response.status === 413) {
return {
status: 'error',
message: 'The file(s) size is too large',
};
} else {
return {
status: 'error',
message: error.message,
};
}
});
};
If anyone could comment on the performance impact of using base_64 instead of the straight file download that would also be helpful
But ultimately I would like a solution for handling the Laravel response()->file() if possible (which I'll use if base_64 is less efficient)
I'm not sure about RN code syntax, but I've ready code with jQuery+poorJS, which looks like this:
$.ajax({
url: "load-image-url", // URL FOR GET REQUEST
cache:false,
xhr: function() { // ACTUALLY THIS PART CAN BE USED AND CUSTOMIZED BY YOU
let xhr = new XMLHttpRequest();
xhr.responseType= 'blob'
return xhr;
},
success: function(data) {
let url = window.URL || window.webkitURL;
$('#image').attr('src', url.createObjectURL(data));
},
error: function(err) {
// console.log(err);
}
}).fail(function() {
$('#ss_product_image').attr('src', "default-image-url.jpg");
});
In my example I've used GET request (but you can try to modify it and test if you want, honestly IDK about that).
This is the back-end part:
public function image(Request $request, $id)
{
// HERE YOU NEED TO GET YOUR IMAGE (using $id or/and $request params) CONTENT FROM SOMEWHERE YOU WANT
$content = <CONTENT>;
return response()->make($content, 200, [
'Content-Type' => (new \finfo(FILEINFO_MIME))->buffer($content),
'Content-length' => strlen($content),
]);
}
I was able to solve this issue by using rn-blob-fetch.
The files are downloaded into a temp cache which can then be accessed for previewing and saving.
this is my function now:
downloadFiles = async (isReply) => {
let {enquiry, reply} = this.state;
this.setState({isLoading: true});
const token = await AsyncStorage.getItem('userToken');
let filePaths = [];
let fileCount = 0;
let files = enquiry.files;
if (isReply) {
files = reply.files;
}
const dirToSave =
Platform.OS == 'ios'
? RNFetchBlob.fs.dirs.DocumentDir
: RNFetchBlob.fs.dirs.DownloadDir;
new Promise((resolve, reject) => {
for (var i = 0; i < files.length; i++) {
var id = files[i].file_id;
var name = files[i].file.file_name;
var ext = extension(name);
const configOptions = Platform.select({
ios: {
appendExt: ext,
fileCache: true,
title: name,
path: `${dirToSave}/${name}`,
},
android: {
useDownloadManager: true,
notification: true,
mediaScannable: true,
fileCache: true,
title: name,
path: `${dirToSave}/${name}`,
},
});
var mime = content(ext);
let headers = {
'Content-Type': mime,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Method': 'POST, GET, DELETE, PUT',
Authorization: 'Bearer ' + token,
};
RNFetchBlob.config(configOptions)
.fetch('GET', BASE_API + '/enquiries/files/download/' + id, headers)
.then(async (response) => {
RNFetchBlob.fs.writeFile(
configOptions.path,
response.data,
'base64',
);
filePaths.push({
title: configOptions.title,
path: configOptions.path,
ext: extension(configOptions.title),
mime,
});
fileCount++;
if (fileCount >= files.length) {
resolve('Download Successful!');
}
})
.catch((error) => {
console.log('File Download Error: ', error.message);
reject('Download Failed');
});
}
})
.then((data) => {
this.setState({isLoading: false, filePaths});
})
.catch((error) => {
console.log('Download Promise Error: ', error);
this.setState({isLoading: false});
});
};
previewDocument = (id) => {
let {filePaths} = this.state;
if (Platform.OS == 'ios') {
RNFetchBlob.ios.openDocument(filePaths[id].path);
} else if (Platform.OS == 'android') {
RNFetchBlob.android.actionViewIntent(
filePaths[id].path,
filePaths[id].mime,
);
}
};
i am new at laravel ,when i enable switch popup message is working perfectly but I don't want to show error popup message when i disable to switch please how can i do that help me thanks.
Does Anyone have an idea please help me thank.
CONTROLLER
public function featured(Request $request)
{
if ($request->is_featured) {
$assignFeature = Product::where('is_featured', 1)->exists();
if ($assignFeature) {
$response['error'] = 'Product is already featured';
return response()->json($response, 422);
}
}
$id = $request->input('id');
$featured = $request->input('is_featured');
$featurediItem = Product::find($id);
if ($featurediItem->update(['is_featured' => $featured])) {
// form helpers.php
logAction($request);
$response['is_featured'] = true;
$response['message'] = 'product featured updated successfully.';
return response()->json($response, 200);
}
}
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,
})
swal({
text: "Product is already featured",
type: 'error',
confirmButtonColor: '#4fa7f3',
})
.then(function (responsive) {
console.log(responsive);
})
.catch(function (error) {
console.log(error);
});
});
you can use axios.post.then method to work after getting response success fully. Something like this
axios.post('/login', {
firstName: 'Finn',
lastName: 'Williams'
})
.then((response) => {
swal({
text: "Product is already featured",
type: 'error',
confirmButtonColor: '#4fa7f3',
})
}
here you can use your response variable to check if is_featured true do something what you want
I created a simple system for commenting posts or videos. Everything works fine.
A function called loadComments() shows comments related to posts or videos.
When a user submits a new comment, the comment is created, but in order to view the new comment I have to refresh the page because I receive an undefined response.
Here the store function in the controller
public function store(Request $request)
{
$comments = Comment::create([
'comment' => $request->comment,
'user_id' => auth()->user()->id,
'post_id' => $request->post_id
]);
return response()->json([
'comments' => $comments,
'success' => 'Comment created successfully!'
],200);
}
Here the addComment method:
addNewComment() {
const formData = {
comment: this.comment,
post_id: this.propsVideoid
}
axios
.post(this.commentsUri, formData)
.then(response => {
this.comments.unshift(response.data.comments)
})
.catch(error => {
this.errors = [];
if(error.response.status == 422) {
this.errors = error.response.data.errors;
}
})
},
Here the load and add methods together
addNewComment() {
const formData = {
comment: this.comment,
post_id: this.propsVideoid
}
axios
.post(this.commentsUri, formData)
.then(response => {
this.comments.unshift(response.data.comments)
})
.catch(error => {
this.errors = [];
if(error.response.status == 422) {
this.errors = error.response.data.errors;
}
})
},
loadComments() {
axios.get(this.commentsListUri, {
params: {
post_id: this.propsVideoid
}
}).then(response => {
this.comments = response.data.comments;
});
},
},
mounted() {
this.loadComments();
}
The addNewComment() method inserts the new comment in the database, but it does not return any json response.
Before everything, this is not duplicate.
How can i get my Axios parameters from URL for my GET request?
Example:
Link : http://127.0.0.1:8000/callback?Authority=000000000000000000000000000107041762&Status=OK
So parameters are Authority And Status
Authority: How to get this parameters from url
Status: How to get this parameters from url
I'm using laravel & vue.js which the codes are :
callback.vue:
<template>
<div>
TEXT
</div>
</template>
<script>
export default {
name: "callback",
data () {
return {}
},
methods: {
loadData(){
axios.get("api/callback", {
Authority: ,
Status
})
.then(({ data }) => (
console.log(data)
));
},
},
created() {
this.loadData();
}
}
Controller function :
public function order(Request $request){
$MerchantID = 'xxxx';
$Authority =$request->get('Authority') ;
$Amount = 111 ;
if ($request->get('Status') == 'OK') {
$client = new nusoap_client('https://localhost/ices/WebGate/wsdl', 'wsdl');
$client->soap_defencoding = 'UTF-8';
$result = $client->call('PaymentVerification', [
[
'MerchantID' => $MerchantID,
'Authority' => $Authority,
'Amount' => $Amount,
],
]);
if ($result['Status'] == 100) {
return 'Done';
} else {
return 'Error 1';
}
}
else
{
return 'Error 2';
}
You need to use {params: {}} to pass url query to axios.get
axios.get("api/callback", {
params: {
Authority: ''
Status: 'OK'
}
})
.then(({
data
}) => (
console.log(data)
));
You may do this like so:
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
Usage
Example URL:
http://www.example.com/index.php?id=1&image=awesome.jpg
Calling getQueryVariable("id") - would return "1".
Calling getQueryVariable("image") - would return "awesome.jpg".
Taken from here