Paypal intergration - Payment not processable error in ionic3? - paypal

I am working on the paypal integration to my ionic app,…Happily i could easily implement the paypal with static value, but when I tried to dynamic value it shows an error.
Payment not processable in console.
continueSubscription(){
//initialize payment......
this.payPal.init({
PayPalEnvironmentProduction: '',
PayPalEnvironmentSandbox: 'XXXXXX'
}).then(() => {
var data = this.paymentAmount;
// Environments: PayPalEnvironmentNoNetwork, PayPalEnvironmentSandbox, PayPalEnvironmentProduction
this.payPal.prepareToRender('PayPalEnvironmentSandbox', new PayPalConfiguration({})).then(() => {
console.log(this.selectedValue);
var payment = new PayPalPayment(this.selectedValue.amount, this.selectedValue.currency_type, 'Description', this.selectedValue.descryption);
this.payPal.renderSinglePaymentUI(payment).then((res) => {
// Successfully paid
this.paymentResponse = res;
}, (error) => {
console.log(error);
// Error or render dialog closed without being successful
});
}, () => {
// Error in configuration
});
}, () => {
// Error in initialization, maybe PayPal isn't supported or something else
});
}
below share the updated ts code and selectedValue is object in which we have pass dynamic data and i pass following object to payment:
amount: "200"
bnCode: "PhoneGap_SP"
currency: "INR"
details: undefined
intent: "Health Record With Conditioncjn dfgh"
shortDescription: "Description"
Please team tell me how to fix above error ?

Did you make sure that this.selectedValue.amount is a string?
PayPal expects the amount as a string, no number / int is accepted.
What does your console say if you execute console.log(this.selectedValue.amount);?
You could also try to use single quotes instead of double quotes.

Related

how to fix UNAUTHENTICATED error while trying to create an asset report using PLAID? Plaid createAssetReport using cloud function

I'm trying to create an asset report from Plaid, I'm using Cloud Functions for these calls, all the other cloud functions work (link, transactions, balance) but assetReportCreate fails and return UNAUTHENTICATED

The Plaid logs do not show the call...so I guess something is wrong in my Cloud Function, but the Google Console Logs show status 200.
has anybody experienced the same issue and know how to fix it?
PS: just double checked today to make sure I'm authenticated and I am...
//create ASSET report
exports.createAssetReport = functions.https.onCall(async (data, context) => {
const accessToken = data.accessToken;
const daysRequested = data.daysRequested;
// const options = {
// client_report_id: '123',
// webhook: "https://www.example.com", //to let you know when report is ready, get link from cloud console
// };
const configuration = new Configuration({
basePath: PlaidEnvironments[functions.config().app.env],
baseOptions: {
headers: {
"PLAID-CLIENT-ID": functions.config().plaid.client_id,
"PLAID-SECRET": functions.config().plaid.secret,
},
},
});
const plaidClient = new PlaidApi(configuration);
//call the createLinkToken METHOD of the plaidClient instance!
return plaidClient
.assetReportCreate({
access_tokens: [accessToken],
days_requested: daysRequested,
//options,
})
.then((response) => {
const assetReportId = response.data.asset_report_id;
const assetReportToken = response.data.asset_report_token;
return assetReportToken; //token is needed to retrieve the report via //pdf/get
})
.catch((err) => {
console.log(err);
throw new functions.https.HttpsError(
"internal",
" Unable to create asset report: " + err
);
});
});
I found that for whatever reason the function wasn't open for all users to invoke, adding a principal with role: "cloud functions invoker" fixed the issue, shame on you google cloud, I spent two full days on this!! jk, thanks for your services but fix these small details and you could become the #1 cloud provider

Ionic view not updating after return from provider promise

