Esempio n. 1
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object

            DoCaptureRequestType request =
                new DoCaptureRequestType();

            request.AuthorizationID = authorizationId.Value;
            CurrencyCodeType currency = (CurrencyCodeType)
                Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
            request.Amount = new BasicAmountType(currency, amount.Value);
            if (completeType.SelectedIndex != 0)
            {
                request.CompleteType = (CompleteCodeType)
                    Enum.Parse(typeof(CompleteCodeType), completeType.SelectedValue);
            }
            if (note.Value != "")
            {
                request.Note = note.Value;
            }
            if (invoiceId.Value != "")
            {
                request.InvoiceID = invoiceId.Value;
            }
            if (softDescriptor.Value != "")
            {
                request.Descriptor = softDescriptor.Value;
            }

            // Invoke the API
            DoCaptureReq wrapper = new DoCaptureReq();
            wrapper.DoCaptureRequest = request;
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService();
            DoCaptureResponseType doCaptureResponse =
                    service.DoCapture(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, doCaptureResponse);
        }
        /// <summary>
        /// Captures payment
        /// </summary>
        /// <param name="capturePaymentRequest">Capture payment request</param>
        /// <returns>Capture payment result</returns>
        public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
        {
            var result = new CapturePaymentResult();

            string authorizationId = capturePaymentRequest.Order.AuthorizationTransactionId;
            var req = new DoCaptureReq();
            req.DoCaptureRequest = new DoCaptureRequestType();
            req.DoCaptureRequest.Version = GetApiVersion();
            req.DoCaptureRequest.AuthorizationID = authorizationId;
            req.DoCaptureRequest.Amount = new BasicAmountType();
            req.DoCaptureRequest.Amount.value = Math.Round(capturePaymentRequest.Order.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            req.DoCaptureRequest.Amount.currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));
            req.DoCaptureRequest.CompleteType = CompleteCodeType.COMPLETE;

            var service = GetService();
            DoCaptureResponseType response = service.DoCapture(req);

            string error;
            bool success = PaypalHelper.CheckSuccess(response, out error);
            if (success)
            {
                result.NewPaymentStatus = PaymentStatus.Paid;
                result.CaptureTransactionId = response.DoCaptureResponseDetails.PaymentInfo.TransactionID;
                result.CaptureTransactionResult = response.Ack.ToString();
            }
            else
            {
                result.AddError(error);
            }
            return result;
        }
        public ActionResult CaptureOrder(string authorizationId)
        {
            var service = new PayPalAPIInterfaceServiceService();

            var request = new GetTransactionDetailsReq
            {
                GetTransactionDetailsRequest = new GetTransactionDetailsRequestType
                {
                    TransactionID = authorizationId
                }
            };

            var transactionDetailsResponse = service.GetTransactionDetails(request);

            if (transactionDetailsResponse.Ack == AckCodeType.SUCCESS)
            {
                //if(transactionDetailsResponse.PaymentTransactionDetails.PaymentInfo.PaymentStatus == PaymentStatusCodeType.)

                var captureRequest = new DoCaptureReq
                {
                    DoCaptureRequest = new DoCaptureRequestType
                    {
                        AuthorizationID = authorizationId,
                        Amount = transactionDetailsResponse.PaymentTransactionDetails.PaymentInfo.GrossAmount
                    }
                };

                var captureResponse = service.DoCapture(captureRequest);

                if (captureResponse.Ack == AckCodeType.SUCCESS)
                {
                    return RedirectToAction("OrderSuccessful", new { transactionId = captureResponse.DoCaptureResponseDetails.PaymentInfo.TransactionID });
                }
                else
                {
                    foreach (var error in captureResponse.Errors)
                    {
                        ModelState.AddModelError("__FORM", error.LongMessage);
                    }
                }
            }
            else
            {
                foreach (var error in transactionDetailsResponse.Errors)
                {
                    ModelState.AddModelError("__FORM", error.LongMessage);
                }
            }

            return View("Error");
        }
        /// <summary>
        /// 
        /// </summary>
        ///<param name="doCaptureReq"></param>
        ///<param name="credential">An explicit ICredential object that you want to authenticate this call against</param> 
        public DoCaptureResponseType DoCapture(DoCaptureReq doCaptureReq, ICredential credential)
        {
            setStandardParams(doCaptureReq.DoCaptureRequest);
            DefaultSOAPAPICallHandler defaultHandler = new DefaultSOAPAPICallHandler(this.config, doCaptureReq.ToXMLString(null, "DoCaptureReq"), null, null);
            IAPICallPreHandler apiCallPreHandler = new MerchantAPICallPreHandler(this.config, defaultHandler, credential);
            ((MerchantAPICallPreHandler) apiCallPreHandler).SDKName = SDKName;
            ((MerchantAPICallPreHandler) apiCallPreHandler).SDKVersion = SDKVersion;
            ((MerchantAPICallPreHandler) apiCallPreHandler).PortName = "PayPalAPIAA";

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(Call(apiCallPreHandler));
            return new DoCaptureResponseType(
                xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='DoCaptureResponse']")
            );
        }
 /// <summary> 
 /// 
 /// </summary>
 ///<param name="doCaptureReq"></param>
 public DoCaptureResponseType DoCapture(DoCaptureReq doCaptureReq)
 {
     return DoCapture(doCaptureReq,(string) null);
 }
 /**
   *AUTO_GENERATED
  	  */
 public DoCaptureResponseType DoCapture(DoCaptureReq doCaptureReq, string apiUserName)
 {
     IAPICallPreHandler apiCallPreHandler = null;
      		string portName = "PayPalAPIAA";
     setStandardParams(doCaptureReq.DoCaptureRequest);
     DefaultSOAPAPICallHandler defaultHandler = new DefaultSOAPAPICallHandler(doCaptureReq.ToXMLString(null, "DoCaptureReq"), null, null);
     apiCallPreHandler = new MerchantAPICallPreHandler(defaultHandler, apiUserName, getAccessToken(), getAccessTokenSecret());
     ((MerchantAPICallPreHandler) apiCallPreHandler).SDKName = SDKName;
     ((MerchantAPICallPreHandler) apiCallPreHandler).SDKVersion = SDKVersion;
     ((MerchantAPICallPreHandler) apiCallPreHandler).PortName = portName;
     string response = Call(apiCallPreHandler);
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.LoadXml(response);
     XmlNode xmlNode = xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='DoCaptureResponse']");
     return new DoCaptureResponseType(xmlNode);
 }
