On my back-end I got two possible responses within that action.
The first one:
return Ok(new { Message = "email_confirmed" });
And the second one:
return NotFound();
And on my front-end I got this:
let url: string = "http://10.0.2.2:53286/api/Home/AccountValidation?codeActivation=" + this.code;
this.http.patch(url, {
}).subscribe((res) => {
console.log(JSON.stringify(res));
if(res.status != 404) {
alert({title: "Sistema 3 Esferas", message: "¡Tu cuenta ha sido activada satisfactoriamente! :)", okButtonText: "¡Entendido!"});
this.router.navigate(["/Miembro"]);
} else {
this.btnEnabled = true;
alert({title: "Sistema 3 Esferas", message: "Has introducido un código inválido. :(", okButtonText: "Entiendo..."});
}
});
If the back-end reaches the Ok(), then the if gets executed and everything works perfectly.
However, if my back-end reaches the second return, which is the NotFound() one, nothing happens. You see this log at the beginning of the subscribe()?
console.log(JSON.stringify(res));
Well, if NotFound() is returned, nothing is showed on the log. It's almost like if the subscribe was never executed.
Why is that happening?
You need to add catch handler to catch all other responses than 200(OK) because they are treated as errors, like this -
this.http.patch(url, {
}).subscribe((res) => {
console.log(JSON.stringify(res));
alert({title: "Sistema 3 Esferas", message: "¡Tu cuenta ha sido activada satisfactoriamente! :)", okButtonText: "¡Entendido!"});
this.router.navigate(["/Miembro"]);
}).catch(this.handleError);
};
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
this.btnEnabled = true;
alert({title: "Sistema 3 Esferas", message: "Has introducido un código inválido. :(", okButtonText: "Entiendo..."});
}
For more information, refer to this.
Related
I'm using checkout-sdk with angular and spring boot. Here is the code I have on the angular side
paypal
.Buttons({
style: {
color: 'blue',
shape: 'pill',
label: 'pay',
height: 40
},
createOrder: (data, actions) => {
return actions.order.create({
purchase_units: [
{
description: 'Order id: '+this.order.id,
amount: {
currency_code: 'EUR',
value: this.order.totalPrice
}
}
]
});
},
onApprove: async (data, actions) => {
const order = await actions.order.capture();
this.paidFor = true;
this.checkoutPaypal(this.id,order.id)
},
onError: err => {
}
})
.render(this.paypalElement.nativeElement);
This is function used to retrieve payment, and save details to database..
public String checkoutPaypal(Integer id, String orderId) {
OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
request.requestBody(buildRequestBody());
HttpResponse<com.paypal.orders.Order> response;
try {
response = payPalClient.client().execute(request);
} catch (IOException e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
}
for (PurchaseUnit purchaseUnit : response.result().purchaseUnits()) {
purchaseUnit.amountWithBreakdown();
for (Capture capture : purchaseUnit.payments().captures()) {
if (capture.status().equals("COMPLETED")) {
Order order = orderRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found!"));
order.setOrderState(OrderState.PAID);
order.setPaymentDetails("Charge id: " + capture.id() + "; Status: " + capture.status() + "; Time paid: " + capture.createTime() + " GMT");
order.addOrderStateChange(OrderState.PAID, false);
sendEmail(order, " paid successfully!", "Thanks for your purchase!<br>We will work as hard as we can, to deliver the order to you, as soon as possible!");
orderRepository.save(order);
}
}
}
return "Successfully paid!";
}
Which worked few days ago.. But now I'm getting this error
{"name":"UNPROCESSABLE_ENTITY","details":[{"issue":"ORDER_ALREADY_CAPTURED","description":"Order already captured.If 'intent=CAPTURE' only one capture per order is allowed."}],"message":"The requested action could not be performed, semantically incorrect, or failed business validation.","debug_id":"f058cb447ccbb","links":[{"href":"https://developer.paypal.com/docs/api/orders/v2/#error-ORDER_ALREADY_CAPTURED","rel":"information_link","method":"GET"}]}
But after replacing
OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
request.requestBody(buildRequestBody());
HttpResponse<com.paypal.orders.Order> response;
with
OrdersGetRequest request = new OrdersGetRequest(orderId);
HttpResponse<com.paypal.orders.Order> response;
It works as it should.
So my question is, what is the difference between
https://developer.paypal.com/docs/checkout/reference/server-integration/capture-transaction/
and
https://developer.paypal.com/docs/checkout/reference/server-integration/get-transaction/ ?
One is to get the status of the order, the other is to capture the order.
Capturing should not be done once you have called actions.order.capture() on the client side, and will always return an error in such a case. It may also also return an error when the order has been created on the client side (actions.order.create())
A correct server-based integration uses neither actions.order.create() nor actions.order.capture() on the client side. It is very important not to do so, as transactions will be created without your server receiving any immediate direct response from PayPal.
Instead, create two routes on your server, one for 'Create Order' and one for 'Capture Order' as documented here. These routes should return JSON data. Before returning data, the capture route should check for success and act accordingly to send an email or whatever other business operation you need.
The approval flow to pair with the above two routes is https://developer.paypal.com/demo/checkout/#/pattern/server
I'm using stripe in React and processing the charge through an AJAX call.
I've tried to strip down the Stripe.card.createToken function to the bare essentials for this question.
The if else statement checks if the response has any errors.
I use the 4100000000000019 card number to ensure a card declined error but the else statement(the successful charge) fires regardless which card number is entered.
Entering the 4100000000000019 card number results in a blocked charge in the Stripe dashboard. An error definitely gets generated:
{
"error": {
"message": "Your card was declined.",
"type": "card_error",
"code": "card_declined",
"decline_code": "generic_decline",
"charge": "ch_19gMBaIWHxnqld7LCdbCtdNz"
}
}
But the if(response.error) is ignored and runs the else statement.
Stripe.card.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val(),
name: $('.first-name').val()
}, function(status, response){
if (response.error) {
this.reportError(response.error.message);
} else { // No errors, submit the form.
var token = response.id;
$.ajax({
type: 'POST',
url: 'components/charge.php',
data : {
stripeToken: token
},
success: function(data,response) {
paymentSuccessful();
},
error: function(data,textStatus) {
console.log("Ajax Error!");
}
});//$.ajax
}//else
});//Stripe.card.createToken
Any help is much appreciated.
Moe
UPDATE: Thanks to this awesome tutorial by Larry Ullman and it's section on stripe error handling, I came up with a fairly good solution.
http://www.larryullman.com/2013/01/30/handling-stripe-errors/
So I added the if else statment inside the AJAX success function.
success: function(data,response) {
if(data == "success"){
$('#payment-error-copy').text("Your payment was successful. Thank you for ordering!");
paymentSuccessful();
} else {
$('#payment-error-copy').text(data);
}
};//success function
Inside the charge we can return the error response and the precise reason for the error.
my charge.php file
<?php
require_once('vendor/autoload.php');
// Get the payment token submitted by the form:
$token = $_POST['stripeToken'];
try{
\Stripe\Stripe::setApiKey("<secret_KEY>");
$customer = \Stripe\Customer::create(array(
"source" => $token,
"email" => $email
)
);
// Charge the Customer instead of the card
\Stripe\Charge::create(array(
"amount" => $price, // amount in cents, again
"currency" => "aud",
"description" => $email." ".$first_name,
"customer" => $customer->id
)
);
echo "success";
} catch (\Stripe\Error\ApiConnection $e) {
// Network problem, perhaps try again.
$e_json = $e->getJsonBody();
$error = $e_json['error'];
echo "Sorry, your charge couldn't be processed. Reason: ".$error['message'];
} catch (\Stripe\Error\InvalidRequest $e) {
// You screwed up in your programming. Shouldn't happen!
$e_json = $e->getJsonBody();
$error = $e_json['error'];
echo "Sorry, your charge couldn't be processed. Reason: ".$error['message'];
} catch (\Stripe\Error\Api $e) {
// Stripe's servers are down!
$e_json = $e->getJsonBody();
$error = $e_json['error'];
echo "Sorry, your charge couldn't be processed. Reason: ".$error['message'];
} catch (\Stripe\Error\Card $e) {
// Card was declined.
$e_json = $e->getJsonBody();
$error = $e_json['error'];
echo "Sorry, your charge couldn't be processed. Reason: ".$error['message'];
}
?>
The try catch statement returns a precise message about the charge error and returns it to our success function, so if the charge is anything other than success it runs the error function.
Although my question remains unanswered, the build works as expected and still remains safe for the user to enter their billing info.
Thanks to the other SO users for their input, it is really appreciated.
I think this particular card number only gives an error when Stripe actually tries to use it.
Just built a change-card-function for my SaaS and noticed that when I update my StripeCustomer default source with the token received, it fails.
I have been trying to alert this so that it prints two responses
when there is an error or a duplicate entry and
when the response is ok and prints successfully
var response;
try {
response = JSON.parse(xmlhttp.responseText);
} catch (e) {
console.error(this.responseText);
alert(this.responseText);
}
if (response) {
console.log(response);
}
I want it to alert a response both when there is a failure and when the response is successful, but I haven't figured it out yet.
figured it out
at this stage
console.error(this.responseText);
alert(this.responseText);
i needed to insert my error message here like this
var responseText = this.responseText;
alert('Registration failure because ' + responseText );
and below
console.log(response);
alert ('Registration Successful');
At this stage it prints the required outcome.
I had this little piece of code working perfectly returning account and transactions objects in response to the Plaid MFA questions. I'm not sure what went wrong as I (had not until it stopped working and I've since tried a few things) did not touch the code (to my recollection) and even checked several previous working versions to be safe. Anyhow I now get the following list of errors given the scenario:
1) If I try to US Bank MFA, it returns an MFA and after I answer it also returns a account and transactions object. At the end of that info in my terminal it also returns events.js 85 throw er; // Unhandled error event
2) If I try USAA or Bank of America I get the following error object for my response:
{ code: 1203,
message: 'invalid mfa',
resolve: 'The MFA response provided was not correct.',
access_token: 'test_bofa' }
It returns the MFA question though and when I answer with 'again', I get:
{ type: 'questions',
mfa: [ { question: 'You say tomato, I say...?' } ],
access_token: 'test_bofa' }
events.js:85 throw er; // Unhandled 'error' event
plaid.connect({username: req.body.cardName, password: req.body.cardPass, pin: req.body.pin}, req.body.type,
'test#plaid.com',
function (error, response, mfa) {
if (response == undefined) {
res.send(response);
} else if (response.hasOwnProperty('accounts')) {
res.send(response);
} else if (response.hasOwnProperty("mfa")) {
res.send(response);//If I remove this response it kicks me out right away. But with it, I receive an undefined MFA response.
plaid.step(response.access_token, req.body.answer, function (err, response) {
if (response == undefined) {
res.send(response);
} else if (response.hasOwnProperty("resolve")) {
res.send(response);
} else if (response.hasOwnProperty('accounts')) {
res.send(response);
} else if (response.hasOwnProperty('mfa')) {
res.send(response);
}
}
)
}
else {
response = "error";
response.send("something went wrong with Plaid");
}
}
)
}
As i understand during testing mfa code should be string or and array(if there are few questions). So if you enter mfa as an int you will get error.
'again' mfa will call one more mfa loop, and 'tomato' will finalize it.
If the server returns an error (HTTP response code != 200) when uploading a file with Uploadify, the uploaded file gets a red background and a message is show like this:
file.jpg (52.78KB) - HTTP Error
indicating that there was a HTTP Error. But that's not very useful to the the user. How can I make it show a more detailed error message? Like: 'Not a valid image' or 'Quota full'?
I was thinking of passing those messages in the HTTP response body, but Uploadify doesn't pick them up. Is there a known way to pass error messages back to Uploadify?
Take a look at these two posts in the uploadify forum on how to handle errors
onError to display what's happening
and
Upload script error reporting
there is a lot of useful info in there ..
Update
The following seems to do the trick for me ..
'onComplete': function(a, b, c, d, e){
if (d !== '1')
{
alert(d);
}
else
{
alert('Filename: ' + c.name + ' was uploaded');
}
}
coupled with this version of the uploadify script
<?php
if (!empty($_FILES))
{
$tempFile = $_FILES['userfile']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['userfile']['name'];
move_uploaded_file($tempFile,$targetFile);
switch ($_FILES['userfile']['error'])
{
case 0:
$msg = ""; // comment this out if you don't want a message to appear on success.
break;
case 1:
$msg = "The file is bigger than this PHP installation allows";
break;
case 2:
$msg = "The file is bigger than this form allows";
break;
case 3:
$msg = "Only part of the file was uploaded";
break;
case 4:
$msg = "No file was uploaded";
break;
case 6:
$msg = "Missing a temporary folder";
break;
case 7:
$msg = "Failed to write file to disk";
break;
case 8:
$msg = "File upload stopped by extension";
break;
default:
$msg = "unknown error ".$_FILES['userfile']['error'];
break;
}
}
if ($msg)
{ $stringData = "Error: ".$_FILES['userfile']['error']." Error Info: ".$msg; }
else
{ $stringData = "1"; } // This is required for onComplete to fire on Mac OSX
echo $stringData;
?>
Unfortunately the onUploadError event does not have access to the reponse body. You'll have to return 200 status and handle the errors in onUploadSuccess as far as I'm aware.
Here's how I'm doing it:
'onUploadSuccess' : function(file, data, response) {
var responseObj = JSON.parse(data);
if(responseObj.error_message)
{
$("#" + file.id).hide(); // this will hide the misleading "complete" message..
alert(responseObj.error_message);
return;
}
}
Or better yet you could replace the "complete" message with your error message like so:
'onUploadSuccess' : function(file, data, response) {
var responseObj = JSON.parse(data);
if(responseObj.error_message)
{
$("#" + file.id).find('.data').css('color', 'red').html(' - ' + responseObj.error_message);
return;
}
console.log(file, data, response);
}
I've had the same problem. after search for hours I found the problem. I have set "proxy server" in my "internet Options->Lan setting" , and when I returned it to default state, uploadify worked again.
For uploadify version 3.0+ take a look at the onUploadSuccess option - specifically the passed in variable named data - that will have whatever the server echoed. If you echo JSON remember to decode it like so:
...
'onUploadSuccess' : function(file, data, response) {
if (response){
var json_data=JSON.decode(data);
/* code here */
}
},
....