I'm very new to Ionic and JS programming in general so please forgive my ignorance. I've been able to get data from other REST providers I've setup and have the updated values display fine. Pretty much copied the code from some other working functions. This time, no matter what I try, nothing will update.
Provider:
return new Promise(resolve => {
this.http.post(this.apiUrl)
.subscribe(res => {
resolve(res);
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
this.error = {"text":"App error occured."};
console.log('Client-side error occured.');
} else {
this.error = {"text":"Cloud server error occured."};
console.log('Cloud server error occured:'+err);
}
return this.error;
});
});
}
HTML:
<ion-item>
<ion-label stacked>Make</ion-label>
{{vesselData?.make}}
</ion-item>
Function:
vesselData = {"make":""};
updateVesselInfo() {
const data = JSON.parse(localStorage.getItem('userData'));
this.vesselProvider.getVesselData(data.userData.sim).then(vData => {
this.vesselData = vData;
}).catch(console.log.bind(console));
}, (err) => {
console.log("Vessel: ".err);
});
If I log the data returned from the provider in the .then(), it shows the provider returned the correct data. However, it's not updating any of the vesselData variables. Any idea where I'm going wrong here?
So modern way is to provide method in your provider that returns Observable and then in your component you just call this method and subscribe to it to obtain data:
In your provider:
getVesselData() {
return this.http.post(this.apiUrl)
.pipe(
catchError(this.yourErrorHandlerInsideProviderHere)
)
}
Now in your component:
vesselData = {"make":""};
updateVesselInfo() {
this.provider.getVesselData().subscribe( vesselData => {
this.vesselData = vesselData;
})
}
So ideal is to keep error handling inside provider here and within component your methods should be light weight.
This example should work for you as long as you are on Angular 4.3+ using modern HTTP module that comes with it.
Update:
Please ensure you properly bind to template. Here is example:
https://stackblitz.com/edit/ionic-wqrnl4
I skipped the rest call (http), but the principle is the same.

ionic update contact info

