GetExpressCheckoutDetails() public method

public GetExpressCheckoutDetails ( GetExpressCheckoutDetailsReq getExpressCheckoutDetailsReq ) : GetExpressCheckoutDetailsResponseType
getExpressCheckoutDetailsReq PayPal.PayPalAPIInterfaceService.Model.GetExpressCheckoutDetailsReq
return PayPal.PayPalAPIInterfaceService.Model.GetExpressCheckoutDetailsResponseType
        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);
        }
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();
            // (Required) A timestamped token, the value of which was returned by SetExpressCheckout response.
            // Character length and limitations: 20 single-byte characters
            request.Token = token.Value;

            // Invoke the API
            GetExpressCheckoutDetailsReq wrapper = new GetExpressCheckoutDetailsReq();
            wrapper.GetExpressCheckoutDetailsRequest = request;

            // 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);

            // # API call
            // Invoke the GetExpressCheckoutDetails method in service wrapper object
            GetExpressCheckoutDetailsResponseType ecResponse = service.GetExpressCheckoutDetails(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, ecResponse);
        }
    // # GetExpressCheckout API Operation
    // The GetExpressCheckoutDetails API operation obtains information about an Express Checkout transaction
    public GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetailsAPIOperation()
    {
        // Create the GetExpressCheckoutDetailsResponseType object
        GetExpressCheckoutDetailsResponseType responseGetExpressCheckoutDetailsResponseType = new GetExpressCheckoutDetailsResponseType();

        try
        {
            // Create the GetExpressCheckoutDetailsReq object
            GetExpressCheckoutDetailsReq getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq();

            // A timestamped token, the value of which was returned by `SetExpressCheckout` response
            GetExpressCheckoutDetailsRequestType getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType("EC-11U13522TP7143059");
            getExpressCheckoutDetails.GetExpressCheckoutDetailsRequest = getExpressCheckoutDetailsRequest;

            // Create the service wrapper object to make the API call
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

            // # API call
            // Invoke the GetExpressCheckoutDetails method in service wrapper object
            responseGetExpressCheckoutDetailsResponseType = service.GetExpressCheckoutDetails(getExpressCheckoutDetails);

            if (responseGetExpressCheckoutDetailsResponseType != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "GetExpressCheckoutDetails API Operation - ";
                acknowledgement += responseGetExpressCheckoutDetailsResponseType.Ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responseGetExpressCheckoutDetailsResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Unique PayPal Customer Account identification number. This
                    // value will be null unless you authorize the payment by
                    // redirecting to PayPal after `SetExpressCheckout` call.
                    logger.Info("Payer ID : " + responseGetExpressCheckoutDetailsResponseType.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID + "\n");
                    Console.WriteLine("Payer ID : " + responseGetExpressCheckoutDetailsResponseType.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID + "\n");

                }
                // # Error Values
                else
                {
                    List<ErrorType> errorMessages = responseGetExpressCheckoutDetailsResponseType.Errors;
                    foreach (ErrorType error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.LongMessage);
                        Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return responseGetExpressCheckoutDetailsResponseType;
    }
        public IPaymentResult ComplitePayment(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);
        }
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object
            GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();
            request.Token = token.Value;

            // Invoke the API
            GetExpressCheckoutDetailsReq wrapper = new GetExpressCheckoutDetailsReq();
            wrapper.GetExpressCheckoutDetailsRequest = request;
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
            GetExpressCheckoutDetailsResponseType ecResponse = service.GetExpressCheckoutDetails(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, ecResponse);
        }
        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);
        }
 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);
 }
		// # GetExpressCheckout API Operation
		// The GetExpressCheckoutDetails API operation obtains information about an Express Checkout transaction
		public GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetailsAPIOperation()
		{
			// Create the GetExpressCheckoutDetailsResponseType object
			GetExpressCheckoutDetailsResponseType responseGetExpressCheckoutDetailsResponseType =
				new GetExpressCheckoutDetailsResponseType();

			try
			{
				// Create the GetExpressCheckoutDetailsReq object
				GetExpressCheckoutDetailsReq getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq();

				// A timestamped token, the value of which was returned by `SetExpressCheckout` response
				GetExpressCheckoutDetailsRequestType getExpressCheckoutDetailsRequest =
					new GetExpressCheckoutDetailsRequestType("EC-3PG29673CT337061M");
				getExpressCheckoutDetails.GetExpressCheckoutDetailsRequest = getExpressCheckoutDetailsRequest;

				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 GetExpressCheckoutDetails method in service wrapper object
				responseGetExpressCheckoutDetailsResponseType = service.GetExpressCheckoutDetails(getExpressCheckoutDetails);

				if (responseGetExpressCheckoutDetailsResponseType != null)
				{
					// Response envelope acknowledgement
					string acknowledgement = "GetExpressCheckoutDetails API Operation - ";
					acknowledgement += responseGetExpressCheckoutDetailsResponseType.Ack.ToString();
					Console.WriteLine(acknowledgement + "\n");

					// # Success values
					if (responseGetExpressCheckoutDetailsResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
					{
						// Unique PayPal Customer Account identification number. This
						// value will be null unless you authorize the payment by
						// redirecting to PayPal after `SetExpressCheckout` call.
						Console.WriteLine("Payer ID : " +
						                  responseGetExpressCheckoutDetailsResponseType.GetExpressCheckoutDetailsResponseDetails.PayerInfo
						                                                               .PayerID + "\n");

					}
						// # Error Values
					else
					{
						List<ErrorType> errorMessages = responseGetExpressCheckoutDetailsResponseType.Errors;
						foreach (ErrorType error in errorMessages)
						{
							Console.WriteLine("API Error Message : " + error.LongMessage + "\n");
						}
					}
				}
			}
				// # Exception log    
			catch (System.Exception ex)
			{
				// Log the exception message       
				Console.WriteLine("Error Message : " + ex.Message);
			}
			return responseGetExpressCheckoutDetailsResponseType;
		}
示例#9
0
        public string ProcessPayment(string token, string PayerID)
        {
            string result = "success";

            GetExpressCheckoutDetailsRequestType request = new GetExpressCheckoutDetailsRequestType();
            request.Version = "104.0";
            request.Token = token;
            GetExpressCheckoutDetailsReq wrapper = new GetExpressCheckoutDetailsReq();
            wrapper.GetExpressCheckoutDetailsRequest = request;
            Dictionary<string, string> sdkConfig = new Dictionary<string, string>();

            sdkConfig.Add("mode", appMode);
            sdkConfig.Add("account1.apiUsername", username);
            sdkConfig.Add("account1.apiPassword", password);
            sdkConfig.Add("account1.apiSignature", signature);
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(sdkConfig);
            GetExpressCheckoutDetailsResponseType ecResponse = service.GetExpressCheckoutDetails(wrapper);

            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)), this.TotalPrice);
            paymentDetail.OrderDescription = PaypalComment;
            List<PaymentDetailsType> paymentDetails = new List<PaymentDetailsType>();
            paymentDetails.Add(paymentDetail);

            DoExpressCheckoutPaymentRequestType request2 = new DoExpressCheckoutPaymentRequestType();
            request.Version = "104.0";
            DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
            requestDetails.PaymentDetails = paymentDetails;
            requestDetails.Token = token;
            requestDetails.PayerID = PayerID;
            request2.DoExpressCheckoutPaymentRequestDetails = requestDetails;

            DoExpressCheckoutPaymentReq wrapper2 = new DoExpressCheckoutPaymentReq();
            wrapper2.DoExpressCheckoutPaymentRequest = request2;
            Dictionary<string, string> sdkConfig2 = new Dictionary<string, string>();


            sdkConfig2.Add("mode", appMode);
            sdkConfig2.Add("account1.apiUsername", username);
            sdkConfig2.Add("account1.apiPassword", password);
            sdkConfig2.Add("account1.apiSignature", signature);
            PayPalAPIInterfaceServiceService service2 = new PayPalAPIInterfaceServiceService(sdkConfig);
            DoExpressCheckoutPaymentResponseType doECResponse = service2.DoExpressCheckoutPayment(wrapper2);

            this.PaymentConfirmationID = doECResponse.CorrelationID;

            return result;
        }
        public ActionResult PaypalExpressSuccess(string token, string payerID)
        {

            var model = (CheckoutModel)TempData["checkout_" + token] ?? PrepareCheckoutModel(new CheckoutModel());
            model.Payments = model.Payments ?? GetPayments().ToArray();

            //Resave LastOrderId
            TempData["LastOrderId"] = TempData["LastOrderId"];

            var payment = _paymentClient.GetPaymentMethod(model.PaymentMethod ?? "Paypal");
            var configMap = payment.CreateSettings();

            var service = new PayPalAPIInterfaceServiceService(configMap);

            var getEcWrapper = new GetExpressCheckoutDetailsReq
            {
                GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token)
            };

            GetExpressCheckoutDetailsResponseType getEcResponse = null;

            try
            {
                getEcResponse = service.GetExpressCheckoutDetails(getEcWrapper);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", @"Paypal failure".Localize());
                ModelState.AddModelError("", ex.Message);
            }

            if (getEcResponse != null)
            {
                if (getEcResponse.Ack.Equals(AckCodeType.FAILURE) ||
                    (getEcResponse.Errors != null && getEcResponse.Errors.Count > 0))
                {
                    ModelState.AddModelError("", @"Paypal failure".Localize());
                    foreach (var error in getEcResponse.Errors)
                    {
                        ModelState.AddModelError("", error.LongMessage);
                    }
                }
                else
                {
                    var details = getEcResponse.GetExpressCheckoutDetailsResponseDetails;

                    if (details.CheckoutStatus.Equals("PaymentActionCompleted", StringComparison.OrdinalIgnoreCase))
                    {
                        UserHelper.CustomerSession.LastOrderId = TempData["LastOrderId"] as string;
                        return RedirectToAction("ProcessCheckout", "Checkout", new { id = UserHelper.CustomerSession.LastOrderId });
                    }

                    model.PaymentMethod = payment.Name;
                    model.ShippingMethod = details.UserSelectedOptions.ShippingOptionName;

                    var paymentDetails = details.PaymentDetails[0];

                    model.BillingAddress.Address = ConvertToPaypalAddress(paymentDetails.ShipToAddress, "Billing");
                    model.BillingAddress.Address.Email = details.PayerInfo.Payer;
                    model.ShippingAddress.Address = ConvertToPaypalAddress(paymentDetails.ShipToAddress, "Shipping");
                    model.ShippingAddress.Address.Email = details.PayerInfo.Payer;

                    Ch.Reset();
                    UpdateCart(model, true);
                    Ch.RunWorkflow("ShoppingCartPrepareWorkflow");

                    var cartPayment =
                        Ch.OrderForm.Payments.FirstOrDefault(
                            x => x.PaymentMethodName.Equals(payment.Name, StringComparison.OrdinalIgnoreCase));

                    if (cartPayment == null)
                    {
                        ModelState.AddModelError("", @"Shopping cart failure!".Localize());
                    }
                    else if (ModelState.IsValid)
                    {
                        cartPayment.ContractId = payerID;
                        cartPayment.AuthorizationCode = token;
                        cartPayment.Amount = Ch.Cart.Total;

                        if (decimal.Parse(paymentDetails.OrderTotal.value) != Ch.Cart.Total)
                        {
                            ModelState.AddModelError("", @"Paypal payment total does not match cart total!".Localize());
                        }

                        Ch.SaveChanges();

                        if (DoCheckout())
                        { 
                            //This call was made from paypal API, we need so save last order id, as it is not saved in our cookie
                            TempData["LastOrderId"] = UserHelper.CustomerSession.LastOrderId;
                            return null;
                        }
                    }

                }
            }

            return View("Index", model);

        }
        /// <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 override PostProcessPaymentResult PostProcessPayment(PostProcessPaymentEvaluationContext context)
		{
			var retVal = new PostProcessPaymentResult();

			if (context == null && context.Payment == null)
				throw new ArgumentNullException("paymentEvaluationContext");

			if (context.Order == null)
				throw new NullReferenceException("no order with this id");

			retVal.OrderId = context.Order.Id;

			if (!(context.Store != null && !string.IsNullOrEmpty(context.Store.Url)))
				throw new NullReferenceException("no store with this id");

			var config = GetConfigMap(context.Store);

			var service = new PayPalAPIInterfaceServiceService(config);

		    var getExpressCheckoutDetailsRequest = GetGetExpressCheckoutDetailsRequest(context.OuterId);
			try
			{
				var response = service.GetExpressCheckoutDetails(getExpressCheckoutDetailsRequest);

				CheckResponse(response);

				var status = response.GetExpressCheckoutDetailsResponseDetails.CheckoutStatus;

				if (!status.Equals("PaymentActionCompleted"))
				{
					var doExpressCheckoutPaymentRequest = GetDoExpressCheckoutPaymentRequest(response, context.OuterId);
					var doResponse = service.DoExpressCheckoutPayment(doExpressCheckoutPaymentRequest);

					CheckResponse(doResponse);

					response = service.GetExpressCheckoutDetails(getExpressCheckoutDetailsRequest);
					status = response.GetExpressCheckoutDetailsResponseDetails.CheckoutStatus;
				}
				if (status.Equals("PaymentActionCompleted"))
				{
					retVal.IsSuccess = true;
					retVal.NewPaymentStatus = PaymentStatus.Paid;
				}
			}
			catch (System.Exception ex)
			{
				retVal.Error = ex.Message;
				retVal.NewPaymentStatus = PaymentStatus.Pending;
			}

			return retVal;
		}
        // # GetExpressCheckout API Operation
        // The GetExpressCheckoutDetails API operation obtains information about an Express Checkout transaction
        public GetExpressCheckoutDetailsResponseType GetExpressCheckoutDetails(string token)
        {
            // Create the GetExpressCheckoutDetailsResponseType object
            GetExpressCheckoutDetailsResponseType responseGetExpressCheckoutDetailsResponseType = new GetExpressCheckoutDetailsResponseType();

            try
            {
                // Create the GetExpressCheckoutDetailsReq object
                GetExpressCheckoutDetailsReq getExpressCheckoutDetails = new GetExpressCheckoutDetailsReq();

                // A timestamped token, the value of which was returned by `SetExpressCheckout` response
                GetExpressCheckoutDetailsRequestType getExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token);
                getExpressCheckoutDetails.GetExpressCheckoutDetailsRequest = getExpressCheckoutDetailsRequest;

                // Create the service wrapper object to make the API call
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();

                // # API call
                // Invoke the GetExpressCheckoutDetails method in service wrapper object
                responseGetExpressCheckoutDetailsResponseType = service.GetExpressCheckoutDetails(getExpressCheckoutDetails);
            }
            // # Exception log
            catch (System.Exception ex)
            {
                // Log the exception message
                levent.Level = LogLevel.Error;
                levent.Message = "Logon failed for PaypalExpressCheckout: " + ex.Message;
                log.Log(levent);
            }
            return responseGetExpressCheckoutDetailsResponseType;
        }
		public override PostProcessPaymentResult PostProcessPayment(PostProcessPaymentEvaluationContext context)
		{
			if (context.Order == null)
				throw new ArgumentNullException("context.Order is null");
			if (context.Payment == null)
				throw new ArgumentNullException("context.Payment is null");
			if (context.Store == null)
				throw new ArgumentNullException("context.Store is null");
			if (string.IsNullOrEmpty(context.Store.Url))
				throw new NullReferenceException("url of store not set");

			var retVal = new PostProcessPaymentResult();

			retVal.OrderId = context.Order.Id;

			var config = GetConfigMap();

			var service = new PayPalAPIInterfaceServiceService(config);

		    var getExpressCheckoutDetailsRequest = GetGetExpressCheckoutDetailsRequest(context.OuterId);
			try
			{
				var response = service.GetExpressCheckoutDetails(getExpressCheckoutDetailsRequest);

				CheckResponse(response);

				var status = response.GetExpressCheckoutDetailsResponseDetails.CheckoutStatus;

				if (!status.Equals("PaymentActionCompleted"))
				{
					var doExpressCheckoutPaymentRequest = GetDoExpressCheckoutPaymentRequest(response, context.OuterId);
					var doResponse = service.DoExpressCheckoutPayment(doExpressCheckoutPaymentRequest);

					CheckResponse(doResponse);

					response = service.GetExpressCheckoutDetails(getExpressCheckoutDetailsRequest);
					status = response.GetExpressCheckoutDetailsResponseDetails.CheckoutStatus;
				}
				if (status.Equals("PaymentActionCompleted"))
				{
					retVal.IsSuccess = true;
					retVal.OuterId = response.GetExpressCheckoutDetailsResponseDetails.PaymentDetails[0].TransactionId;
					if(PaypalPaymentActionType == PaymentActionCodeType.AUTHORIZATION)
					{
						retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Authorized;
						context.Payment.OuterId = retVal.OuterId;
						context.Payment.AuthorizedDate = DateTime.UtcNow;
					}
					else if (PaypalPaymentActionType == PaymentActionCodeType.SALE)
					{
						retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Paid;
						context.Payment.OuterId = retVal.OuterId;
						context.Payment.IsApproved = true;
						context.Payment.CapturedDate = DateTime.UtcNow;
					}
				}
				else
				{
					retVal.ErrorMessage = "Payment process not successfully ends";
				}
			}
			catch (System.Exception ex)
			{
				retVal.ErrorMessage = ex.Message;
			}

			return retVal;
		}
