IONIC 2 Image upload to php server - ionic-framework

I'm getting an error when i pick a photo from the gallery its showing the alert as "server error". Please help me with my problem >_< I'm using Image Picker and cordova file transfer
upload(){
ImagePicker.getPictures({
maximumImagesCount: 1,
width: 127,
height: 127,
quality: 75
}).then((results) => {
for (var i = 0; i < results.length; i++) {
var url = "http://ifund.esy.es/register.php"
var targetPath = results[i];
// File name only
var filename = targetPath.split("/").pop();
const fileTransfer = new Transfer();
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "image/jpg",
params: {'directory': 'upload', 'fileName': filename, 'username': this.username, 'password': this.password, 'first_name': this.fname, 'last_name': this.lname, 'email': this.email, 'address': this.address, 'contact': this.contact, 'bday': this.bday}
};
fileTransfer.upload(url, targetPath, options).then((results) => {
alert('file uploaded successfully ' + results);
}, error => {
alert('server error');
});
}
}, (err) => {
let alert = this.alert.create({
title:'Warning',
subTitle: "ERROR",
buttons: ['OK']
})
alert.present(); });

Related

The client_secret Provided does not match any associated PaymentIntent on this account

I'm trying to use flutter_stripe for a stripe connect account, But I always get the
same error: The client_secret provided doesn't match the client_secret associated with the PaymentIntend.
I've completed all steps according to flutter_stripe but I still face this error.
Below is my code Please check this and help me.
inde.js
const functions = require("firebase-functions");
const stripe = require("stripe")("secret_key");
exports.stripePaymentIntentRequest = functions.https.onRequest(async (req, res) => {
try {
let customerId;
//Gets the customer who's email id matches the one sent by the client
const customerList = await stripe.customers.list({
email: req.body.email,
limit: 1
});
//Checks the if the customer exists, if not creates a new customer
if (customerList.data.length !== 0) {
customerId = customerList.data[0].id;
}
else {
const customer = await stripe.customers.create({
email: req.body.email
});
customerId = customer.data.id;
}
//Creates a temporary secret key linked with the customer
const ephemeralKey = await stripe.ephemeralKeys.create(
{ customer: customerId },
{ apiVersion: '2020-08-27' }
);
//Creates a new payment intent with amount passed in from the client
const paymentIntent = await stripe.paymentIntents.create({
amount: parseInt(req.body.amount),
currency: 'usd',
customer: customerId,
})
res.status(200).send({
clientSecret: paymentIntent.client_secret,
paymentIntent: paymentIntent,
ephemeralKey: ephemeralKey.secret,
customer: customerId,
success: true,
})
} catch (error) {
res.status(404).send({ success: false, error: error.message })
}
});
PaymentService.dart
Future<void> initPaymentSheet(
{required BuildContext context, required String email, required int amount}) async {
try {
// 1. create payment intent on the server
final response = await http.post(
Uri.parse(
'Firebase api link of Functions'),
body: {
'email': email,
'amount': amount.toString(),
});
Map<String, dynamic> paymentIntentBody = jsonDecode(response.body);
log(paymentIntentBody.toString());
//2. initialize the payment sheet
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentBody["clientSecret"],
merchantDisplayName: 'Flutter Stripe Store Demo',
customerId: paymentIntentBody['customer'],
customerEphemeralKeySecret: paymentIntentBody['ephemeralKey'],
style: ThemeMode.light,
testEnv: true,
merchantCountryCode: 'US',
),
);
await Stripe.instance.presentPaymentSheet();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Payment completed!')),
);
} catch (e) {
if (e is StripeException) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error from Stripe: ${e.error.localizedMessage}'),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error the Stripe of : $e')),
);
}
}
}
The log error print on my console is :
> [log] {paymentIntent:
> pi_3LI2acCTAUDjRNFV1Ra3dahz_secret_Fcqw73pWrE4avKRyuDVzRBitG,
> ephemeralKey:
> ek_test_YWNjdF8xSlQ3amtDVEFVRGpSTkZWLDl1OE5Vdm1jTGY4T1RpaVhHOTB3NTRVSkQ5UGl4azA_00j32OYG9n,
> customer: cus_LHG2YpQP9Cgwuy, success: true}
The following code is from a previous Stripe evaluation stage. But it worked. Slim it down to your needs.
Remember to publish your secret key to the server, so the server can talk to Stripe.
code.dart
Future<bool> payWithPaymentSheet(
ProductModel productModel, PriceModel priceModel,
{String merchantCountryCode = 'DE'}) async {
if (kIsWeb) {
throw 'Implementation not availabe on Flutter-WEB!';
}
String uid = AuthService.instance.currentUser().uid;
String email = AuthService.instance.currentUser().email ?? '';
HttpsCallableResult response;
try {
response = await FirebaseFunctions
.httpsCallable('createPaymentIntent')
.call(<String, dynamic>{
'amount': priceModel.unitAmount,
'currency': priceModel.currency,
'receipt_email': email,
'metadata': {
'product_id': productModel.id,
'user_id': uid,
"valid_until": productModel.getUntilDateTime().toIso8601String(),
'product_name': productModel.name.tr,
},
'testEnv': kDebugMode,
});
} on FirebaseFunctionsException catch (error) {
log(error.code);
log(error.details);
log(error.message ?? '(no message)');
Get.snackbar(
error.code,
error.message ?? '(no message)',
icon: const Icon(Icons.error_outline),
);
return false;
}
Map<String, dynamic> paymentIntentBody = response.data;
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentBody["clientSecret"],
currencyCode: priceModel.currency,
applePay: false,
googlePay: false,
merchantCountryCode: merchantCountryCode,
merchantDisplayName: Strings.appName,
testEnv: kDebugMode,
customerId: paymentIntentBody['customer'],
customerEphemeralKeySecret: paymentIntentBody['ephemeralKey'],
));
try {
await Stripe.instance.presentPaymentSheet();
return true;
} on StripeException catch (e) {
log(e.error.code.name);
log(e.error.message ?? '(no message)');
log(e.error.localizedMessage ?? '(no message)');
Get.snackbar(e.error.code.name, e.error.message ?? '',
icon: const Icon(Icons.error_outline));
} catch (e) {
Get.snackbar('An unforseen error occured', e.toString(),
icon: const Icon(Icons.error_outline));
}
return false;
}
index.ts
// SETTING SECRET KEY ON SERVER:
// cd functions
// firebase functions:config:set stripe.secret_key="sk_live_51L...Noe"
// firebase deploy --only functions
let stripe = require("stripe")(functions.config().stripe.secret_key);
exports.createPaymentIntent = functions
.https.onCall((data, context) => {
// if (!context.auth) {
// return { "access": false };
// }
return new Promise(function (resolve, reject) {
stripe.paymentIntents.create({
amount: data.amount,
currency: data.currency,
receipt_email: decodeURIComponent(data.receipt_email),
metadata: data.metadata,
}, function (err, paymentIntent) {
if (err != null) {
functions.logger.error("Error paymentIntent: ", err);
reject(err);
}
else {
resolve({
clientSecret: paymentIntent.client_secret,
paymentIntentData: paymentIntent,
});
}
});
});
});