I create an Application to Read and Update Contacts Details. Here is a problem to updating Contact email. (I'm using Ionic 3)
When I try to add information to an existing contact the app closes and the console dont show nothing more. I'm using android studio to see the APK in the mobile and does not allow me to update. Here my code:
Update: I got the follow error:
"Wrong type for parameter "properties" of contacts.create: Expected Object, but got String."
"Error in Success callbackId: Contacts1616016237 : TypeError: Wrong type for parameter "properties" of contacts.create: Expected Object, but got String."
I pass the id as a parameter and I look for the contact to update.
UpdateContact(id, email){
var options = new ContactFindOptions();
options.filter = id;
options.multiple = true;
let proms = [];
this.contacts.find(["id"], options).then(res=>{res.forEach( (item:Contact) => {
//console.log(contact);
proms.push(new Promise( (resolve, reject) => {
var f = new ContactField('email',email,true);
item.emails = [];
item.emails.push(f);
console.log('FIXED '+item.displayName);
item.save().then(() => console.log('Contact saved!'),
(error: any) => console.error('Error saving contact.', error)
);
resolve();
}))
})
})
}

Angular2 return data from validation service after Http call

I have build a validation service for my registration form and one of the static methods is checking if the entered email is available by calling my API the following:
static emailAvailable(control){
let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
let valid = "E-mail is available";
http.post('https://secretapi.com/email', JSON.stringify({ email: control.value }))
.map((res: Response) => res.json())
.subscribe(function(result){
if(result.success){
valid = result.success; //The console.log on the line below is correct, the one at the bottom of the script never changes.
console.log(valid);
return null; //Doesn't do anything?
}else{
valid = result.error; //The console.log on the line below is correct, the one at the bottom of the script never changes.
console.log(valid);
return { 'invalidEmailAddress': true }; //Doesn't do anything, just like the return above
}
});
console.log(valid); //Output always "E-mail is available"
}
It should return "null" to the form validator when the email is available. The last console.log at the bottom should output the message that it recieves in the subscribe call. This doesn't happen and I'm not sure why. For some reason everything that happens within the subscribe call is contained there and never reaches the validator. What should I change? I have no idea and been searching the web for hours now.
You have to return Observable or Promise from your validator:
return http.post('https://secretapi.com/email', ...
console.log(...) doesn't make any sense here, since it will be executed after the Observable has been created as an object, but not after the ajax call has bee made.
If you want to output something after a response has been received, you have to move it inside subscribe
So in the end this website had the right answer. Also important to notice with the Angular2 Form validator to put the Async validators in the third (3) parameter and not together in an array in the second (2) parameter. That took me about 3 hours to figure out.
function checkEmail(control: Control){
let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
return new Observable((obs: any) => {
control
.valueChanges
.debounceTime(400)
.flatMap(value => http.post('https://secretapi.com/email', JSON.stringify({ email: control.value })))
.map((res: Response) => res.json())
.subscribe(
data => {
if(data.success){
obs.next(null);
obs.complete();
} else {
obs.next({ 'invalidEmailAddress': true });
obs.complete();
}
}
);
});
}
The validator should look something like this, with the first validators checking on required and if it's actually an email address and the last doing an async call to the server to see if it's not already in use:
this.registerForm = this.formBuilder.group({
'email': ['', [Validators.required, ValidationService.emailValidator], ValidationService.emailAvailable],
});

Azure Mobile Service: 500 Error but it's actually working?

I've got an Azure Mobile Service with a custom API. I have tested this API in the past from iOS and it seems to work fine. I am now testing this API on Android. This is the API method in question:
exports.post = function(request, response) {
var body = request.body;
var email = body.email;
var tables = request.service.tables;
var users = tables.getTable('User');
users.where({ email: email }).read({
success: function (userList) {
if (userList.length === 0) {
response.send(200, { Status: 'Error', Error: 'Email not found.' });
} else {
var user = userList[0];
var providerId = user.ObjectId;
var accounts = tables.getTable('Account');
accounts.where({ User: providerId }).read({
success: function (accountList) {
if (accountList.length === 0) {
response.send(200, { Status: 'Error', Error: 'Internal server error.' });
} else {
var account = accountList[0];
var mssql = request.service.mssql;
var sql = "EXEC [db].[usp_RequestPasswordReset] ?;";
mssql.query(sql, [account.id], {
success: function (results) {
console.log(results);
var codeRow = results[0];
if (codeRow == undefined) {
console.log("codeRow is undefined");
} else {
console.log(codeRow);
}
var code = codeRow.Code;
response.send(200, { Status: 'Success', Message: 'Please check your email for further instructions.', Code: code });
sendEmail(email, user.Name, code);
}
});
}
}
});
}
}
});
};
Now, sendEmail is a separate function that sends an email using Azure's SendGrid feature.
What is really perplexing me is that all of the code appears to be working fine.
The stored procedure executes just fine.
The database is updated exactly as I would expect.
The email comes through the SendGrid service exactly as expected.
The console.log messages that I have in the code display the expected values.
The only thing that is funky is that the call is returning a "500: Internal Server Error" error.
This is true both in my Android client and also in the API log on the Azure Management Portal.
The error message I am getting is telling me that var code = codeRow.Code; is trying to access 'Code' of 'undefined'. But it's not undefined.
Going back and checking my iOS client against this produces the same results.
Everything works fine except for the message returned to the user.
To be clear, the error code is 500, not 200, since it's possible for my code to return an "Internal Server Error" message.
Also, I am very sure that my mssql.query success block is firing, based on the console log messages and the outcome.
So, what gives?
mssql.query can call your callback more than once depending on what's in your stored procedure. You can define a variable outside your callback, e.g.
var callbackReceived = false;
and then in your callback, only send a response for the call that actually receives the updated record:
if (callbackReceived === false && results && results.length > 0) {
callbackReceived = true;
// continue as before
}
See also this question answered by one of the Azure developers:
Azure mobile service custom API calling SQL SP multiple times