示例#15
0
        /// <summary>
        /// Paypal IPN callback
        /// </summary>
        /// <param name="token"></param>
        /// <param name="payerId"></param>
        /// <param name="cancel"></param>
        /// <returns></returns>
        public ActionResult PaypalExpressSuccess(string token, string payerId, bool? cancel)
        {
            var model = PrepareCheckoutModel(new CheckoutModel());
            Payment payment = null;

            var order = _orderClient.GetOrderByAuthCode(token);

            if (order == null)
            {
                ModelState.AddModelError("", "Order cannot be found for current payment!".Localize());
            }
            else
            {
                payment = order.OrderForms.SelectMany(f => f.Payments).First(p => p.AuthorizationCode == token);

                //If payment not cancelled proceed
                if (!cancel.HasValue || !cancel.Value)
                {

                    var paymentMethod = _paymentClient.GetPaymentMethod(payment.PaymentMethodName ?? "Paypal");

                    var configMap = paymentMethod.CreateSettings();

                    var service = new PayPalAPIInterfaceServiceService(configMap);

                    var getEcWrapper = new GetExpressCheckoutDetailsReq
                    {
                        GetExpressCheckoutDetailsRequest = new GetExpressCheckoutDetailsRequestType(token)
                    };

                    GetExpressCheckoutDetailsResponseType getEcResponse = null;

                    try
                    {
                        getEcResponse = service.GetExpressCheckoutDetails(getEcWrapper);
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("", @"Paypal failure".Localize());
                        ModelState.AddModelError("", ex.Message);
                    }

                    if (getEcResponse != null)
                    {
                        if (getEcResponse.Ack.Equals(AckCodeType.FAILURE) ||
                            (getEcResponse.Errors != null && getEcResponse.Errors.Count > 0))
                        {
                            ModelState.AddModelError("", @"Paypal failure".Localize());
                            foreach (var error in getEcResponse.Errors)
                            {
                                ModelState.AddModelError("", error.LongMessage);
                            }
                        }
                        else
                        {
                            var details = getEcResponse.GetExpressCheckoutDetailsResponseDetails;

                            if (details.CheckoutStatus.Equals("PaymentActionCompleted",
                                StringComparison.OrdinalIgnoreCase))
                            {
                                return RedirectToAction("ProcessCheckout", "Checkout", new {id = order.OrderGroupId});
                            }

                            model.PaymentMethod = paymentMethod.Name;
                            model.ShippingMethod = details.UserSelectedOptions.ShippingOptionName;

                            if (!string.IsNullOrEmpty(details.UserSelectedOptions.ShippingOptionName))
                            {
                                foreach (var lineItem in order.OrderForms.SelectMany(f => f.LineItems))
                                {
                                    var shippingMethod =
                                        Ch.GetShippingMethods(new List<string> {model.ShippingMethod}).First();
                                    lineItem.ShippingMethodName = shippingMethod.DisplayName;
                                    lineItem.ShippingMethodId = shippingMethod.Id;
                                }
                            }

                            var paymentDetails = details.PaymentDetails[0];

                            model.BillingAddress.Address = ConvertFromPaypalAddress(paymentDetails.ShipToAddress,
                                "Billing");
                            model.BillingAddress.Address.Email = details.PayerInfo.Payer;
                            model.ShippingAddress.Address = ConvertFromPaypalAddress(paymentDetails.ShipToAddress,
                                "Shipping");
                            model.ShippingAddress.Address.Email = details.PayerInfo.Payer;

                            #region Process billing address

                            var billingAddress = OrderClient.FindAddressByName(order, "Billing");
                            if (billingAddress == null)
                            {
                                billingAddress = new OrderAddress();
                                order.OrderAddresses.Add(billingAddress);

                                var orderAddressId = billingAddress.OrderAddressId;
                                billingAddress.InjectFrom(
                                    new IgnorePropertiesInjection("OrderGroupId", "OrderGroup", "OrderAddressId",
                                        "Created"), model.BillingAddress.Address);
                                billingAddress.Name = "Billing";
                                billingAddress.OrderAddressId = orderAddressId;
                                order.AddressId = orderAddressId;
                                order.OrderForms[0].BillingAddressId = orderAddressId;
                            }

                            #endregion

                            #region Process shipping address

                            var shippingAddress = OrderClient.FindAddressByName(order, "Shipping");
                            if (shippingAddress == null)
                            {
                                shippingAddress = new OrderAddress();
                                order.OrderAddresses.Add(shippingAddress);
                            }

                            shippingAddress.InjectFrom(
                                new IgnorePropertiesInjection("OrderGroupId", "OrderGroup", "OrderAddressId", "Created"),
                                model.ShippingAddress.Address);
                            shippingAddress.Name = "Shipping";
                            shippingAddress.OrderAddressId = shippingAddress.OrderAddressId;

                            //Update shipping address id
                            foreach (var shipment in order.OrderForms.SelectMany(f => f.Shipments))
                            {
                                shipment.ShippingAddressId = shippingAddress.OrderAddressId;
                            }
                            foreach (var lineItem in order.OrderForms.SelectMany(f => f.LineItems))
                            {
                                lineItem.ShippingAddressId = shippingAddress.OrderAddressId;
                            }

                            #endregion

                            //Recalcualte totals (User could have changed shipping method in paypal).
                            Ch.RunWorkflow("ShoppingCartPrepareWorkflow", order);


                            if (ModelState.IsValid)
                            {
                                payment.ContractId = payerId;
                                payment.AuthorizationCode = token;
                                payment.Amount = order.Total;

                                //Normally this message should be shown to user when. This happens because address changes and Tax is recalculated
                                if (decimal.Parse(paymentDetails.OrderTotal.value, CultureInfo.InvariantCulture) !=
                                    order.Total)
                                {
                                    ModelState.AddModelError("",
                                        "Paypal payment total does not match order total! Check the totals and try to pay again."
                                            .Localize());
                                }
                                else
                                {
                                    try
                                    {
                                        Ch.RunWorkflow("ShoppingCartCheckoutWorkflow", order);
                                        Ch.OrderRepository.UnitOfWork.Commit();
                                        return RedirectToAction("ProcessCheckout", "Checkout",
                                            new {id = order.OrderGroupId});
                                    }
                                    catch (Exception ex)
                                    {
                                        ModelState.AddModelError("", ex.Message);
                                    }
                                }

                            }

                        }
                    }
                }
            }

            if (order != null)
            {
                //Cancel old order
                order.Status = OrderStatus.Cancelled.ToString();
                payment.Status = PaymentStatus.Canceled.ToString();

                //Restore cart if order fails
                Ch.ToCart(order);

                //Add paypal payment to make it selected in UI
                var paypalPayment = new OtherPayment
                {
                    PaymentMethodId = payment.PaymentMethodId,
                    PaymentMethodName = payment.PaymentMethodName,
                    Amount = payment.Amount
                };
                Ch.OrderForm.Payments.Add(paypalPayment);
                Ch.SaveChanges();
            }

            return View("Index", model);

        }
        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);
        }