FileTransfer download returns error with all properties null

I'm trying to use Ionic FileTransfer, but it always returns me with this response:
PS: The url is a direct link to the download
I really have no idea of whats wrong in this code
FileTransferError
{
body:null,
code:null,
exception:null,
http_status:null,
source:null,
target:null
}
My code:
const storageDirectory = '';
this.platform.ready().then(() => {
storageDirectory = cordova.file.externalRootDirectory;
let url = this.apiURL + itemId
const fileTransfer: FileTransferObject = this.transfer.create();
fileTransfer.download(url, storageDirectory + "item" + itemId+ ".xml")
.then(response => {
const alertSuccess = this.alertCtrl.create({
title: `Successfully downloaded!`,
subTitle: `The file is in: \n: ${response.toURL()}`,
buttons: ['Ok']
});
alertSuccess.present();
})
.catch(err => {
const alert = this.alertCtrl.create({
title: 'Error!',
subTitle: 'Try again!',
buttons: [{
text: 'OK',
handler: () => {
this.util.getPermission();
}
}]
});
alert.present();
});
})
}

send multiple images via file transfer plugin ionic 3

i'm working on app witch i need to send multiple images,
and i wonder if there is any way to send multiple images via file transfer plugin,
this my code:
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageData2) => {
this.imageURI2 = imageData2;
}, (err) => {
console.log(err);
});
upload
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'file',
fileName: 'name.jpg',
headers: {
Connection: "close"
}
}
options.chunkedMode = false;
if(this.imageURI1 != null){
fileTransfer.upload(this.imageURI1,
'https://test.test.com/uplaodphoto.php', options)
.then((data) => {
alert("success");
this.imageFileName1 =
"https://test.test.com/images/name.jpg"
}, (err) => {
alert("error"+JSON.stringify(err));
});
User Image Picker Plugin Cordova Image Picker
Usage:
import { ImagePicker } from '#ionic-native/image-picker';
constructor(private imagePicker: ImagePicker) { }
export class YourPage {
pickImages(){
this.imagePicker.getPictures(options).then((results) => {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
this.imageUpload(results[i])
}
}, (err) => { });
}
// Upload Image function.
imageUpload(path) {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'image',
fileName: '.png',
chunkedMode: false,
//mimeType: "image/jpeg",
}
fileTransfer.upload(path, 'https://api.com/image-upload', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
let res = JSON.parse(data.response);
if (res.success == true) {
}
this.loader.dismiss();
}, (err) => {
console.log(err);
});
}
}

