public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(string token, string payerID, string paymentAmount, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType, string invoiceId) { // Create the request object var pp_request = new DoExpressCheckoutPaymentRequestType { DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType { Token = token, PayerID = payerID } }; // Create the request details object var paymentDetails = new PaymentDetailsType { InvoiceID = invoiceId, PaymentAction = paymentAction, PaymentActionSpecified = true, OrderTotal = new BasicAmountType { currencyID = currencyCodeType, Value = paymentAmount } }; paymentDetails.ButtonSource = "HotcakesCommerce_Cart_EC_US"; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails = new[] { paymentDetails }; return((DoExpressCheckoutPaymentResponseType)caller.Call("DoExpressCheckoutPayment", pp_request)); }
public void DoExpressCheckoutPayment(string token, string payerId) { var service = new PayPalAPIInterfaceServiceService(); var getECWrapper = new GetExpressCheckoutDetailsReq { GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token) }; var request = new DoExpressCheckoutPaymentRequestType(); var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = requestDetails; var getECResponse = service.GetExpressCheckoutDetails(getECWrapper); requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails; requestDetails.Token = token; requestDetails.PayerID = payerId; requestDetails.PaymentAction = PaymentActionCodeType.SALE; var wrapper = new DoExpressCheckoutPaymentReq { DoExpressCheckoutPaymentRequest = request }; var doECResponse = service.DoExpressCheckoutPayment(wrapper); var ack = doECResponse.Ack.HasValue ? doECResponse.Ack.Value : AckCodeType.FAILURE; AssertCheckoutResponse(ack, doECResponse.Errors); }
protected void Submit_Click(object sender, EventArgs e) { PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(); GetExpressCheckoutDetailsReq getECWrapper = new GetExpressCheckoutDetailsReq(); getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token.Value); GetExpressCheckoutDetailsResponseType getECResponse = service.GetExpressCheckoutDetails(getECWrapper); // Create request object DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType(); DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = requestDetails; requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails; requestDetails.Token = token.Value; requestDetails.PayerID = payerId.Value; requestDetails.PaymentAction = (PaymentActionCodeType) Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue); // Invoke the API DoExpressCheckoutPaymentReq wrapper = new DoExpressCheckoutPaymentReq(); wrapper.DoExpressCheckoutPaymentRequest = request; DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(wrapper); // Check for API return status setKeyResponseObjects(service, doECResponse); }
public CheckoutPaymentResult DoExpressCheckoutPayment(User user, string token, string payerId) { var getEcResponse = _GetExpressCheckoutDetails(token); CheckoutStatus status; if (!Enum.TryParse(getEcResponse.GetExpressCheckoutDetailsResponseDetails.CheckoutStatus, true, out status)) { return new CheckoutPaymentResult { Errors = new List <string> { "NOCHECKOUTSTATUS" } } } ; if (status == CheckoutStatus.PaymentActionNotInitiated) { user.PaypalPayerId = payerId; var request = new DoExpressCheckoutPaymentRequestType(); var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType { Token = token, PayerID = payerId, PaymentAction = PaymentActionCodeType.SALE }; request.DoExpressCheckoutPaymentRequestDetails = requestDetails; requestDetails.PaymentDetails = getEcResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails; var wrapper = new DoExpressCheckoutPaymentReq { DoExpressCheckoutPaymentRequest = request }; var doEcResponse = _payPalApiService.DoExpressCheckoutPayment(wrapper, GetApiUserName()); var custom = getEcResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails[0].Custom.Split('|'); var result = new CheckoutPaymentResult { BillingAgreementId = doEcResponse.DoExpressCheckoutPaymentResponseDetails.BillingAgreementID, PaymentStatus = doEcResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus.ToString(), PendingReason = doEcResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason.ToString(), TransactionId = doEcResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID, ProductName = (ProductNames)Enum.Parse(typeof(ProductNames), custom[0], true), Referrer = custom[1], Errors = new List <string>(), }; if (doEcResponse.Ack.Equals(AckCodeType.FAILURE) || (doEcResponse.Errors != null && doEcResponse.Errors.Count > 0)) { foreach (var error in doEcResponse.Errors) { result.Errors.Add(error.LongMessage); } } else { _userService.Purchase(user, result.ProductName, payerId); } return(result); } return(new CheckoutPaymentResult { Errors = new List <string> { status.ToString() } }); } }
/// <summary> /// Do paypal express checkout /// </summary> /// <param name="Token">Paypal express checkout token</param> /// <param name="PayerID">Paypal payer identifier</param> /// <param name="OrderTotal">Order total</param> /// <param name="processPaymentResult">Process payment result</param> public void DoExpressCheckout(string Token, string PayerID, decimal OrderTotal, ProcessPaymentResult processPaymentResult) { InitSettings(); TransactMode transactionMode = GetCurrentTransactionMode(); DoExpressCheckoutPaymentReq req = new DoExpressCheckoutPaymentReq(); DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType(); req.DoExpressCheckoutPaymentRequest = request; request.Version = this.APIVersion; DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = details; PaymentDetailsType paymentDetails = new PaymentDetailsType(); details.PaymentDetails = paymentDetails; if (transactionMode == TransactMode.Authorize) { details.PaymentAction = PaymentActionCodeType.Authorization; } else { details.PaymentAction = PaymentActionCodeType.Sale; } details.Token = Token; details.PayerID = PayerID; paymentDetails.OrderTotal = new BasicAmountType(); paymentDetails.OrderTotal.Value = OrderTotal.ToString("N", new CultureInfo("en-us")); paymentDetails.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(CurrencyManager.PrimaryStoreCurrency); paymentDetails.ButtonSource = "nopCommerceCart"; DoExpressCheckoutPaymentResponseType response = service2.DoExpressCheckoutPayment(req); string error; if (!PaypalHelper.CheckSuccess(response, out error)) { throw new NopException(error); } processPaymentResult.AuthorizationTransactionID = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.TransactionID; processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString(); //processPaymentResult.AuthorizationDate = response.Timestamp; //processPaymentResult.AuthorizationDate = DateTime.Now; if (transactionMode == TransactMode.Authorize) { processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized; } else { processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid; } }
public IPaymentResult CompletePayment(IInvoice invoice, IPayment payment, string token, string payerId) { var config = new Dictionary <string, string> { { "mode", "sandbox" }, { "account1.apiUsername", _settings.ApiUsername }, { "account1.apiPassword", _settings.ApiPassword }, { "account1.apiSignature", _settings.ApiSignature } }; var service = new PayPalAPIInterfaceServiceService(config); var getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq { GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token) }; var expressCheckoutDetailsResponse = service.GetExpressCheckoutDetails(getExpressCheckoutDetails); if (expressCheckoutDetailsResponse != null) { if (expressCheckoutDetailsResponse.Ack == AckCodeType.SUCCESS) { // do express checkout var doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq(); var doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType { Token = token, PayerID = payerId, PaymentDetails = new List <PaymentDetailsType> { GetPaymentDetails(invoice) } }; var doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails); doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest; var doExpressCheckoutPaymentResponse = service.DoExpressCheckoutPayment(doExpressCheckoutPayment); if (doExpressCheckoutPaymentResponse != null) { if (doExpressCheckoutPaymentResponse.Ack == AckCodeType.SUCCESS) { payment.Authorized = true; payment.Collected = true; return(new PaymentResult(Attempt <IPayment> .Succeed(payment), invoice, true)); } } } } return(new PaymentResult(Attempt <IPayment> .Succeed(payment), invoice, false)); }
public static PayPalConfirmPaymentModel GetPayment(string token) { if (string.IsNullOrEmpty(token)) { throw new ArgumentNullException("token"); } Dictionary <string, string> config = PayPal.Api.ConfigManager.Instance.GetProperties(); PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config); GetExpressCheckoutDetailsReq getECWrapper = new GetExpressCheckoutDetailsReq(); getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token); GetExpressCheckoutDetailsResponseType getECResponse = service.GetExpressCheckoutDetails(getECWrapper); DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType(); DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = requestDetails; requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails; requestDetails.Token = getECResponse.GetExpressCheckoutDetailsResponseDetails.Token; requestDetails.PayerID = getECResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID; DoExpressCheckoutPaymentReq wrapper = new DoExpressCheckoutPaymentReq(); wrapper.DoExpressCheckoutPaymentRequest = request; DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(wrapper); if (doECResponse.Ack == AckCodeType.SUCCESS) { var paymentInfo = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.First(); var confirmModel = new PayPalConfirmPaymentModel { Success = true, PaymentRequestID = paymentInfo.PaymentRequestID, OrderTotal = decimal.Parse(paymentInfo.GrossAmount.value), OrderDate = string.IsNullOrEmpty(paymentInfo.PaymentDate) ? DateTimeOffset.Parse(paymentInfo.PaymentDate) : (DateTimeOffset?)null }; return(confirmModel); } return(new PayPalConfirmPaymentModel { Success = false, ErrorMessage = string.Join(". ", doECResponse.Errors.Select(x => x.LongMessage).ToList()) }); }
protected void Submit_Click(object sender, EventArgs e) { // Configuration map containing signature credentials and other required configuration. // For a full list of configuration parameters refer in wiki page // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters] Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig(); // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap); GetExpressCheckoutDetailsReq getECWrapper = new GetExpressCheckoutDetailsReq(); // (Required) A timestamped token, the value of which was returned by SetExpressCheckout response. // Character length and limitations: 20 single-byte characters getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token.Value); // # API call // Invoke the GetExpressCheckoutDetails method in service wrapper object GetExpressCheckoutDetailsResponseType getECResponse = service.GetExpressCheckoutDetails(getECWrapper); // Create request object DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType(); DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = requestDetails; requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails; // (Required) The timestamped token value that was returned in the SetExpressCheckout response and passed in the GetExpressCheckoutDetails request. requestDetails.Token = token.Value; // (Required) Unique PayPal buyer account identification number as returned in the GetExpressCheckoutDetails response requestDetails.PayerID = payerId.Value; // (Required) How you want to obtain payment. It is one of the following values: // * Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture. // * Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture. // * Sale – This is a final sale for which you are requesting payment. // Note: You cannot set this value to Sale in the SetExpressCheckout request and then change this value to Authorization in the DoExpressCheckoutPayment request. requestDetails.PaymentAction = (PaymentActionCodeType) Enum.Parse(typeof(PaymentActionCodeType), paymentAction.SelectedValue); // Invoke the API DoExpressCheckoutPaymentReq wrapper = new DoExpressCheckoutPaymentReq(); wrapper.DoExpressCheckoutPaymentRequest = request; // # API call // Invoke the DoExpressCheckoutPayment method in service wrapper object DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(wrapper); // Check for API return status setKeyResponseObjects(service, doECResponse); }
/// <summary> /// The do express checkout payment. /// </summary> /// <param name="invoice"> /// The invoice. /// </param> /// <param name="payment"> /// The payment. /// </param> /// <param name="token"> /// The token. /// </param> /// <param name="payerId"> /// The payer id. /// </param> /// <param name="record"> /// The record of the transaction. /// </param> /// <returns> /// The <see cref="PayPalExpressTransactionRecord"/>. /// </returns> internal PayPalExpressTransactionRecord DoExpressCheckoutPayment(IInvoice invoice, IPayment payment, string token, string payerId, PayPalExpressTransactionRecord record) { var factory = new PayPalPaymentDetailsTypeFactory(); ExpressCheckoutResponse result = null; try { // do express checkout var request = new DoExpressCheckoutPaymentRequestType( new DoExpressCheckoutPaymentRequestDetailsType { Token = token, PayerID = payerId, PaymentDetails = new List <PaymentDetailsType> { factory.Build(invoice, PaymentActionCodeType.ORDER) } }); var doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq { DoExpressCheckoutPaymentRequest = request }; var service = GetPayPalService(); var response = service.DoExpressCheckoutPayment(doExpressCheckoutPayment); result = _responseFactory.Build(response, token); var transactionId = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; var currency = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.currencyID; var amount = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.value; record.Data.CheckoutPaymentTransactionId = transactionId; record.Data.CurrencyId = currency.ToString(); record.Data.AuthorizedAmount = amount; } catch (Exception ex) { result = _responseFactory.Build(ex); } record.DoExpressCheckoutPayment = result; record.Success = result.Success(); return(record); }
public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(string token, string payerID, string paymentAmount, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType, string invoiceId) { // Create the request object DoExpressCheckoutPaymentRequestType pp_request = new DoExpressCheckoutPaymentRequestType(); // Create the request details object pp_request.DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); pp_request.DoExpressCheckoutPaymentRequestDetails.Token = token; pp_request.DoExpressCheckoutPaymentRequestDetails.PayerID = payerID; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentAction = paymentAction; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails = new PaymentDetailsType(); pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails.InvoiceID = invoiceId; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails.OrderTotal = new BasicAmountType(); pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID = currencyCodeType; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails.OrderTotal.Value = paymentAmount; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails.ButtonSource = "BVCommerce_Cart_EC_US"; return((DoExpressCheckoutPaymentResponseType)caller.Call("DoExpressCheckoutPayment", pp_request)); }
public DoExpressCheckoutPaymentResponseType DoExpressCheckout(HttpResponseBase response, string token) { var getCheckoutRequest = new GetExpressCheckoutDetailsRequestType(); getCheckoutRequest.Token = token; var getCheckOutInfo = new GetExpressCheckoutDetailsReq(); getCheckOutInfo.GetExpressCheckoutDetailsRequest = getCheckoutRequest; var service = new PayPalAPIInterfaceServiceService(); var getResponse = service.GetExpressCheckoutDetails(getCheckOutInfo); var doRequest = new DoExpressCheckoutPaymentRequestType(); var requestInfo = new DoExpressCheckoutPaymentRequestDetailsType(); doRequest.DoExpressCheckoutPaymentRequestDetails = requestInfo; requestInfo.PaymentDetails = getResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails; requestInfo.Token = token; requestInfo.PayerID = getResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID; requestInfo.PaymentAction = PaymentActionCodeType.SALE; var wrapper = new DoExpressCheckoutPaymentReq(); wrapper.DoExpressCheckoutPaymentRequest = doRequest; return(service.DoExpressCheckoutPayment(wrapper)); }
public DoExpressCheckoutPaymentReq Do() { var paymentDetail = new PaymentDetailsType(); paymentDetail.PaymentAction = PaymentActionCodeType.SALE; paymentDetail.OrderTotal = new BasicAmountType(CurrencyCodeType.NZD, _details.Amount.ToCurrencyString()); var request = new DoExpressCheckoutPaymentRequestType { Version = PayPalConfig.VersionNumber }; var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType { PaymentDetails = paymentDetail.PutIntoList(), Token = _details.Token, PayerID = _details.PayerId }; request.DoExpressCheckoutPaymentRequestDetails = requestDetails; return(new DoExpressCheckoutPaymentReq { DoExpressCheckoutPaymentRequest = request }); }
public Commerce.Common.Transaction DoExpressCheckout(Commerce.Common.Order order, bool AuthOnly) { //validate that the token is applied to the BillingAddress //same with PayerID if (String.IsNullOrEmpty(order.BillingAddress.PayPalPayerID)) { throw new Exception("No payer ID set for the BillingAddress of the order"); } if (String.IsNullOrEmpty(order.BillingAddress.PayPalToken)) { throw new Exception("No Token set for the BillingAddress of the order"); } PayPalSvc.DoExpressCheckoutPaymentReq checkoutRequest = new DoExpressCheckoutPaymentReq(); DoExpressCheckoutPaymentRequestType checkoutReqType = new DoExpressCheckoutPaymentRequestType(); DoExpressCheckoutPaymentRequestDetailsType checkoutDetails = new DoExpressCheckoutPaymentRequestDetailsType(); PaymentDetailsType paymentDetails = new PaymentDetailsType(); if (!AuthOnly) { checkoutDetails.PaymentAction = PaymentActionCodeType.Sale; } else { checkoutDetails.PaymentAction = PaymentActionCodeType.Authorization; } int roundTo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits; checkoutDetails.Token = order.BillingAddress.PayPalToken; checkoutDetails.PayerID = order.BillingAddress.PayPalPayerID; checkoutReqType.Version = PayPalServiceUtility.PayPalAPIVersionNumber; decimal dTotal = order.OrderTotal; paymentDetails.OrderTotal = GetBasicAmount(RoundIt(dTotal, roundTo)); paymentDetails.ShippingTotal = this.GetBasicAmount(RoundIt(order.ShippingAmount, roundTo)); paymentDetails.TaxTotal = this.GetBasicAmount(RoundIt(order.TaxAmount, roundTo)); paymentDetails.Custom = order.OrderNumber; paymentDetails.ItemTotal = GetBasicAmount(RoundIt(order.CalculateSubTotal(), roundTo)); //paymentDetails.OrderDescription = orderDescription; //This tells PayPal that the dashCommerce is making the call. Please leave this //as it helps us keep going :):) (not monetarily, just with some love from PayPal). paymentDetails.ButtonSource = EC_BN_ID; //load up the payment items PaymentDetailsItemType item; int itemCount = order.Items.Count; PaymentDetailsItemType[] items = new PaymentDetailsItemType[itemCount]; for (int i = 0; i < itemCount; i++) { item = new PaymentDetailsItemType(); item.Name = order.Items[i].ProductName; item.Number = order.Items[i].Sku; item.Quantity = order.Items[i].Quantity.ToString(); item.Amount = GetBasicAmount(RoundIt(order.Items[i].PricePaid, roundTo)); items[i] = item; } paymentDetails.PaymentDetailsItem = items; checkoutRequest.DoExpressCheckoutPaymentRequest = checkoutReqType; checkoutRequest.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails = checkoutDetails; checkoutRequest.DoExpressCheckoutPaymentRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetails; PayPalSvc.DoExpressCheckoutPaymentResponseType response = service2.DoExpressCheckoutPayment(checkoutRequest); string errors = this.CheckErrors(response); string sOut = ""; Commerce.Common.Transaction trans = new Commerce.Common.Transaction(); if (errors == string.Empty) { trans.GatewayResponse = response.Ack.ToString(); trans.AuthorizationCode = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.TransactionID; } else { trans.GatewayResponse = errors; } //return out the transactionID return(trans); }
public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPayment(string token, string payerID, string paymentAmount, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType, string invoiceId) { // Create the request object DoExpressCheckoutPaymentRequestType pp_request = new DoExpressCheckoutPaymentRequestType(); // Create the request details object pp_request.DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); pp_request.DoExpressCheckoutPaymentRequestDetails.Token = token; pp_request.DoExpressCheckoutPaymentRequestDetails.PayerID = payerID; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentAction = paymentAction; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails = new PaymentDetailsType(); pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails.InvoiceID = invoiceId; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails.OrderTotal = new BasicAmountType(); pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID = currencyCodeType; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails.OrderTotal.Value = paymentAmount; pp_request.DoExpressCheckoutPaymentRequestDetails.PaymentDetails.ButtonSource = "BVCommerce_Cart_EC_US"; return (DoExpressCheckoutPaymentResponseType)caller.Call("DoExpressCheckoutPayment", pp_request); }
protected DoExpressCheckoutPaymentResponseType ECDoExpressCheckoutCode(string token, string payerID, string paymentAmount, PaymentActionCodeType paymentAction, CurrencyCodeType currencyCodeType) { var caller = CreateCaller(); var pp_request = new DoExpressCheckoutPaymentRequestType { Version = "51.0", DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType { Token = token, PayerID = payerID, PaymentAction = paymentAction, PaymentDetails = new PaymentDetailsType { OrderTotal = new BasicAmountType { currencyID = currencyCodeType, Value = paymentAmount } } } }; return (DoExpressCheckoutPaymentResponseType)caller.Call("DoExpressCheckoutPayment", pp_request); }
public PostProcessPaymentResponse PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest) { var paymentResponse = new PostProcessPaymentResponse(); var req = new DoExpressCheckoutPaymentReq(); var request = new DoExpressCheckoutPaymentRequestType(); var payment = postProcessPaymentRequest.Payment; var order = postProcessPaymentRequest.Order; req.DoExpressCheckoutPaymentRequest = request; request.Version = Settings.Version; var details = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = details; details.PaymentAction = PaymentActionCodeType.Authorization; details.PaymentActionSpecified = true; details.Token = postProcessPaymentRequest.Token; details.PayerID = postProcessPaymentRequest.PayerId; var payer = GetPayerInfo(postProcessPaymentRequest.Token, postProcessPaymentRequest.PayerId); var paymentDetail = new PaymentDetailsType(); paymentDetail.OrderTotal = new BasicAmountType(); paymentDetail.OrderTotal.Value = order.GrandTotal.Raw.WithTax.ToString("N", new CultureInfo("en-us")); var currencyCode = (CurrencyCodeType)Utils.GetEnumValueByName(typeof(CurrencyCodeType), order.CurrencyCode); paymentDetail.OrderTotal.currencyID = currencyCode; paymentDetail.ButtonSource = ""; paymentDetail.PaymentAction = PaymentActionCodeType.Authorization; paymentDetail.PaymentActionSpecified = true; PaymentDetailsType[] paymentDetails = { paymentDetail }; details.PaymentDetails = paymentDetails; // System.Net.ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); var credentials = PaypalSecurityHeader(); DoExpressCheckoutPaymentResponseType response = _paypalService2.DoExpressCheckoutPayment(ref credentials, req); if (response.Ack == AckCodeType.Success) { payment.PaymentMethod = "ExpressCheckout"; payment.CvcResult = payer.AccountVerifyCode; payment.AvsResult = payer.AddressVerifyCode; payment.Secure3DResult = ""; payment.CardHolderName = payer.Email; payment.IssuerCountry = payer.CountryCode; payment.CardNo = payer.PayerId; payment.IsVerify = payer.IsVerify; payment.IsValidAddress = payer.IsValidAddress; payment.Info1 = ""; if (!string.IsNullOrEmpty(payer.Address1)) { payment.Info1 = payer.Address1 + ", "; } if (!string.IsNullOrEmpty(payer.Address2)) { payment.Info1 = payment.Info1 + payer.Address2 + ", "; } if (!string.IsNullOrEmpty(payer.City)) { payment.Info1 = payment.Info1 + payer.City + ", "; } if (!string.IsNullOrEmpty(payer.State)) { payment.Info1 = payment.Info1 + payer.State + ", "; } if (!string.IsNullOrEmpty(payer.PostCode)) { payment.Info1 = payment.Info1 + payer.PostCode + ", "; } if (!string.IsNullOrEmpty(payer.CountryCode)) { payment.Info1 = payment.Info1 + payer.CountryCode; } var billAddress = new AddressModel { FirstName = payer.FirstName, LastName = payer.LastName, Address1 = payer.Address1, Address2 = payer.Address2, City = payer.City, State = payer.State, PostCode = payer.PostCode, Country = payer.Country, CountryCode = payer.CountryCode, PhoneNo = payer.CountryCode }; order.BillingAddress = billAddress;//Mapper.Map<PayerInfo, Address>(payer); paymentResponse.Payment = payment; paymentResponse.Order = order; paymentResponse.Payment.AuthCode = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; paymentResponse.Payment.Status = PaymentStatus.Authorized.GetHashCode(); } else { paymentResponse.Order = order; payment.Status = PaymentStatus.Declined.GetHashCode(); payment.IsValid = false; paymentResponse.Payment = payment; paymentResponse.AddError("decline"); foreach (var er in response.Errors) { paymentResponse.AddError(er.ErrorCode + " : " + er.ShortMessage); } } //if (Settings.IsImmediateCapture) //{ // var capturePaymentRequest = new CapturePaymentRequest(); // var pRes = new CapturePaymentResult(); // capturePaymentRequest.CurrencyCode = order.CurrencyCode; // capturePaymentRequest.CaptureTransactionId = Convert.ToString(paymentResponse.Payment.AuthCode); // capturePaymentRequest.OrderTotal = paymentResponse.Payment.OrderAmount; // pRes = Capture(capturePaymentRequest); // if (pRes.Success && string.IsNullOrEmpty(pRes.CaptureTransactionCode) == false) // { // paymentResponse.Payment.AuthCode = pRes.CaptureTransactionCode; // paymentResponse.Payment.Status = PaymentStatus.Paid.GetHashCode(); // paymentResponse.Payment.PaidAmount = capturePaymentRequest.OrderTotal; // paymentResponse.Order.PaymentStatus = PaymentStatus.Paid; // } // else // { // paymentResponse.Payment.PSPResponseMessage = pRes.CaptureTransactionResult; // } //} return(paymentResponse); }
private ActionResult ProcessingResult_PayPal(ProcessingResultModel model) { if (model == null) { throw new System.ArgumentNullException("model"); } PaymentResultContext context = new PaymentResultContext(); context.Order = model.order; if (model.success == true) { if (model.token == null) { throw new System.ArgumentNullException("token"); } if (model.payerID == null) { throw new System.ArgumentNullException("payerID"); } GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType(); request.Version = "104.0"; request.Token = model.token; GetExpressCheckoutDetailsReq wrapper = new GetExpressCheckoutDetailsReq(); wrapper.GetExpressCheckoutDetailsRequest = request; System.Collections.Generic.Dictionary <string, string> config = PaymentController.PayPal_CreateConfig(); PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config); GetExpressCheckoutDetailsResponseType ecResponse = service.GetExpressCheckoutDetails(wrapper); if (ecResponse == null) { throw new System.Exception("checkout details result is null"); } if (ecResponse.Errors != null && ecResponse.Errors.Count > 0) { ecResponse.Errors.ForEach(delegate(ErrorType m) { context.Errors.Add(m.LongMessage); }); } if (ecResponse.Ack == AckCodeType.SUCCESS || ecResponse.Ack == AckCodeType.SUCCESSWITHWARNING) { GetExpressCheckoutDetailsResponseDetailsType details = ecResponse.GetExpressCheckoutDetailsResponseDetails; if (details == null) { throw new System.Exception("details object is null"); } if (string.IsNullOrEmpty(details.InvoiceID)) { throw new System.Exception("invoiceID not found"); } if (details.PaymentDetails == null) { throw new System.Exception("payment details is null"); } System.Collections.Generic.List <PaymentDetailsType> paymentDetails = new System.Collections.Generic.List <PaymentDetailsType>(); foreach (PaymentDetailsType payment in details.PaymentDetails) { paymentDetails.Add(new PaymentDetailsType { NotifyURL = null, PaymentAction = payment.PaymentAction, OrderTotal = payment.OrderTotal }); } DoExpressCheckoutPaymentRequestType paymentRequest = new DoExpressCheckoutPaymentRequestType(); paymentRequest.Version = "104.0"; paymentRequest.DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType { PaymentDetails = paymentDetails, Token = model.token, PayerID = model.payerID }; DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(new DoExpressCheckoutPaymentReq { DoExpressCheckoutPaymentRequest = paymentRequest }); if (doECResponse == null) { throw new System.Exception("payment result is null"); } if (doECResponse.Errors != null && doECResponse.Errors.Count > 0) { doECResponse.Errors.ForEach(delegate(ErrorType m) { context.Errors.Add(m.LongMessage); }); } if (doECResponse.Ack == AckCodeType.SUCCESS || doECResponse.Ack == AckCodeType.SUCCESSWITHWARNING) { ConfirmInvoiceResult invoiceResult = BookingProvider.ConfirmInvoice(details.InvoiceID.Trim()); Tracing.DataTrace.TraceEvent(TraceEventType.Information, 0, "PAYPAL transaction: invoice: '{0}', invoice confirmation: '{1}'", new object[] { details.InvoiceID, invoiceResult.IsSuccess ? "SUCCESS" : "FAILED" }); if (!invoiceResult.IsSuccess) { context.Errors.Add(string.Format("invoice confirmation error: {0}", invoiceResult.ErrorMessage)); } else { context.Success = true; BookingProvider.AcceptInvoice(Convert.ToInt32(context.Order)); } } } } else { context.Errors.Add(PaymentStrings.PaymentCancelled); } return(base.View("_ProcessingResult", context)); }
/// <summary> /// The do express checkout payment. /// </summary> /// <param name="invoice"> /// The invoice. /// </param> /// <param name="payment"> /// The payment. /// </param> /// <param name="token"> /// The token. /// </param> /// <param name="payerId"> /// The payer id. /// </param> /// <param name="record"> /// The record of the transaction. /// </param> /// <returns> /// The <see cref="PayPalExpressTransactionRecord"/>. /// </returns> internal PayPalExpressTransactionRecord DoExpressCheckoutPayment(IInvoice invoice, IPayment payment, string token, string payerId, PayPalExpressTransactionRecord record) { var factory = new PayPalPaymentDetailsTypeFactory(); ExpressCheckoutResponse result = null; try { // do express checkout var request = new DoExpressCheckoutPaymentRequestType( new DoExpressCheckoutPaymentRequestDetailsType { Token = token, PayerID = payerId, PaymentDetails = new List<PaymentDetailsType> { factory.Build(invoice, PaymentActionCodeType.ORDER) } }); var doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq { DoExpressCheckoutPaymentRequest = request }; var service = GetPayPalService(); var response = service.DoExpressCheckoutPayment(doExpressCheckoutPayment); result = _responseFactory.Build(response, token); var transactionId = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; var currency = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.currencyID; var amount = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.value; record.Data.CheckoutPaymentTransactionId = transactionId; record.Data.CurrencyId = currency.ToString(); record.Data.AuthorizedAmount = amount; } catch (Exception ex) { result = _responseFactory.Build(ex); } record.DoExpressCheckoutPayment = result; record.Success = result.Success(); return record; }
/// <summary> /// Processes the payment. Can be used for both positive and negative transactions. /// </summary> /// <param name="payment">The payment.</param> /// <param name="message">The message.</param> /// <returns></returns> public override bool ProcessPayment(Payment payment, ref string message) { try { payment.Status = PaymentStatus.Processing.ToString(); //ContractId - used as paypal PayerID var payerId = payment.ContractId; //ValidationCode - used as paypal token var token = payment.AuthorizationCode; if (string.IsNullOrEmpty(payerId) || string.IsNullOrEmpty(token)) { return(false); } // Create the PayPalAPIInterfaceServiceService service object to make the API call var service = new PayPalAPIInterfaceServiceService((Dictionary <string, string>)Settings); var getECWrapper = new GetExpressCheckoutDetailsReq(); getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token); var getECResponse = service.GetExpressCheckoutDetails(getECWrapper); var request = new DoExpressCheckoutPaymentRequestType(); var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = requestDetails; requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails; requestDetails.Token = token; requestDetails.PayerID = payerId; requestDetails.PaymentAction = PaymentActionCodeType.SALE; // Invoke the API var wrapper = new DoExpressCheckoutPaymentReq(); wrapper.DoExpressCheckoutPaymentRequest = request; var doECResponse = service.DoExpressCheckoutPayment(wrapper); if (doECResponse.Ack.Equals(AckCodeType.FAILURE) || (doECResponse.Errors != null && doECResponse.Errors.Count > 0)) { return(false); } else { switch (doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus) { case PaymentStatusCodeType.COMPLETED: payment.Status = PaymentStatus.Completed.ToString(); break; case PaymentStatusCodeType.INPROGRESS: payment.Status = PaymentStatus.Processing.ToString(); break; case PaymentStatusCodeType.DENIED: payment.Status = PaymentStatus.Denied.ToString(); break; case PaymentStatusCodeType.FAILED: payment.Status = PaymentStatus.Failed.ToString(); break; default: payment.Status = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PaymentStatus .ToString(); break; } } } catch (Exception ex) { message = ex.Message; return(false); } return(true); }
//public PaypalPayer GetExpressCheckout(IPaymentGatewaySettings settings,string token) //{ // GetExpressCheckoutDetailsReq req = new GetExpressCheckoutDetailsReq(); // GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType(); // req.GetExpressCheckoutDetailsRequest = request; // CustomSecurityHeaderType securityHeader = GetCustomSecurityHeader(settings); // request.Token = token; // request.Version = API_VERSION; // GetExpressCheckoutDetailsResponseType response = GetPayPalAAInterfaceClient(settings).GetExpressCheckoutDetails(ref securityHeader, req); // if (response.Ack != AckCodeType.Success || response.Ack != AckCodeType.SuccessWithWarning) // throw new PaymentServiceException(String.Format("Could not obtain Express Checkoutinformation. PayPal response was : {0}", // String.Join(response.Errors.Select(n => String.Format("Error Code: {0} Error Message: {1};", n.ErrorCode, n.LongMessage)).ToArray()))); // if (!PaypalHelper.CheckSuccess(response, out error)) // throw new NopException(error); // PaypalPayer payer = new PaypalPayer(); // payer.PayerEmail = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Payer; // payer.FirstName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.FirstName; // payer.LastName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerName.LastName; // payer.CompanyName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerBusiness; // payer.Address1 = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street1; // payer.Address2 = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Street2; // payer.City = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CityName; // payer.State = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.StateOrProvince; // payer.Zipcode = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.PostalCode; // payer.Phone = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.ContactPhone; // payer.PaypalCountryName = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.CountryName; // payer.CountryCode = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.Address.Country.ToString(); // payer.PayerID = response.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID; // payer.Token = response.GetExpressCheckoutDetailsResponseDetails.Token; // return payer; //} void DoExpressCheckout(string token) { DoExpressCheckoutPaymentReq req = new DoExpressCheckoutPaymentReq(); DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType(); req.DoExpressCheckoutPaymentRequest = request; request.Version = API_VERSION; DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = details; details.PaymentAction = _PaymentActionCodeType; details.PaymentActionSpecified = true; details.Token = token; }
//GET : PayPal/PaymentSuccess public async Task <ActionResult> PaymentSuccess(Guid invoiceId) { GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType(); request.Version = "104.0"; request.Token = Request["token"]; GetExpressCheckoutDetailsReq wrapper = new GetExpressCheckoutDetailsReq(); wrapper.GetExpressCheckoutDetailsRequest = request; //define sdk configuration Dictionary <string, string> sdkConfig = new Dictionary <string, string>(); sdkConfig.Add("mode", ConfigurationManager.AppSettings["paypal.mode"]); sdkConfig.Add("account1.apiUsername", ConfigurationManager.AppSettings["paypal.apiUsername"]); sdkConfig.Add("account1.apiPassword", ConfigurationManager.AppSettings["paypal.apiPassword"]); sdkConfig.Add("account1.apiSignature", ConfigurationManager.AppSettings["paypal.apiSignature"]); // sdkConfig.Add("acct1.UserName", ConfigurationManager.AppSettings["paypal.apiUsername"]); // sdkConfig.Add("acct1.Password", ConfigurationManager.AppSettings["paypal.apiPassword"]); // sdkConfig.Add("acct1.Signature", ConfigurationManager.AppSettings["paypal.apiSignature"]); PayPalAPIInterfaceServiceService s = new PayPalAPIInterfaceServiceService(sdkConfig); GetExpressCheckoutDetailsResponseType ecResponse = s.GetExpressCheckoutDetails(wrapper); if (ecResponse.Ack.HasValue && ecResponse.Ack.Value.ToString() != "FAILURE" && ecResponse.Errors.Count == 0) { double paymentAmount = 0.0; double.TryParse(ecResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails.FirstOrDefault().OrderTotal.value, out paymentAmount); PaymentDetailsType paymentDetail = new PaymentDetailsType(); paymentDetail.NotifyURL = "http://replaceIpnUrl.com"; paymentDetail.PaymentAction = (PaymentActionCodeType)EnumUtils.GetValue("Sale", typeof(PaymentActionCodeType)); paymentDetail.OrderTotal = new BasicAmountType((CurrencyCodeType)EnumUtils.GetValue("USD", typeof(CurrencyCodeType)), paymentAmount + ""); List <PaymentDetailsType> paymentDetails = new List <PaymentDetailsType>(); paymentDetails.Add(paymentDetail); DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequestType = new DoExpressCheckoutPaymentRequestType(); request.Version = "104.0"; DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); requestDetails.PaymentDetails = paymentDetails; requestDetails.Token = Request["token"]; requestDetails.PayerID = Request["PayerID"]; doExpressCheckoutPaymentRequestType.DoExpressCheckoutPaymentRequestDetails = requestDetails; DoExpressCheckoutPaymentReq doExpressCheckoutPaymentReq = new DoExpressCheckoutPaymentReq(); doExpressCheckoutPaymentReq.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequestType; s = new PayPalAPIInterfaceServiceService(sdkConfig); DoExpressCheckoutPaymentResponseType doECResponse = s.DoExpressCheckoutPayment(doExpressCheckoutPaymentReq); if (doECResponse.Ack.HasValue && doECResponse.Ack.Value.ToString() != "FAILURE" && doECResponse.Errors.Count == 0) { //create payment object for invoice PaymentService paymentService = new PaymentService(this.db); PaymentMethodService paymentMethodService = new PaymentMethodService(this.db); var ccPymtMethod = paymentMethodService.GetCreditCardPaymentMethod(UserContact); if (ccPymtMethod == null) { try { PaymentMethodTypeService paymentMethodTypeService = new PaymentMethodTypeService(this.db); string ccTypeCode = GNPaymentMethodType.Types.CREDIT_CARD.GetCode(); var ccType = this.db.GNPaymentMethodTypes .Where(pt => pt.Name == ccTypeCode).FirstOrDefault(); await paymentMethodService.Insert(UserContact, new GNPaymentMethod { GNAccountId = UserContact.GNOrganization.Account.Id, GNPaymentMethodTypeId = ccType.Id, Description = "PAYPAL", IsDefault = true, IsActive = true, UsedForRecurrentPayments = false, PCITokenId = "X", LastFourDigits = "X", ExpirationDate = DateTime.MaxValue, CreateDateTime = DateTime.Now, CreatedBy = UserContact.Id }); } catch (Exception e) { LogUtil.Error(logger, "Error adding PayPal Credit Card payment method!!", e); } ccPymtMethod = paymentMethodService.GetCreditCardPaymentMethod(UserContact); if (ccPymtMethod == null) { throw new Exception("Credit Card Payment Method Not Found!!"); } } var ecPaymentInfo = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.FirstOrDefault(); double grossAmount = 0.0; double.TryParse(ecPaymentInfo.GrossAmount.value, out grossAmount); if (grossAmount != 0.0) { try { var payment = new GNPayment { Id = Guid.NewGuid(), GNInvoiceId = invoiceId, GNPaymentMethodId = ccPymtMethod.Id, PaymentDate = DateTime.Now, TotalAmount = grossAmount, Status = ecPaymentInfo.PaymentStatus.Value.ToString(), ExternalTxnId = ecPaymentInfo.TransactionID, CreateDateTime = DateTime.Now, CreatedBy = UserContact.Id }; this.AddInvoiceToPayment(payment); await paymentService.Insert(UserContact, payment); } catch (Exception e) { LogUtil.Error(logger, "Error inserting payment!!", e); } } else { throw new Exception("Payment Amount of 0.0 Not Allowed!!"); } } } return(RedirectToAction("MyBillingPayments", "Account")); }
protected void Page_Load(object sender, EventArgs e) { HttpContext CurrContext = HttpContext.Current; // Create the DoExpressCheckoutPaymentResponseType object DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType = new DoExpressCheckoutPaymentResponseType(); try { // Create the DoExpressCheckoutPaymentReq object DoExpressCheckoutPaymentReq doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq(); DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); // The timestamped token value that was returned in the // `SetExpressCheckout` response and passed in the // `GetExpressCheckoutDetails` request. doExpressCheckoutPaymentRequestDetails.Token = (string)(Session["EcToken"]); // Unique paypal buyer account identification number as returned in // `GetExpressCheckoutDetails` Response doExpressCheckoutPaymentRequestDetails.PayerID = (string)(Session["PayerId"]); // # Payment Information // list of information about the payment List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>(); // information about the payment PaymentDetailsType paymentDetails = new PaymentDetailsType(); CurrencyCodeType currency_code_type = (CurrencyCodeType)(Session["currency_code_type"]); PaymentActionCodeType payment_action_type = (PaymentActionCodeType)(Session["payment_action_type"]); //Pass the order total amount which was already set in session string total_amount = (string)(Session["Total_Amount"]); BasicAmountType orderTotal = new BasicAmountType(currency_code_type, total_amount); paymentDetails.OrderTotal = orderTotal; paymentDetails.PaymentAction = payment_action_type; //BN codes to track all transactions paymentDetails.ButtonSource = BNCode; // Unique identifier for the merchant. SellerDetailsType sellerDetails = new SellerDetailsType(); sellerDetails.PayPalAccountID = (string)(Session["SellerEmail"]); paymentDetails.SellerDetails = sellerDetails; paymentDetailsList.Add(paymentDetails); doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList; DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails); doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest; // Create the service wrapper object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(); // # API call // Invoke the DoExpressCheckoutPayment method in service wrapper object responseDoExpressCheckoutPaymentResponseType = service.DoExpressCheckoutPayment(doExpressCheckoutPayment); if (responseDoExpressCheckoutPaymentResponseType != null) { // Response envelope acknowledgement string acknowledgement = "DoExpressCheckoutPayment API Operation - "; acknowledgement += responseDoExpressCheckoutPaymentResponseType.Ack.ToString(); //logger.Info(acknowledgement + "\n"); System.Diagnostics.Debug.WriteLine(acknowledgement + "\n"); // # Success values if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS")) { // Transaction identification number of the transaction that was // created. // This field is only returned after a successful transaction // for DoExpressCheckout has occurred. if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null) { IEnumerator <PaymentInfoType> paymentInfoIterator = responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator(); while (paymentInfoIterator.MoveNext()) { PaymentInfoType paymentInfo = paymentInfoIterator.Current; //logger.Info("Transaction ID : " + paymentInfo.TransactionID + "\n"); Session["Transaction_Id"] = paymentInfo.TransactionID; Session["Transaction_Type"] = paymentInfo.TransactionType; Session["Payment_Status"] = paymentInfo.PaymentStatus; Session["Payment_Type"] = paymentInfo.PaymentType; Session["Payment_Total_Amount"] = paymentInfo.GrossAmount.value; System.Diagnostics.Debug.WriteLine("Transaction ID : " + paymentInfo.TransactionID + "\n"); } } } // # Error Values else { List <ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors; string errorMessage = ""; foreach (ErrorType error in errorMessages) { //logger.Debug("API Error Message : " + error.LongMessage); System.Diagnostics.Debug.WriteLine("API Error Message : " + error.LongMessage + "\n"); errorMessage = errorMessage + error.LongMessage; } //Redirect to error page in case of any API errors CurrContext.Items.Add("APIErrorMessage", errorMessage); Server.Transfer("~/Response.aspx"); } } } catch (System.Exception ex) { // Log the exception message //logger.Debug("Error Message : " + ex.Message); System.Diagnostics.Debug.WriteLine("Error Message : " + ex.Message); } }
public IPaymentResult AuthorizePayment(IInvoice invoice, IPayment payment, string token, string payerId) { var service = GetPayPalService(); var getExpressCheckoutReq = new GetExpressCheckoutDetailsReq() { GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token) }; GetExpressCheckoutDetailsResponseType expressCheckoutDetailsResponse; try { expressCheckoutDetailsResponse = service.GetExpressCheckoutDetails(getExpressCheckoutReq); if (expressCheckoutDetailsResponse.Ack != AckCodeType.SUCCESS && expressCheckoutDetailsResponse.Ack != AckCodeType.SUCCESSWITHWARNING) { return(new PaymentResult(Attempt <IPayment> .Fail(payment, CreateErrorResult(expressCheckoutDetailsResponse.Errors)), invoice, false)); } } catch (Exception ex) { return(new PaymentResult(Attempt <IPayment> .Fail(payment, ex), invoice, false)); } // check if already do if (payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.PaymentAuthorized) != "true") { // do express checkout var doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(new DoExpressCheckoutPaymentRequestDetailsType { Token = token, PayerID = payerId, PaymentDetails = new List <PaymentDetailsType> { CreatePayPalPaymentDetails(invoice) } }); var doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq() { DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest }; DoExpressCheckoutPaymentResponseType doExpressCheckoutPaymentResponse; try { doExpressCheckoutPaymentResponse = service.DoExpressCheckoutPayment(doExpressCheckoutPayment); if (doExpressCheckoutPaymentResponse.Ack != AckCodeType.SUCCESS && doExpressCheckoutPaymentResponse.Ack != AckCodeType.SUCCESSWITHWARNING) { return(new PaymentResult(Attempt <IPayment> .Fail(payment, CreateErrorResult(doExpressCheckoutPaymentResponse.Errors)), invoice, false)); } } catch (Exception ex) { return(new PaymentResult(Attempt <IPayment> .Fail(payment, ex), invoice, false)); } var transactionId = doExpressCheckoutPaymentResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; var currency = doExpressCheckoutPaymentResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.currencyID; var amount = doExpressCheckoutPaymentResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].GrossAmount.value; // do authorization var doAuthorizationResponse = service.DoAuthorization(new DoAuthorizationReq { DoAuthorizationRequest = new DoAuthorizationRequestType { TransactionID = transactionId, Amount = new BasicAmountType(currency, amount) } }); if (doAuthorizationResponse.Ack != AckCodeType.SUCCESS && doAuthorizationResponse.Ack != AckCodeType.SUCCESSWITHWARNING) { return(new PaymentResult(Attempt <IPayment> .Fail(payment, CreateErrorResult(doAuthorizationResponse.Errors)), invoice, false)); } payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AuthorizationId, doAuthorizationResponse.TransactionID); payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.AmountCurrencyId, currency.ToString()); payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.PaymentAuthorized, "true"); } payment.Authorized = true; return(new PaymentResult(Attempt <IPayment> .Succeed(payment), invoice, true)); }
public PaymentResponse Payment(string token, string payerId) { // Configuration map containing signature credentials and other required configuration. // For a full list of configuration parameters refer in wiki page // [https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters] // Create the PayPalAPIInterfaceServiceService service object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(_payPalConfiguration); GetExpressCheckoutDetailsReq getECWrapper = new GetExpressCheckoutDetailsReq(); // (Required) A timestamped token, the value of which was returned by SetExpressCheckout response. // Character length and limitations: 20 single-byte characters getECWrapper.GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token); // # API call // Invoke the GetExpressCheckoutDetails method in service wrapper object GetExpressCheckoutDetailsResponseType getECResponse = service.GetExpressCheckoutDetails(getECWrapper); // Create request object DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType(); DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = requestDetails; requestDetails.ButtonSource = "PTSH"; requestDetails.PaymentDetails = getECResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails; // (Required) The timestamped token value that was returned in the SetExpressCheckout response and passed in the GetExpressCheckoutDetails request. requestDetails.Token = token; // (Required) Unique PayPal buyer account identification number as returned in the GetExpressCheckoutDetails response requestDetails.PayerID = payerId; // (Required) How you want to obtain payment. It is one of the following values: // * Authorization – This payment is a basic authorization subject to settlement with PayPal Authorization and Capture. // * Order – This payment is an order authorization subject to settlement with PayPal Authorization and Capture. // * Sale – This is a final sale for which you are requesting payment. // Note: You cannot set this value to Sale in the SetExpressCheckout request and then change this value to Authorization in the DoExpressCheckoutPayment request. requestDetails.PaymentAction = PaymentActionCodeType.SALE; // Invoke the API DoExpressCheckoutPaymentReq wrapper = new DoExpressCheckoutPaymentReq(); wrapper.DoExpressCheckoutPaymentRequest = request; // # API call // Invoke the DoExpressCheckoutPayment method in service wrapper object DoExpressCheckoutPaymentResponseType doECResponse = service.DoExpressCheckoutPayment(wrapper); // Check for API return status if (doECResponse.Ack.Equals(AckCodeType.FAILURE) || (doECResponse.Errors != null && doECResponse.Errors.Any())) { return(null); } string transactionId = doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; if (doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason != null && doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason != PendingStatusCodeType.NONE) { CancelTransaction(transactionId); throw new Exception( doECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].PendingReason.ToString() + transactionId); } return(new PaymentResponse { TransactionId = transactionId, Price = float.Parse(requestDetails.PaymentDetails[0].OrderTotal.value) }); }
/// <summary> /// Do paypal express checkout /// </summary> /// <param name="paymentInfo">Payment info required for an order processing</param> /// <param name="orderGuid">Unique order identifier</param> /// <param name="processPaymentResult">Process payment result</param> public void DoExpressCheckout(PaymentInfo paymentInfo, Guid orderGuid, ProcessPaymentResult processPaymentResult) { InitSettings(); TransactMode transactionMode = GetCurrentTransactionMode(); DoExpressCheckoutPaymentReq req = new DoExpressCheckoutPaymentReq(); DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType(); req.DoExpressCheckoutPaymentRequest = request; request.Version = this.APIVersion; DoExpressCheckoutPaymentRequestDetailsType details = new DoExpressCheckoutPaymentRequestDetailsType(); request.DoExpressCheckoutPaymentRequestDetails = details; if (transactionMode == TransactMode.Authorize) { details.PaymentAction = PaymentActionCodeType.Authorization; } else { details.PaymentAction = PaymentActionCodeType.Sale; } details.PaymentActionSpecified = true; details.Token = paymentInfo.PaypalToken; details.PayerID = paymentInfo.PaypalPayerId; details.PaymentDetails = new PaymentDetailsType[1]; PaymentDetailsType paymentDetails1 = new PaymentDetailsType(); details.PaymentDetails[0] = paymentDetails1; paymentDetails1.OrderTotal = new BasicAmountType(); paymentDetails1.OrderTotal.Value = paymentInfo.OrderTotal.ToString("N", new CultureInfo("en-us")); paymentDetails1.OrderTotal.currencyID = PaypalHelper.GetPaypalCurrency(IoC.Resolve <ICurrencyService>().PrimaryStoreCurrency); paymentDetails1.Custom = orderGuid.ToString(); paymentDetails1.ButtonSource = "nopCommerceCart"; DoExpressCheckoutPaymentResponseType response = service2.DoExpressCheckoutPayment(req); string error; if (!PaypalHelper.CheckSuccess(response, out error)) { throw new NopException(error); } if (response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null && response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0] != null) { processPaymentResult.AuthorizationTransactionId = response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; processPaymentResult.AuthorizationTransactionResult = response.Ack.ToString(); if (transactionMode == TransactMode.Authorize) { processPaymentResult.PaymentStatus = PaymentStatusEnum.Authorized; } else { processPaymentResult.PaymentStatus = PaymentStatusEnum.Paid; } } else { throw new NopException("response.DoExpressCheckoutPaymentResponseDetails.PaymentInfo is null"); } }
/// <summary> /// Charges the specified payment info. /// </summary> /// <param name="financialGateway">The financial gateway.</param> /// <param name="paymentInfo">The payment info.</param> /// <param name="errorMessage">The error message.</param> /// <returns></returns> public override FinancialTransaction Charge(FinancialGateway financialGateway, PaymentInfo paymentInfo, out string errorMessage) { errorMessage = string.Empty; if (!(paymentInfo is PayPalExpress.PayPalPaymentInfo)) { errorMessage = "PaymentInfo object must be of type PayPalPaymentInfo in order to charge a PayPal Express transaction."; return(null); } PayPalPaymentInfo payPalPaymentInfo = (PayPalPaymentInfo)paymentInfo; // Create the DoExpressCheckoutPaymentResponseType object DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType = new DoExpressCheckoutPaymentResponseType(); try { // Create the DoExpressCheckoutPaymentReq object DoExpressCheckoutPaymentReq doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq(); DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); // The timestamped token value that was returned in the // `SetExpressCheckout` response and passed in the // `GetExpressCheckoutDetails` request. doExpressCheckoutPaymentRequestDetails.Token = payPalPaymentInfo.Token; // Unique paypal buyer account identification number as returned in // `GetExpressCheckoutDetails` Response doExpressCheckoutPaymentRequestDetails.PayerID = payPalPaymentInfo.PayerId; // # Payment Information // list of information about the payment List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>(); // information about the first payment PaymentDetailsType paymentDetails = new PaymentDetailsType(); BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.USD, paymentInfo.Amount.ToString()); paymentDetails.OrderTotal = orderTotal; // We are actually capturing this payment now. paymentDetails.PaymentAction = PaymentActionCodeType.SALE; // Unique identifier for the merchant. For parallel payments, this field // is required and must contain the Payer Id or the email address of the // merchant. String apiUsername = Encryption.DecryptString(financialGateway.GetAttributeValue("PayPalAPIUsername")); SellerDetailsType sellerDetails = new SellerDetailsType(); sellerDetails.PayPalAccountID = apiUsername; paymentDetailsList.Add(paymentDetails); doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList; DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails); doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest; // Create the service wrapper object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(GetCredentials(financialGateway)); // # API call // Invoke the DoExpressCheckoutPayment method in service wrapper object responseDoExpressCheckoutPaymentResponseType = service.DoExpressCheckoutPayment(doExpressCheckoutPayment); if (responseDoExpressCheckoutPaymentResponseType != null) { // # Success values if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS")) { // Transaction identification number of the transaction that was // created. // This field is only returned after a successful transaction // for DoExpressCheckout has occurred. if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null) { IEnumerator <PaymentInfoType> paymentInfoIterator = responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator(); while (paymentInfoIterator.MoveNext()) { PaymentInfoType ppPaymentInfo = paymentInfoIterator.Current; var transaction = new FinancialTransaction(); transaction.TransactionCode = ppPaymentInfo.TransactionID; return(transaction); } } } // # Error Values else { List <ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors; foreach (ErrorType error in errorMessages) { errorMessage += "API Error Message : " + error.LongMessage + "\n"; } } } } // # Exception log catch (System.Exception ex) { errorMessage += "Error Message : " + ex.Message; } return(null); }
public static String ProcessEC(ShoppingCart cart, decimal OrderTotal, int OrderNumber, String PayPalToken, String PayerID, String TransactionMode, out String AuthorizationResult, out String AuthorizationTransID) { PayPalAPISoapBinding IPayPalRefund; PayPalAPIAASoapBinding IPayPal; PayPalController.GetPaypalRequirements(out IPayPalRefund, out IPayPal); String result = String.Empty; AuthorizationResult = String.Empty; AuthorizationTransID = String.Empty; DoExpressCheckoutPaymentReq ECRequest = new DoExpressCheckoutPaymentReq(); DoExpressCheckoutPaymentRequestType varECRequest = new DoExpressCheckoutPaymentRequestType(); DoExpressCheckoutPaymentRequestDetailsType varECRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); DoExpressCheckoutPaymentResponseType ECResponse = new DoExpressCheckoutPaymentResponseType(); DoExpressCheckoutPaymentResponseDetailsType varECResponse = new DoExpressCheckoutPaymentResponseDetailsType(); ECRequest.DoExpressCheckoutPaymentRequest = varECRequest; varECRequest.DoExpressCheckoutPaymentRequestDetails = varECRequestDetails; ECResponse.DoExpressCheckoutPaymentResponseDetails = varECResponse; varECRequestDetails.Token = PayPalToken; varECRequestDetails.PayerID = PayerID; varECRequestDetails.PaymentAction = PaymentActionCodeType.Authorization; if (TransactionMode == AppLogic.ro_TXModeAuthCapture || AppLogic.AppConfigBool("PayPal.ForceCapture") || PayPalController.GetAppropriateExpressType() == ExpressAPIType.PayPalAcceleratedBording) { varECRequestDetails.PaymentAction = PaymentActionCodeType.Sale; } varECRequestDetails.PaymentActionSpecified = true; PaymentDetailsType ECPaymentDetails = new PaymentDetailsType(); BasicAmountType ECPaymentOrderTotal = new BasicAmountType(); ECPaymentOrderTotal.Value = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal); ECPaymentOrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true); ECPaymentDetails.InvoiceID = OrderNumber.ToString(); ECPaymentDetails.Custom = cart.ThisCustomer.CustomerID.ToString(); ECPaymentDetails.ButtonSource = PayPalController.BN + "_EC_US"; ECPaymentDetails.NotifyURL = AppLogic.GetStoreHTTPLocation(true) + AppLogic.AppConfig("PayPal.NotificationURL"); varECRequest.Version = API_VER; ECPaymentDetails.OrderTotal = ECPaymentOrderTotal; List <PaymentDetailsType> ECPaymentDetailsList = new List <PaymentDetailsType>(); ECPaymentDetailsList.Add(ECPaymentDetails); varECRequestDetails.PaymentDetails = ECPaymentDetailsList.ToArray(); ECResponse = IPayPal.DoExpressCheckoutPayment(ECRequest); if (ECResponse.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase)) { AuthorizationTransID = CommonLogic.IIF(varECRequestDetails.PaymentAction == PaymentActionCodeType.Sale, "CAPTURE=", "AUTH=") + ECResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; result = AppLogic.ro_OK; AuthorizationResult = ECResponse.Ack.ToString(); SetECFaultRedirect(cart.ThisCustomer, string.Empty); } else { if (ECResponse.Errors != null) { if (ECResponse.Errors.Any(e => e.ErrorCode == ECFaultRedirectErrorCode.ToString())) { // Express Checkout failed funding recovery feature returns a 10486 which signifies that // the user should be redirected back to paypal. result = AuthorizationResult = AppLogic.ro_PMPayPalExpressRedirect; } else { result = AuthorizationResult = string.Join(",", ECResponse.Errors.Select(e => e.LongMessage).ToArray()); } } } return(result); }
// # DoExpressCheckoutPayment API Operation // The DoExpressCheckoutPayment API operation completes an Express Checkout transaction. // If you set up a billing agreement in your SetExpressCheckout API call, // the billing agreement is created when you call the DoExpressCheckoutPayment API operation. public DoExpressCheckoutPaymentResponseType DoExpressCheckoutPaymentAPIOperation() { // Create the DoExpressCheckoutPaymentResponseType object DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType = new DoExpressCheckoutPaymentResponseType(); try { // Create the DoExpressCheckoutPaymentReq object DoExpressCheckoutPaymentReq doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq(); DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); // The timestamped token value that was returned in the // `SetExpressCheckout` response and passed in the // `GetExpressCheckoutDetails` request. doExpressCheckoutPaymentRequestDetails.Token = "EC-3PG29673CT337061M"; // Unique paypal buyer account identification number as returned in // `GetExpressCheckoutDetails` Response doExpressCheckoutPaymentRequestDetails.PayerID = "WJ3Q38FZ9FDYS"; // # Payment Information // list of information about the payment List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>(); // information about the first payment PaymentDetailsType paymentDetails1 = new PaymentDetailsType(); // Total cost of the transaction to the buyer. If shipping cost and tax // charges are known, include them in this value. If not, this value // should be the current sub-total of the order. // // If the transaction includes one or more one-time purchases, this field must be equal to // the sum of the purchases. Set this field to 0 if the transaction does // not include a one-time purchase such as when you set up a billing // agreement for a recurring payment that is not immediately charged. // When the field is set to 0, purchase-specific fields are ignored. // // * `Currency Code` - You must set the currencyID attribute to one of the // 3-character currency codes for any of the supported PayPal // currencies. // * `Amount` BasicAmountType orderTotal1 = new BasicAmountType(CurrencyCodeType.USD, "2.00"); paymentDetails1.OrderTotal = orderTotal1; // How you want to obtain payment. When implementing parallel payments, // this field is required and must be set to `Order`. When implementing // digital goods, this field is required and must be set to `Sale`. If the // transaction does not include a one-time purchase, this field is // ignored. It is one of the following values: // // * `Sale` - This is a final sale for which you are requesting payment // (default). // * `Authorization` - This payment is a basic authorization subject to // settlement with PayPal Authorization and Capture. // * `Order` - This payment is an order authorization subject to // settlement with PayPal Authorization and Capture. // Note: // You cannot set this field to Sale in SetExpressCheckout request and // then change the value to Authorization or Order in the // DoExpressCheckoutPayment request. If you set the field to // Authorization or Order in SetExpressCheckout, you may set the field // to Sale. paymentDetails1.PaymentAction = PaymentActionCodeType.ORDER; // Unique identifier for the merchant. For parallel payments, this field // is required and must contain the Payer Id or the email address of the // merchant. SellerDetailsType sellerDetails1 = new SellerDetailsType(); sellerDetails1.PayPalAccountID = "*****@*****.**"; paymentDetails1.SellerDetails = sellerDetails1; // A unique identifier of the specific payment request, which is // required for parallel payments. paymentDetails1.PaymentRequestID = "PaymentRequest1"; // information about the second payment PaymentDetailsType paymentDetails2 = new PaymentDetailsType(); // Total cost of the transaction to the buyer. If shipping cost and tax // charges are known, include them in this value. If not, this value // should be the current sub-total of the order. // // If the transaction includes one or more one-time purchases, this field must be equal to // the sum of the purchases. Set this field to 0 if the transaction does // not include a one-time purchase such as when you set up a billing // agreement for a recurring payment that is not immediately charged. // When the field is set to 0, purchase-specific fields are ignored. // // * `Currency Code` - You must set the currencyID attribute to one of the // 3-character currency codes for any of the supported PayPal // currencies. // * `Amount` BasicAmountType orderTotal2 = new BasicAmountType(CurrencyCodeType.USD, "4.00"); paymentDetails2.OrderTotal = orderTotal2; // How you want to obtain payment. When implementing parallel payments, // this field is required and must be set to `Order`. When implementing // digital goods, this field is required and must be set to `Sale`. If the // transaction does not include a one-time purchase, this field is // ignored. It is one of the following values: // // * `Sale` - This is a final sale for which you are requesting payment // (default). // * `Authorization` - This payment is a basic authorization subject to // settlement with PayPal Authorization and Capture. // * `Order` - This payment is an order authorization subject to // settlement with PayPal Authorization and Capture. // `Note: // You cannot set this field to Sale in SetExpressCheckout request and // then change the value to Authorization or Order in the // DoExpressCheckoutPayment request. If you set the field to // Authorization or Order in SetExpressCheckout, you may set the field // to Sale.` paymentDetails2.PaymentAction = PaymentActionCodeType.ORDER; // Unique identifier for the merchant. For parallel payments, this field // is required and must contain the Payer Id or the email address of the // merchant. SellerDetailsType sellerDetails2 = new SellerDetailsType(); sellerDetails2.PayPalAccountID = "*****@*****.**"; paymentDetails2.SellerDetails = sellerDetails2; // A unique identifier of the specific payment request, which is // required for parallel payments. paymentDetails2.PaymentRequestID = "PaymentRequest2"; paymentDetailsList.Add(paymentDetails1); paymentDetailsList.Add(paymentDetails2); doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList; DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails); doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest; var config = new Dictionary <string, string> { { "mode", "sandbox" }, { "account1.apiUsername", "konstantin_merchant_api1.scandiaconsulting.com" }, { "account1.apiPassword", "1398157263" }, { "account1.apiSignature", "AFcWxV21C7fd0v3bYYYRCpSSRl31AlRjlcug7qV.VXWV14E1KtmQPsPL" } }; // Create the service wrapper object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config); // # API call // Invoke the DoExpressCheckoutPayment method in service wrapper object responseDoExpressCheckoutPaymentResponseType = service.DoExpressCheckoutPayment(doExpressCheckoutPayment); if (responseDoExpressCheckoutPaymentResponseType != null) { // Response envelope acknowledgement string acknowledgement = "DoExpressCheckoutPayment API Operation - "; acknowledgement += responseDoExpressCheckoutPaymentResponseType.Ack.ToString(); Console.WriteLine(acknowledgement + "\n"); // # Success values if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS")) { // Transaction identification number of the transaction that was // created. // This field is only returned after a successful transaction // for DoExpressCheckout has occurred. if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null) { IEnumerator <PaymentInfoType> paymentInfoIterator = responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator(); while (paymentInfoIterator.MoveNext()) { PaymentInfoType paymentInfo = paymentInfoIterator.Current; Console.WriteLine("Transaction ID : " + paymentInfo.TransactionID + "\n"); } } } // # Error Values else { List <ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors; foreach (ErrorType error in errorMessages) { Console.WriteLine("API Error Message : " + error.LongMessage + "\n"); } } } return(responseDoExpressCheckoutPaymentResponseType); } // # Exception log catch (System.Exception ex) { // Log the exception message Console.WriteLine("Error Message : " + ex.Message); } return(responseDoExpressCheckoutPaymentResponseType); }
public virtual async Task <VerifyPaymentResult> VerifyPayment(TblInvoices invoice) { var result = new VerifyPaymentResult(); var token = invoice.PaymentGatewayToken; var request = HttpContext.Current.Request; if (string.IsNullOrWhiteSpace(request.QueryString["Status"]) || string.IsNullOrWhiteSpace(request.QueryString["token"])) { result.ErrorMessage = _localizationService.GetResource("Plugin.PaymentMethod.PayPal.StatusOrTokenInvalid"); return(result); } if (!request.QueryString["Status"].Equals("OK")) { result.ErrorMessage = _localizationService.GetResource("Plugin.PaymentMethod.PayPal.StatusFieldIsNotOK"); return(result); } await Task.Run(() => { try { var service = new PayPalAPIInterfaceServiceService(GetPayPalConfig()); var getEcWrapper = new GetExpressCheckoutDetailsReq { GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token) }; var getEcResponse = service.GetExpressCheckoutDetails(getEcWrapper); var ecRequest = new DoExpressCheckoutPaymentRequestType(); var requestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); ecRequest.DoExpressCheckoutPaymentRequestDetails = requestDetails; requestDetails.PaymentDetails = getEcResponse.GetExpressCheckoutDetailsResponseDetails.PaymentDetails; requestDetails.Token = token; requestDetails.PayerID = getEcResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID; requestDetails.PaymentAction = PaymentActionCodeType.SALE; var wrapper = new DoExpressCheckoutPaymentReq { DoExpressCheckoutPaymentRequest = ecRequest }; var doEcResponse = service.DoExpressCheckoutPayment(wrapper); if (doEcResponse.Ack == AckCodeType.SUCCESS) { result.IsSuccess = true; result.TransactionId = doEcResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0].TransactionID; } else { foreach (var error in doEcResponse.Errors) { result.ErrorMessage += $"[{error.SeverityCode}] {error.ErrorCode} : {error.LongMessage} </br>"; } } } catch { result.ErrorMessage = _localizationService.GetResource("Plugin.PaymentMethod.PayPal.ServiceUnavailable"); } }); return(result); }
public ExpressCheckoutResult DoExpressCheckout() { HttpContext context = HttpContext.Current; TraceContext trace = context.Trace; string traceCategory = this.GetType().ToString(); ExpressCheckoutSession paypalSession = ExpressCheckoutSession.Current; if (paypalSession == null) { //EXIT WITH EXCEPTION ErrorType[] customErrorList = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "SESSION"; customError.ShortMessage = "Missing Token"; customError.LongMessage = "The PayPal session token was expired or unavailable. Please try again."; customErrorList[0] = customError; return(new ExpressCheckoutResult(0, string.Empty, customErrorList)); } trace.Write(traceCategory, "Detected PayPal Token:" + paypalSession.Token); trace.Write(traceCategory, "Token Expiration:" + paypalSession.TokenExpiration.ToLongDateString()); if (string.IsNullOrEmpty(paypalSession.PayerID)) { //EXIT WITH EXCEPTION ErrorType[] customErrorList = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "SESSION"; customError.ShortMessage = "Missing Payer ID"; customError.LongMessage = "The PayPal Payer ID is not present."; customErrorList[0] = customError; return(new ExpressCheckoutResult(0, string.Empty, customErrorList)); } trace.Write(traceCategory, "Detected PayPal Payer ID:" + paypalSession.PayerID); //GET THE CURRENCY FOR THE TRANSACTION string storeCurrencyCode = Token.Instance.Store.BaseCurrency.ISOCode; CurrencyCodeType baseCurrencyCode = PayPalProvider.GetPayPalCurrencyType(storeCurrencyCode); //CREATE THE EXPRESS CHECKOUT DoExpressCheckoutPaymentRequestType expressCheckoutRequest = new DoExpressCheckoutPaymentRequestType(); expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType(); expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.Token = paypalSession.Token; expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentAction = this.UseAuthCapture ? PaymentActionCodeType.Sale : PaymentActionCodeType.Authorization; expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentActionSpecified = true; expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PayerID = paypalSession.PayerID; expressCheckoutRequest.Version = "1.0"; //SET THE ORDER TOTAL AMOUNTS Basket basket = Token.Instance.User.Basket; trace.Write(traceCategory, "Set Order Totals"); LSDecimal curOrderTotal = basket.Items.TotalPrice(); LSDecimal curShippingTotal = basket.Items.TotalPrice(OrderItemType.Shipping) + GetShippingCouponTotal(basket.Items); LSDecimal curHandlingTotal = basket.Items.TotalPrice(OrderItemType.Handling); LSDecimal curTaxTotal = basket.Items.TotalPrice(OrderItemType.Tax); LSDecimal curItemTotal = curOrderTotal - (curShippingTotal + curHandlingTotal + curTaxTotal); //MAKE SURE OUR BREAKDOWN IS VALID if ((curShippingTotal < 0) || (curHandlingTotal < 0) || (curTaxTotal < 0) || (curItemTotal < 0)) { //THE BREAKDOWN IS INVALID, DO NOT INCLUDE IT IN THE REQUEST curShippingTotal = 0; curHandlingTotal = 0; curTaxTotal = 0; curItemTotal = curOrderTotal; } //SET THE PAYMENT DETAILS expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails = new PaymentDetailsType[1]; expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0] = new PaymentDetailsType(); PaymentDetailsType paymentDetails = expressCheckoutRequest.DoExpressCheckoutPaymentRequestDetails.PaymentDetails[0]; paymentDetails.OrderTotal = new BasicAmountType(); paymentDetails.OrderTotal.currencyID = baseCurrencyCode; paymentDetails.OrderTotal.Value = string.Format("{0:##,##0.00}", curOrderTotal); paymentDetails.ItemTotal = new BasicAmountType(); paymentDetails.ItemTotal.currencyID = baseCurrencyCode; paymentDetails.ItemTotal.Value = string.Format("{0:##,##0.00}", curItemTotal); paymentDetails.ShippingTotal = new BasicAmountType(); paymentDetails.ShippingTotal.currencyID = baseCurrencyCode; paymentDetails.ShippingTotal.Value = string.Format("{0:##,##0.00}", curShippingTotal); paymentDetails.HandlingTotal = new BasicAmountType(); paymentDetails.HandlingTotal.currencyID = baseCurrencyCode; paymentDetails.HandlingTotal.Value = string.Format("{0:##,##0.00}", curHandlingTotal); paymentDetails.TaxTotal = new BasicAmountType(); paymentDetails.TaxTotal.currencyID = baseCurrencyCode; paymentDetails.TaxTotal.Value = string.Format("{0:##,##0.00}", curTaxTotal); trace.Write(traceCategory, "Order Total: " + curOrderTotal); trace.Write(traceCategory, "Item Total: " + curItemTotal); trace.Write(traceCategory, "Shipping Total: " + curShippingTotal); trace.Write(traceCategory, "Handling Total: " + curHandlingTotal); trace.Write(traceCategory, "Tax Total: " + curTaxTotal); //SET THE BUTTON SOURCE trace.Write(traceCategory, "Set Button Source"); paymentDetails.ButtonSource = "ablecommerce-EC"; //SET THE NOTIFY URL string notifyUrl = GetStoreUrl() + "/ProcessPayPal.ashx"; trace.Write(traceCategory, "IPN Callback URL: " + notifyUrl); paymentDetails.NotifyURL = notifyUrl; //WE HAVE ALL NECESSARY INFORMATION TO DO EXPRESS CHECKOUT //COMMIT THE ORDER BEFORE SUBMITTING THE PAYPAL TRANSACTION //CREATE THE ABLECOMMERCE PAYMENT ITEM Payment checkoutPayment = new Payment(); checkoutPayment.PaymentMethodId = GetPayPalPaymentMethodId(false); checkoutPayment.Amount = curOrderTotal; checkoutPayment.CurrencyCode = baseCurrencyCode.ToString(); //AT THIS POINT, EXECUTE THE CHECKOUT TO SUBMIT THE ORDER CheckoutRequest checkoutRequest = new CheckoutRequest(checkoutPayment); CheckoutResponse checkoutResponse = basket.Checkout(checkoutRequest); int orderId = checkoutResponse.OrderId; //LOAD THE ORDER AND RE-OBTAIN THE PAYMENT RECORD TO AVOID DATA INCONSISTENCIES Order order = OrderDataSource.Load(orderId); if (order == null) { //EXIT WITH EXCEPTION ErrorType[] customErrorList = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "ORDER"; customError.ShortMessage = "Your order could not be completed at this time."; customError.LongMessage = "Your order could not be completed at this time and payment was not processed. " + string.Join(" ", checkoutResponse.WarningMessages.ToArray()); customErrorList[0] = customError; return(new ExpressCheckoutResult(0, string.Empty, customErrorList)); } int findPaymentId = checkoutPayment.PaymentId; foreach (Payment payment in order.Payments) { if (payment.PaymentId == findPaymentId) { checkoutPayment = payment; } } //SET THE DESCRIPTION paymentDetails.OrderDescription = "Order #" + order.OrderNumber.ToString(); paymentDetails.Custom = orderId.ToString(); //EXECUTE PAYPAL REQUEST trace.Write(traceCategory, "Do Request"); DoExpressCheckoutPaymentResponseType expressCheckoutResponse = (DoExpressCheckoutPaymentResponseType)SoapCall("DoExpressCheckoutPayment", expressCheckoutRequest); ErrorType[] responseErrors = null; PaymentStatus finalPaymentStatus = PaymentStatus.Unprocessed; bool isPendingeCheck = false; if (expressCheckoutResponse != null) { if (expressCheckoutResponse.Errors == null) { //CREATE THE PAYPAL TRANSACTION RECORD Transaction checkoutTransaction = new Transaction(); PaymentInfoType paymentInfo = expressCheckoutResponse.DoExpressCheckoutPaymentResponseDetails.PaymentInfo[0]; isPendingeCheck = (paymentInfo.PaymentStatus == PaymentStatusCodeType.Pending && paymentInfo.PendingReason == PendingStatusCodeType.echeck); PaymentStatusCodeType paymentStatus = paymentInfo.PaymentStatus; switch (paymentStatus) { case PaymentStatusCodeType.Completed: case PaymentStatusCodeType.Processed: case PaymentStatusCodeType.Pending: if (isPendingeCheck) { finalPaymentStatus = PaymentStatus.CapturePending; checkoutTransaction.ResponseCode = "PENDING"; checkoutTransaction.ResponseMessage = "echeck"; } else { finalPaymentStatus = (paymentStatus != PaymentStatusCodeType.Pending) ? PaymentStatus.Captured : PaymentStatus.Authorized; } checkoutTransaction.TransactionStatus = TransactionStatus.Successful; break; default: finalPaymentStatus = PaymentStatus.Unprocessed; checkoutTransaction.TransactionStatus = TransactionStatus.Failed; checkoutTransaction.ResponseCode = expressCheckoutResponse.Ack.ToString(); checkoutTransaction.ResponseMessage = paymentStatus.ToString().ToUpperInvariant(); break; } checkoutTransaction.TransactionType = this.UseAuthCapture ? TransactionType.Capture : TransactionType.Authorize; checkoutTransaction.Amount = AlwaysConvert.ToDecimal(paymentInfo.GrossAmount.Value, (Decimal)curOrderTotal); checkoutTransaction.AuthorizationCode = paymentInfo.TransactionID; checkoutTransaction.AVSResultCode = "U"; checkoutTransaction.ProviderTransactionId = paymentInfo.TransactionID; checkoutTransaction.Referrer = context.Request.ServerVariables["HTTP_REFERER"]; checkoutTransaction.PaymentGatewayId = this.PaymentGatewayId; checkoutTransaction.RemoteIP = context.Request.ServerVariables["REMOTE_ADDR"]; checkoutPayment.Transactions.Add(checkoutTransaction); //FIND THE WAITING FOR IPN TRANSACTION AND REMOVE int i = checkoutPayment.Transactions.Count - 1; while (i >= 0) { if (string.IsNullOrEmpty(checkoutPayment.Transactions[i].AuthorizationCode)) { checkoutPayment.Transactions.DeleteAt(i); } i--; } } else { //SOME SORT OF ERROR ATTEMPTING CHECKOUT responseErrors = expressCheckoutResponse.Errors; } } else { //NO RESPONSE, GENERATE CUSTOM ERROR responseErrors = new ErrorType[1]; ErrorType customError = new ErrorType(); customError.ErrorCode = "NORESP"; customError.ShortMessage = "No Response From Server"; customError.LongMessage = "The PayPal service is unavailable at this time."; responseErrors[0] = customError; } trace.Write(traceCategory, "Do Request Done"); //ERRORS IN RESPONSE? if ((responseErrors != null) && (responseErrors.Length > 0)) { //CREATE THE PAYPAL TRANSACTION RECORD FOR ERROR Transaction checkoutTransaction = new Transaction(); finalPaymentStatus = PaymentStatus.Unprocessed; checkoutTransaction.TransactionStatus = TransactionStatus.Failed; checkoutTransaction.Amount = curOrderTotal; checkoutTransaction.AuthorizationCode = string.Empty; checkoutTransaction.Referrer = context.Request.ServerVariables["HTTP_REFERER"]; checkoutTransaction.PaymentGatewayId = this.PaymentGatewayId; checkoutTransaction.RemoteIP = context.Request.ServerVariables["REMOTE_ADDR"]; checkoutTransaction.ResponseCode = responseErrors[0].ShortMessage; checkoutTransaction.ResponseMessage = responseErrors[0].LongMessage; checkoutPayment.Transactions.Add(checkoutTransaction); } //MAKE SURE PAYMENT STATUS IS CORRECT checkoutPayment.ReferenceNumber = paypalSession.Payer; checkoutPayment.PaymentStatus = finalPaymentStatus; if (isPendingeCheck) { checkoutPayment.PaymentStatusReason = "echeck"; } //RECALCULATE THE ORDER STATUS (BUG 6384) AND TRIGGER PAYMENT EVENTS (BUG 8650) order.Save(true, true); //CLEAR THE TOKENS SET IN SESSION paypalSession.Delete(); return(new ExpressCheckoutResult(orderId, string.Empty, responseErrors)); }