微软Wingtip Toys示例中PayPal金额变量值不匹配问题求助
Hey there, let's sort out this PayPal amount mismatch issue you're hitting in the Wingtip Toys project! The problem is straightforward: one value is in dollars (2.94) and the other is in cents (294) — that's exactly why you're getting the mismatch error.
The Root Cause
PayPal often returns transaction amounts in cents as the smallest unit (this avoids floating-point precision errors with currency). Your session value payment_amt is already stored as a dollar amount (2.94), but the AMT value from PayPal is coming through as 294 cents.
How to Unify Both Values to 2.94
The simplest fix is to convert the PayPal-cent amount to dollars by dividing by 100. Here's how to adjust your code:
// Keep your existing session value conversion (already in dollars) decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString()); // Convert PayPal's cent-based amount to dollars decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString()) / 100;
For More Robust Code (Recommended)
To avoid crashes if either value is malformed, use decimal.TryParse instead of Convert.ToDecimal — it lets you handle invalid input gracefully:
decimal paymentAmountOnCheckout; if (!decimal.TryParse(Session["payment_amt"].ToString(), out paymentAmountOnCheckout)) { // Handle invalid session value (e.g., log error, redirect to error page) throw new InvalidOperationException("Could not parse payment amount from session."); } decimal paypalAmountInCents; if (!decimal.TryParse(decoder["AMT"].ToString(), out paypalAmountInCents)) { // Handle invalid PayPal response (e.g., log error, notify user) throw new InvalidOperationException("Could not parse amount from PayPal response."); } // Convert cents to dollars decimal paymentAmoutFromPayPal = paypalAmountInCents / 100;
Quick Check
After making this change, both variables will hold the value 2.94, so the PayPal amount mismatch error should disappear. Always double-check that your currency units align across your app and payment provider to avoid these kinds of issues!
内容的提问来源于stack exchange,提问作者Miguel Boavida