Esempio n. 7
0
		public IPaymentResult CapturePayment(IInvoice invoice, IPayment payment, decimal amount, bool isPartialPayment)
		{
			var service = GetPayPalService();
			var authorizationId = payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.AuthorizationId);
			var currency = PayPalCurrency(invoice.CurrencyCode());
			var currencyDecimals = CurrencyDecimals(currency);
			
			// do express checkout
			var doCaptureRequest = new DoCaptureRequestType() 
				{
					AuthorizationID = authorizationId,
					Amount = new BasicAmountType(currency, PriceToString(amount, currencyDecimals)),
					CompleteType = (isPartialPayment ? CompleteCodeType.NOTCOMPLETE : CompleteCodeType.COMPLETE)
				};
			var doCaptureReq = new DoCaptureReq() { DoCaptureRequest = doCaptureRequest };

			//if (payment.ExtendedData.GetValue(Constants.ExtendedDataKeys.PaymentCaptured) != "true") {
				DoCaptureResponseType doCaptureResponse;
				try {
					doCaptureResponse = service.DoCapture(doCaptureReq);
					if (doCaptureResponse.Ack != AckCodeType.SUCCESS && doCaptureResponse.Ack != AckCodeType.SUCCESSWITHWARNING) {
						return new PaymentResult(Attempt<IPayment>.Fail(payment, CreateErrorResult(doCaptureResponse.Errors)), invoice, false);
					}
				} catch (Exception ex) {
					return new PaymentResult(Attempt<IPayment>.Fail(payment, ex), invoice, false);
				}
			
				payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.TransactionId, doCaptureResponse.DoCaptureResponseDetails.PaymentInfo.TransactionID);
				payment.ExtendedData.SetValue(Constants.ExtendedDataKeys.PaymentCaptured, "true");	
			//}
			
			payment.Authorized = true;
			payment.Collected = true;
			return new PaymentResult(Attempt<IPayment>.Succeed(payment), invoice, true);
			
		}
        public ITransactionCaptureResult Capture(ITransactionCaptureRequest request)
        {
            //to capture a transaction, we'll need authorization id previously obtained from paypal
            var authorizationId = request.GetParameterAs<string>(PaymentParameterNames.AuthorizationId);

            var paypalCurrency = PayPalHelper.GetPaypalCurrency(request.CurrencyIsoCode);

            //create a capture request for paypal
            var doCaptureRequest = new DoCaptureReq() {
                DoCaptureRequest = new DoCaptureRequestType() {
                    Version = ApiVersion,
                    AuthorizationID = authorizationId,
                    Amount = new BasicAmountType() {
                        value = Math.Round(request.Amount, 2).ToString("N", new CultureInfo("en-us")),
                        currencyID = paypalCurrency
                    },
                    CompleteType = CompleteCodeType.COMPLETE
                }
            };

            //get the service for paypal api
            var service = GetPayPalApiInterfaceServiceService();
            var paypalResponse = service.DoCapture(doCaptureRequest);

            var result = new TransactionResult();

            string error;
            var success = PayPalHelper.ParseResponseSuccess(paypalResponse, out error);
            if (success)
            {
                result.Success = true;
                result.SetParameter(PaymentParameterNames.CaptureId, paypalResponse.DoCaptureResponseDetails.PaymentInfo.TransactionID);
                result.SetParameter(PaymentParameterNames.CaptureResult, paypalResponse.Ack);
            }
            else
            {
                result.SetParameter(PaymentParameterNames.ErrorMessage, error);
            }

            return result;
        }
        protected void Submit_Click(object sender, EventArgs e)
        {
            // Create request object

            DoCaptureRequestType request =
                new DoCaptureRequestType();

            // (Required) Authorization identification number of the payment you want to capture. This is the transaction ID returned from DoExpressCheckoutPayment, DoDirectPayment, or CheckOut. For point-of-sale transactions, this is the transaction ID returned by the CheckOut call when the payment action is Authorization.
            request.AuthorizationID = authorizationId.Value;

            // (Required) Amount to capture.
            // Note: You must set the currencyID attribute to one of the three-character currency codes for any of the supported PayPal currencies.
            CurrencyCodeType currency = (CurrencyCodeType)
                Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue);
            request.Amount = new BasicAmountType(currency, amount.Value);

            // (Required) Indicates whether or not this is your last capture. It is one of the following values:
            // * Complete – This is the last capture you intend to make.
            // * NotComplete – You intend to make additional captures.
            if (completeType.SelectedIndex != 0)
            {
                request.CompleteType = (CompleteCodeType)
                    Enum.Parse(typeof(CompleteCodeType), completeType.SelectedValue);
            }
            // (Optional) An informational note about this settlement that is displayed to the buyer in email and in their transaction history.
            if (note.Value != string.Empty)
            {
                request.Note = note.Value;
            }
            // (Optional) Your invoice number or other identification number that is displayed to you and to the buyer in their transaction history. The value is recorded only if the authorization you are capturing is an Express Checkout order authorization.
            // Note: This value on DoCapture overwrites a value previously set on DoAuthorization.
            if (invoiceId.Value != string.Empty)
            {
                request.InvoiceID = invoiceId.Value;
            }
            // (Optional) Per transaction description of the payment that is passed to the buyer's credit card statement.
            //If you provide a value in this field, the full descriptor displayed on the buyer's statement has the following format:
            //<PP * | PAYPAL *><Merchant descriptor as set in the Payment Receiving Preferences><1 space><soft descriptor>
            //Character length and limitations: The soft descriptor can contain only the following characters:
            //Alphanumeric characters
            //- (dash)
            //* (asterisk)
            //. (period)
            //{space}
            //If you pass any other characters (such as ","), PayPal returns an error code.
            //The soft descriptor does not include the phone number, which can be toggled between your customer service number and PayPal's Customer Service number.
            //The maximum length of the soft descriptor is 22 characters. Of this, the PayPal prefix uses either 4 or 8 characters of the data format. Thus, the maximum length of the soft descriptor information that you can pass in this field is:
            //22 - len(<PP * | PAYPAL *>) - len(<Descriptor set in Payment Receiving Preferences> + 1)
            //For example, assume the following conditions:
            //The PayPal prefix toggle is set to PAYPAL * in PayPal's administration tools.
            //The merchant descriptor set in the Payment Receiving Preferences is set to EBAY.
            //The soft descriptor is passed in as JanesFlowerGifts LLC.
            //The resulting descriptor string on the credit card is:
            //PAYPAL *EBAY JanesFlow
            if (softDescriptor.Value != string.Empty)
            {
                request.Descriptor = softDescriptor.Value;
            }

            // Invoke the API
            DoCaptureReq wrapper = new DoCaptureReq();
            wrapper.DoCaptureRequest = 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 DoCapture method in service wrapper object
            DoCaptureResponseType doCaptureResponse =
                    service.DoCapture(wrapper);

            // Check for API return status
            setKeyResponseObjects(service, doCaptureResponse);
        }
    // # DoCapture API Operation 
    // Captures an authorized payment. 
    public DoCaptureResponseType DoCaptureAPIOperation()
    {
        // Create the DoCaptureResponseType object
        DoCaptureResponseType responseDoCaptureResponseType = new DoCaptureResponseType();

        try
        {
            // Create the DoCapture object
            DoCaptureReq doCapture = new DoCaptureReq();

            // `Amount` to capture which takes mandatory params:
            //
            // * `currencyCode`
            // * `amount`
            BasicAmountType amount = new BasicAmountType(CurrencyCodeType.USD, "4.00");

            // `DoCaptureRequest` which takes mandatory params:
            //
            // * `Authorization ID` - Authorization identification number of the
            // payment you want to capture. This is the transaction ID returned from
            // DoExpressCheckoutPayment, DoDirectPayment, or CheckOut. For
            // point-of-sale transactions, this is the transaction ID returned by
            // the CheckOut call when the payment action is Authorization.
            // * `amount` - Amount to capture
            // * `CompleteCode` - Indicates whether or not this is your last capture.
            // It is one of the following values:
            // * Complete – This is the last capture you intend to make.
            // * NotComplete – You intend to make additional captures.
            // `Note:
            // If Complete, any remaining amount of the original authorized
            // transaction is automatically voided and all remaining open
            // authorizations are voided.`
            DoCaptureRequestType doCaptureRequest = new DoCaptureRequestType("O-4VR15106P7416533H", amount, CompleteCodeType.NOTCOMPLETE);
            doCapture.DoCaptureRequest = doCaptureRequest;

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

            // # API call
            // Invoke the DoCapture method in service wrapper object
            responseDoCaptureResponseType = service.DoCapture(doCapture);

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

                // # Success values
                if (responseDoCaptureResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // Authorization identification number
                    logger.Info("Authorization ID : " + responseDoCaptureResponseType.DoCaptureResponseDetails.AuthorizationID + "\n");
                    Console.WriteLine("Authorization ID : " + responseDoCaptureResponseType.DoCaptureResponseDetails.AuthorizationID + "\n");

                }
                // # Error Values
                else
                {
                    List<ErrorType> errorMessages = responseDoCaptureResponseType.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 responseDoCaptureResponseType;
    }
		private DoCaptureReq GetDoCaptureRequest(PaymentIn payment)
		{
			var retVal = new DoCaptureReq();

			retVal.DoCaptureRequest = new DoCaptureRequestType();
			retVal.DoCaptureRequest.Amount = new BasicAmountType(GetPaypalCurrency(payment.Currency.ToString()), FormatMoney(payment.Sum));
			retVal.DoCaptureRequest.AuthorizationID = payment.OuterId;
			retVal.DoCaptureRequest.CompleteType = CompleteCodeType.COMPLETE;

			return retVal;
		}
 /**
   *AUTO_GENERATED
  	  */
 public DoCaptureResponseType DoCapture(DoCaptureReq doCaptureReq, string apiUserName)
 {
     setStandardParams(doCaptureReq.DoCaptureRequest);
     string response = Call("DoCapture", doCaptureReq.ToXMLString(), apiUserName);
     XmlDocument xmlDocument = new XmlDocument();
     xmlDocument.LoadXml(response);
     XmlNode xmlNode = xmlDocument.SelectSingleNode("*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='DoCaptureResponse']");
     return new DoCaptureResponseType(xmlNode);
 }
 public DoCaptureResponseType DoCapture(DoCaptureReq DoCaptureReq)
 {
     return DoCapture(DoCaptureReq, null);
 }
        /**
         *
         */
        public DoCaptureResponseType DoCapture(DoCaptureReq DoCaptureReq, string apiUsername)
        {
            setStandardParams(DoCaptureReq.DoCaptureRequest);
            string resp = call("DoCapture", DoCaptureReq.toXMLString(), apiUsername);

            return new DoCaptureResponseType(resp);
        }
        /// <summary>
        /// Handles DoCapture
        /// </summary>
        /// <param name="contextHttp"></param>
        private void DoCapture(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;

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

            // Creating service wrapper object to make an API call by loading configuration map.
            PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);

            // ## DoCaptureReq
            DoCaptureReq req = new DoCaptureReq();
            // 'Amount' to capture which takes mandatory params:
            //
            // * 'currencyCode'
            // * 'amount'
            BasicAmountType amount = new BasicAmountType(((CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), parameters["currencyCode"])), parameters["amt"]);

            // 'DoCaptureRequest' which takes mandatory params:
            //
            // * 'Authorization ID' - Authorization identification number of the
            // payment you want to capture. This is the transaction ID returned from
            // DoExpressCheckoutPayment, DoDirectPayment, or CheckOut. For
            // point-of-sale transactions, this is the transaction ID returned by
            // the CheckOut call when the payment action is Authorization.
            // * 'amount' - Amount to capture
            // * 'CompleteCode' - Indicates whether or not this is your last capture.
            // It is one of the following values:
            // * Complete – This is the last capture you intend to make.
            // * NotComplete – You intend to make additional captures.
            // 'Note:
            // If Complete, any remaining amount of the original authorized
            // transaction is automatically voided and all remaining open
            // authorizations are voided.'
            DoCaptureRequestType reqType = new DoCaptureRequestType
            (
                    parameters["authID"],
                    amount,
                    (CompleteCodeType)Enum.Parse(typeof(CompleteCodeType), parameters["completeCodeType"])
            );

            req.DoCaptureRequest = reqType;
            DoCaptureResponseType response = null;
            try
            {
                response = service.DoCapture(req);
            }
            catch (System.Exception ex)
            {
                contextHttp.Response.Write(ex.StackTrace);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            responseValues.Add("Acknowledgement", response.Ack.ToString().Trim().ToUpper());

            Display(contextHttp, "DoCapture", "DoCapture", responseValues, service.getLastRequest(), service.getLastResponse(), response.Errors, redirectUrl);
        }