Not able to convert the base64 to image path in Ionic 4

I am working on my Ionic 4 app and I have used the camera plugin for image uploading and I have converted the image to the base64 for showing the image but the problem is that I am not able to convert the base64 to proper image path for sending it to the API.
This is my editimage.page.html:
<ion-item class="newitem2">
<ion-avatar class="image-center">
<img name="profile_pic" [src]="this.userdetailsedit.value.profile_pic"/>
<ion-icon (click)="presentActionSheet()" class="myicon11" name="create"></ion-icon>
</ion-avatar>
</ion-item>
This is my editprofile.page.ts:
async UpdateUserDetails(){
this.storage.get('USER').then(userde => {
if (userde) {
this.userdetails = userde;
const userdetailseditss = {
first_name: this.userdetailsedit.value.first_name,
last_name: this.userdetailsedit.value.last_name,
mobile: this.userdetailsedit.value.mobile,
profile_pic: this.userdetailsedit.value.profile_pic,
};
this.chakapi.UserProfileUpdate(userdetailseditss, 'userUpdateProfile/' + this.userdetails.id).subscribe((data) => {
console.log(data);
}, error => {
console.log(error); });
}
});
}
async imageuserchoose(sourceType){
const options: CameraOptions = {
quality: 76,
sourceType: sourceType,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
correctOrientation: true,
}
this.camera.getPicture(options).then((imageData) => {
if (sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
let path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
let filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let index = filename.indexOf('?');
if (index > -1) {
filename = filename.substring(0,index);
}
this.file.readAsDataURL(path, filename).then(data => {
this.imagepic = data;
this.userdetailsedit.patchValue({
profile_pic: data,
});
});
}
if (sourceType === this.camera.PictureSourceType.CAMERA) {
let filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
this.file.readAsDataURL(path, filename).then(data => {
this.imagepic = data;
this.userdetailsedit.patchValue({
profile_pic: data,
});
});
}
}, (err) => {
});
}
async presentActionSheet() {
const actionSheet = await this.actionSheetController.create({
header: 'Select Image Source',
backdropDismiss:true,
buttons: [{
text: 'Choose From Gallery',
icon: 'images',
cssClass: 'myActionSheetBtnStyle',
handler: () => {
this.imageuserchoose(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Use Camera',
icon: 'camera',
cssClass: 'myActionSheetBtnStyle',
handler: () => {
this.imageuserchoose(this.camera.PictureSourceType.CAMERA);
}
}]
});
await actionSheet.present();
}
}
The problem is that when I am sending the image to the API, it is base64 and I am not able to convert it before sending.
Any help is much appreciated.
Please try this. You can use file transfer Native Plugin for this. It will solve your problem.
In the ts file:
async UpdateUserDetails(){
if(this.imagepic && this.fileUploadName) {
let fileTransfer = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'profile_pic',
fileName: this.fileUploadName,
headers: {}
}
options.params = {
first_name: this.userdetailsedit.value.first_name,
last_name: this.userdetailsedit.value.last_name,
mobile: this.userdetailsedit.value.mobile,
old_password: this.userdetailsedit.value.old_password,
password: this.userdetailsedit.value.password,
};
this.storage.get('USER').then(userde => {
if (userde) {
this.userdetails = userde;
fileTransfer.upload(this.imagepic, this.apiUrl+'userUpdateProfile/'+this.userdetails.id, options)
.then((data) => {
if(data && data.responseCode==200){
let response=JSON.parse(data.response);
if(response.status === "success"){
this.storage.set('ID', response.data.id);
this.storage.set('USER', response.data);
this.modalController.dismiss();
} else{
loading2.dismiss();
}
}else{
//show error msg
}
}, (err) => {
console.log('upload err ::',err);
});
}
});
}
}
async imageuserchoose(sourceType){
const options: CameraOptions = {
quality: 76,
sourceType: sourceType,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
correctOrientation: true,
// allowEdit: true,
}
this.camera.getPicture(options).then((imageData) => {
let filename,path;
this.imagepic = imageData;
if (sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let index = filename.indexOf('?');
if (index > -1) {
filename = filename.substring(0,index);
}
}
if (sourceType === this.camera.PictureSourceType.CAMERA) {
filename = imageData.substring(imageData.lastIndexOf('/') + 1);
path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
console.log(path,'FileName::', filename);
}
this.fileUploadName=filename;
this.file.readAsDataURL(path, filename).then(data => {
this.userdetailsedit.patchValue({
profile_pic: data,
});
});
}, (err) => {
// Handle error
});
}
This will solve your problem.

