我最初发布这个问题是对不同SO线程的评论(较早:PayPal REST API .net SDK - 400 Bad Requests)但由于我没有看到任何回复,我认为问题可能是最好的。
如果不自行更改RestAPISDK,有没有办法让它在发生验证错误时将错误消息返回给我的代码?现在我唯一的行动方案就是阅读日志文件,看看发生了什么,但是当我向用户报告为什么收费失败时,为什么收费失败,这就像卡号无效一样简单,现在我们收到400 Bad Request,但是由于记录了失败,API显然会看到发生了什么,只是没有报告。
这是我正在使用的代码 - 当我进行payment.Create(apiContext)时,错误会被触发。
var card = new PayPal.Api.Payments.CreditCard
{
billing_address = new PayPal.Api.Payments.Address
{
city = customer.BillingAddress.City,
country_code = customer.BillingAddress.Country,
line1 = customer.BillingAddress.Address1,
postal_code = customer.BillingAddress.PostalCode,
state = customer.BillingAddress.StateProvince
},
cvv2 = customer.CreditAccount.SecurityCode,
expire_month = customer.CreditAccount.ExpirationMonth,
expire_year = customer.CreditAccount.ExpirationYear,
first_name = customer.FirstName,
last_name = customer.LastName,
number = customer.CreditAccount.CardNumber
};
//only send line 2 if it exists, otherwise it'll error out
if (!string.IsNullOrEmpty(customer.BillingAddress.Address2))
card.billing_address.line2 = customer.BillingAddress.Address2;
switch (customer.CreditAccount.CardType)
{
case CardTypes.AmericanExpress:
card.type = "amex";
break;
default:
card.type = customer.CreditAccount.CardType.ToString().ToLower();
break;
}
var amt = new PayPal.Api.Payments.Amount
{
currency = "USD",
details = new PayPal.Api.Payments.Details
{
shipping = Math.Round(customer.CreditAccount.Shipping, 2).ToString(),
subtotal = Math.Round(customer.CreditAccount.Amount, 2).ToString(),
tax = Math.Round(customer.CreditAccount.Tax, 2).ToString()
},
total = Math.Round(customer.CreditAccount.GrandTotal, 2).ToString()
};
var payer = new PayPal.Api.Payments.Payer
{
funding_instruments = (new FundingInstrument[] { new FundingInstrument { credit_card = card } }).ToList(),
payment_method = "credit_card"
};
var payment = new Payment
{
intent = "sale",
payer = payer,
transactions = (new Transaction[] {
new Transaction { description = customer.CreditAccount.Description, amount = amt }
}).ToList()
};
try
{
var accessToken = new PayPal.OAuthTokenCredential(this.Configuration.ClientID, this.Configuration.ClientSecret).GetAccessToken();
var apiContext = new PayPal.APIContext(accessToken);
var result = payment.Create(apiContext);
if (result.state == "approved")
creditResponse = new CreditResponse { AuthorizationCode = result.id, Status = CreditResponseTypes.Success, TransactionId = result.id };
else
creditResponse = new CreditResponse { Status = CreditResponseTypes.Declined };
}
catch (Exception ex)
{
creditResponse = new CreditResponse
{
Message = ex.ToString(),
Status = CreditResponseTypes.Error
};
}
已修改:已添加示例代码