Cannot read property 'split' of undefined when image upload is empty in ionic

I tried testing my ionic image upload app in browser but since I can not upload image due to cordova_not_available been displayed on the screen, every time I click ed on the upload button this error pop up Cannot read property 'split' of undefined
**
NewpostPage.html:51 ERROR ReferenceError: FileTransfer is not defined at new Transfer (VM1294 vendor.js:149642) at NewpostPage.webpackJsonp.162.NewpostPage.uploadPhoto (VM1295 main.js:601) at Object.eval [as handleEvent] (VM1527 NewpostPage.ngfactory.js:180) at handleEvent (VM1294 vendor.js:13963) at callWithDebugContext (VM1294 vendor.js:15472) at Object.debugHandleEvent [as handleEvent] (VM1294 vendor.js:15059) at dispatchEvent (VM1294 vendor.js:10378) at VM1294 vendor.js:11003 at HTMLButtonElement. (VM1294 vendor.js:39326) at t.invokeTask (VM1427 polyfills.js:3)
**
in my upload.ts i have this
uploadPhoto() {
let loader = this.loadingCtrl.create({
content: "Please wait..."
});
loader.present();
//let filename = this.imagePath.split('/').pop();
console.log('this.imagePath: ', this.imagePath)
let filename = this.imagePath;
let options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "image/jpg",
params: {'location': this.location, 'title': this.postTitle, 'description': this.desc }
};
const fileTransfer = new Transfer();
fileTransfer.upload(this.imageNewPath, AppSettings.API_UPLOAD_ENDPOINT,
options).then((entry) => {
this.imagePath = '';
this.imageChosen = 0;
loader.dismiss();
this.navCtrl.setRoot(IncidentsPage);
}, (err) => {
alert(JSON.stringify(err));
});
}
chooseImage() {
let actionSheet = this.actionSheet.create({
title: 'Choose Picture Source',
buttons: [
{
text: 'Gallery',
icon: 'albums',
handler: () => {
this.actionHandler(1);
}
},
{
text: 'Camera',
icon: 'camera',
handler: () => {
this.actionHandler(2);
}
},
{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
}
]
});
actionSheet.present();
}
//}
actionHandler(selection: any) {
var options: any;
if (selection == 1) {
options = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 500,
targetHeight: 500,
saveToPhotoAlbum: false
};
} else {
options = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 500,
targetHeight: 500,
saveToPhotoAlbum: false
};
}
Camera.getPicture(options).then((imgUrl) => {
var sourceDirectory = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1);
var sourceFileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.length);
sourceFileName = sourceFileName.split('?').shift();
File.copyFile(sourceDirectory, sourceFileName, cordova.file.externalApplicationStorageDirectory, sourceFileName).then((result: any) => {
this.imagePath = imgUrl;
this.imageChosen = 1;
this.imageNewPath = result.nativeURL;
}, (err) => {
alert(JSON.stringify(err));
})
}, (err) => {
alert(JSON.stringify(err))
});
}
Please help out.
I think i see what you are asking now.
You need to check for undefined and "" before running the code inside uploadPhoto().
uploadPhoto() {
if(this.imagePath !== undefined || this.imagePath !== '') {
let loader = this.loadingCtrl.create({
content: "Please wait..."
});
loader.present();
//let filename = this.imagePath.split('/').pop();
console.log('this.imagePath: ', this.imagePath)
let filename = this.imagePath;
let options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "image/jpg",
params: {'location': this.location, 'title': this.postTitle, 'description': this.desc }
};
const fileTransfer = new Transfer();
fileTransfer.upload(this.imageNewPath, AppSettings.API_UPLOAD_ENDPOINT,
options).then((entry) => {
this.imagePath = '';
this.imageChosen = 0;
loader.dismiss();
this.navCtrl.setRoot(IncidentsPage);
}, (err) => {
alert(JSON.stringify(err));
});
}
} else {
//do something else
}