Пример #1
0
        /// <summary>
        /// Handle SetPaymentOptions API call
        /// </summary>
        /// <param name="context"></param>
        private void SetPaymentOptions(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            SetPaymentOptionsRequest req = new SetPaymentOptionsRequest(
                    new RequestEnvelope("en_US"), parameters["payKey"]);
            if (parameters["institutionId"] != "")
            {
                req.initiatingEntity = new InitiatingEntity();
                req.initiatingEntity.institutionCustomer = new InstitutionCustomer(
                    parameters["institutionId"], parameters["firstName"],
                    parameters["lastName"], parameters["displayName"],
                    parameters["institutionCustomerId"], parameters["countryCode"]);
                if (parameters["email"] != "")
                {
                    req.initiatingEntity.institutionCustomer.email = parameters["email"];
                }
            }
            if (parameters["emailHeaderImageUrl"] != "" || parameters["emailMarketingImageUrl"] != ""
                || parameters["headerImageUrl"] != "" || parameters["businessName"] != "")
            {
                req.displayOptions = new DisplayOptions();
                if (parameters["emailHeaderImageUrl"] != "" )
                    req.displayOptions.emailHeaderImageUrl = parameters["emailHeaderImageUrl"];
                if (parameters["emailMarketingImageUrl"] != "")
                    req.displayOptions.emailMarketingImageUrl = parameters["emailMarketingImageUrl"];
                if(parameters["headerImageUrl"] != "" )
                    req.displayOptions.headerImageUrl = parameters["headerImageUrl"];
                if(parameters["businessName"] != "")
                    req.displayOptions.businessName = parameters["businessName"];
            }
            if (parameters["shippingAddressId"] != "")
            {
                req.shippingAddressId = parameters["shippingAddressId"];
            }
            if (parameters["requireShippingAddressSelection"] != "" || parameters["referrerCode"] != "")
            {
                req.senderOptions = new SenderOptions();
                if (parameters["requireShippingAddressSelection"] != "")
                    req.senderOptions.requireShippingAddressSelection =
                        Boolean.Parse(parameters["requireShippingAddressSelection"]);
                if (parameters["referrerCode"] != "")
                    req.senderOptions.referrerCode = parameters["referrerCode"];
            }
            req.receiverOptions = new List<ReceiverOptions>();
            ReceiverOptions receiverOption = new ReceiverOptions();
            req.receiverOptions.Add(receiverOption);
            if (parameters["description"] != "")
                receiverOption.description = parameters["description"];
            if (parameters["customId"] != "")
                receiverOption.customId = parameters["customId"];

            string[] name = context.Request.Form.GetValues("name");
            string[] identifier = context.Request.Form.GetValues("identifier");
            string[] price = context.Request.Form.GetValues("price");
            string[] itemPrice = context.Request.Form.GetValues("itemPrice");
            string[] itemCount = context.Request.Form.GetValues("itemCount");
            if (name.Length > 0 && name[0] != "")
            {
                receiverOption.invoiceData = new InvoiceData();
                for (int j = 0; j < name.Length; j++)
                {
                    InvoiceItem item = new InvoiceItem();
                    if (name[j] != "")
                        item.name = name[j];
                    if (identifier[j] != "")
                        item.identifier = identifier[j];
                    if (price[j] != "")
                        item.price = Decimal.Parse(price[j]);
                    if (itemPrice[j] != "")
                        item.itemPrice = Decimal.Parse(itemPrice[j]);
                    if (itemCount[j] != "")
                        item.itemCount = Int32.Parse(itemCount[j]);
                    receiverOption.invoiceData.item.Add(item);
                }

                if (parameters["totalTax"] != "")
                    receiverOption.invoiceData.totalTax = Decimal.Parse(parameters["totalTax"]);
                if (parameters["totalShipping"] != "")
                    receiverOption.invoiceData.totalShipping = Decimal.Parse(parameters["totalShipping"]);
            }
            if (parameters["emailIdentifier"] != "" ||
                (parameters["phoneCountry"] != "" && parameters["phoneNumber"] != ""))
            {
                receiverOption.receiver = new ReceiverIdentifier();
                if(parameters["emailIdentifier"] != "")
                    receiverOption.receiver.email = parameters["emailIdentifier"];
                if (parameters["phoneCountry"] != "" && parameters["phoneNumber"] != "")
                {
                    receiverOption.receiver.phone =
                        new PhoneNumberType(parameters["phoneCountry"], parameters["phoneNumber"]);
                    if (parameters["phoneExtn"] != "")
                        receiverOption.receiver.phone.extension = parameters["phoneExtn"];
                }
            }
            if (parameters["receiverReferrerCode"] != "")
                receiverOption.referrerCode = parameters["receiverReferrerCode"];

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            SetPaymentOptionsResponse resp = null;
            try
            {
                resp = service.SetPaymentOptions(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();

            //Selenium Test Case
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
            }

            displayResponse(context, "SetPaymentOptions", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, null);
        }
		public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context)
		{
			var retVal = new ProcessPaymentResult();

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

            if (!(!string.IsNullOrEmpty(context.Store.SecureUrl) || !string.IsNullOrEmpty(context.Store.Url)))
                throw new NullReferenceException("store must specify Url or SecureUrl property");

			var url = string.Empty;
			if (!string.IsNullOrEmpty(context.Store.SecureUrl))
			{
				url = context.Store.SecureUrl;
			}
			else
			{
				url = context.Store.Url;
			}

			var config = GetConfigMap();

			var service = new AdaptivePaymentsService(config);

			var request = CreatePaypalRequest(context.Order, context.Payment, url);

			var payResponse = service.Pay(request);
            var setPaymentOptionsResponse = service.SetPaymentOptions(new SetPaymentOptionsRequest { payKey = payResponse.payKey, senderOptions = new SenderOptions { referrerCode = "Virto_SP" } });
            var executePaymentResponse = service.ExecutePayment(new ExecutePaymentRequest { payKey = payResponse.payKey, actionType = "PAY", requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" } });

			if (executePaymentResponse.error != null && executePaymentResponse.error.Count > 0)
			{
				var sb = new StringBuilder();
				foreach (var error in executePaymentResponse.error)
				{
					sb.AppendLine(error.message);
				}
				retVal.Error = sb.ToString();
				retVal.NewPaymentStatus = PaymentStatus.Voided;
			}
			else
			{
				retVal.OuterId = payResponse.payKey;
				retVal.IsSuccess = true;
				var redirectBaseUrl = GetBaseUrl(Mode);
				retVal.RedirectUrl = string.Format(redirectBaseUrl, retVal.OuterId);
				retVal.NewPaymentStatus = PaymentStatus.Pending;
			}

			return retVal;
		}
        /// <summary>
        /// Handle SetPaymentOptions API call
        /// </summary>
        /// <param name="contextHttp"></param>
        private void SetPaymentOptions(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;

            // error language : (Required) RFC 3066 language in which error 
            // messages are returned; by default it is en_US, which is the only language currently supported. 
            // paykey : (Required) The pay key that identifies the payment for which you want 
            // to set payment options. This is the pay key returned in the PayResponse message.
            SetPaymentOptionsRequest request = new SetPaymentOptionsRequest(new RequestEnvelope("en_US"), parameters["payKey"]);
            if (parameters["institutionId"] != string.Empty)
            {
                request.initiatingEntity = new InitiatingEntity();
                // institutionid : (Required) The unique identifier assigned to the institution
                // firstname :  (Required) The first name of the consumer as known by the institution.
                // lastname: (Required) The last name of the consumer as known by the institution.
                // displayname : (Required) The full name of the consumer as known by the institution.
                // institutioncustomerid : (Required) The unique identifier assigned to the consumer by the institution
                // countrycode : (Required) The two-character country code of the home country of the end consumer
                // email : (Optional) The email address of the consumer as known by the institution.
                request.initiatingEntity.institutionCustomer = new InstitutionCustomer(
                    parameters["institutionId"], parameters["firstName"], 
                    parameters["lastName"], parameters["displayName"], 
                    parameters["institutionCustomerId"], parameters["countryCode"]);
                if (parameters["email"] != string.Empty)
                {
                    request.initiatingEntity.institutionCustomer.email = parameters["email"];
                }
            }

            if (parameters["emailHeaderImageUrl"] != string.Empty || parameters["emailMarketingImageUrl"] != string.Empty
                || parameters["headerImageUrl"] != string.Empty || parameters["businessName"] != string.Empty)
            {
                request.displayOptions = new DisplayOptions();

                //(Optional) The URL of the image that displays in the in the header of customer emails. 
                // The URL cannot exceed 1,024 characters. The image dimensions are 
                // 43 pixels high x 240 pixels wide.
                if (parameters["emailHeaderImageUrl"] != string.Empty )
                    request.displayOptions.emailHeaderImageUrl = parameters["emailHeaderImageUrl"];

                //(Optional) The URL of the image that displays in the in customer emails. 
                // The URL cannot exceed 1,024 characters. The image dimensions are 
                // 80 pixels high x 530 pixels wide.
                if (parameters["emailMarketingImageUrl"] != string.Empty)
                    request.displayOptions.emailMarketingImageUrl = parameters["emailMarketingImageUrl"];

                // (Optional) The URL of an image that displays in the header of a payment page. 
                // If set, it overrides the header image URL specified in your account's Profile. 
                // The URL cannot exceed 1,024 characters. The image dimensions are 
                // 90 pixels high x 750 pixels wide.
                if(parameters["headerImageUrl"] != string.Empty )
                    request.displayOptions.headerImageUrl = parameters["headerImageUrl"];

                //(Optional) The business name to display. The name cannot exceed 128 characters. 
                if(parameters["businessName"] != string.Empty)
                    request.displayOptions.businessName = parameters["businessName"];
            }
            if (parameters["shippingAddressId"] != string.Empty)
            {
                // (Optional) Sender's shipping address ID.
                request.shippingAddressId = parameters["shippingAddressId"];
            }

            if (parameters["requireShippingAddressSelection"] != string.Empty || parameters["referrerCode"] != string.Empty)
            {
                request.senderOptions = new SenderOptions();
                
                //(Optional) If true, require the sender to select a shipping address during 
                //the embedded payment flow;  default is false. 
                if (parameters["requireShippingAddressSelection"] != string.Empty)
                    request.senderOptions.requireShippingAddressSelection = 
                       Convert.ToBoolean(parameters["requireShippingAddressSelection"]);

                // (Optional) A code that identifies the partner associated with this transaction.
                // Maximum length: 32 characters.
                if (parameters["referrerCode"] != string.Empty)
                    request.senderOptions.referrerCode = parameters["referrerCode"];
            }
            request.receiverOptions = new List<ReceiverOptions>();
            ReceiverOptions receiverOption = new ReceiverOptions();
            request.receiverOptions.Add(receiverOption);

            //  (Optional) A description you want to associate with the payment. 
            // This overrides the value of the memo in Pay API for each receiver. 
            // If this is not specified the value in the memo will be used.
            // Maximum length: 1000 characters
            if (parameters["description"] != string.Empty)
                receiverOption.description = parameters["description"];

            // (Optional) An external reference or identifier you want to associate with the payment.
            // Maximum length: 1000 characters
            if (parameters["customId"] != string.Empty)
                receiverOption.customId = parameters["customId"];

            // (Optional) Name of item. 
            string[] name = contextHttp.Request.Form.GetValues("name");

            // (Optional) External reference to item or item ID. 
            string[] identifier = contextHttp.Request.Form.GetValues("identifier");

            // (Optional) Total of item line. 
            string[] price = contextHttp.Request.Form.GetValues("price");

            // (Optional) Price of an individual item. 
            string[] itemPrice = contextHttp.Request.Form.GetValues("itemPrice");

            // (Optional) Item quantity. 
            string[] itemCount = contextHttp.Request.Form.GetValues("itemCount");
            if (name.Length > 0 && name[0] != string.Empty)
            {
                receiverOption.invoiceData = new InvoiceData();
                for (int j = 0; j < name.Length; j++)
                {
                    InvoiceItem item = new InvoiceItem();
                    if (name[j] != string.Empty)
                        item.name = name[j];
                    if (identifier[j] != string.Empty)
                        item.identifier = identifier[j];
                    if (price[j] != string.Empty)
                        item.price = Convert.ToDecimal(price[j]);
                    if (itemPrice[j] != string.Empty)
                        item.itemPrice = Convert.ToDecimal(itemPrice[j]);
                    if (itemCount[j] != string.Empty)
                        item.itemCount = Convert.ToInt32(itemCount[j]);
                    receiverOption.invoiceData.item.Add(item);
                }

                // (Optional) Total tax associated with the payment. 
                if (parameters["totalTax"] != string.Empty)
                    receiverOption.invoiceData.totalTax = Convert.ToDecimal(parameters["totalTax"]);

                // (Optional) Total shipping charge associated with the payment. 
                if (parameters["totalShipping"] != string.Empty)
                    receiverOption.invoiceData.totalShipping = Convert.ToDecimal(parameters["totalShipping"]);
            }


            if (parameters["emailIdentifier"] != string.Empty ||
                (parameters["phoneCountry"] != string.Empty && parameters["phoneNumber"] != string.Empty))
            {
                receiverOption.receiver = new ReceiverIdentifier();

                // (Optional) Receiver's email address.Maximum length: 127 characters
                if(parameters["emailIdentifier"] != string.Empty)
                    receiverOption.receiver.email = parameters["emailIdentifier"];

                // (Optional) Receiver's phone number. 
                if (parameters["phoneCountry"] != string.Empty && parameters["phoneNumber"] != string.Empty)
                {
                    receiverOption.receiver.phone = 
                        new PhoneNumberType(parameters["phoneCountry"], parameters["phoneNumber"]);

                    // (Optional) Telephone extension. 
                    if (parameters["phoneExtn"] != string.Empty)
                        receiverOption.receiver.phone.extension = parameters["phoneExtn"];
                }
            }

            // (Optional) A code that identifies the partner associated with this transaction. 
            if (parameters["receiverReferrerCode"] != string.Empty)
                receiverOption.referrerCode = parameters["receiverReferrerCode"];
               
            AdaptivePaymentsService service = null;
            SetPaymentOptionsResponse response = null;
            try
            {
                // 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 and loading
                // configuration map for your credentials and endpoint
                service = new AdaptivePaymentsService(configurationMap);
                response = service.SetPaymentOptions(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }
                        
            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
            }

            Display(contextHttp, "SetPaymentOptions", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, null);
        }
    // # SetPaymentOptions API Operation
    // You use the SetPaymentOptions API operation to specify settings for a payment of the actionType CREATE. This actionType is specified in the PayRequest message. 
    public SetPaymentOptionsResponse SetPaymentOptionsAPIOperation()
    {
        // Create the SetPaymentOptionsResponse object
        SetPaymentOptionsResponse responseSetPaymentOptions = new SetPaymentOptionsResponse();

        try
        {
            // # SetPaymentOptionsRequest
            // The code for the language in which errors are returned
            RequestEnvelope envelopeRequest = new RequestEnvelope();
            envelopeRequest.errorLanguage = "en_US";

            // SetPaymentOptionsRequest which takes,
            //
            // * `Request Envelope` - Information common to each API operation, such
            // as the language in which an error message is returned.
            // * `Pay Key` - The pay key that identifies the payment for which you
            // want to set payment options. This is the pay key returned in the
            // PayResponse message. Action Type in PayRequest must be `CREATE`
            SetPaymentOptionsRequest requestSetPaymentOptions = new SetPaymentOptionsRequest(envelopeRequest, "AP-1VB65877N5917862M");

            // Specifies display items in payment flows and emails.
            DisplayOptions displayOptions = new DisplayOptions();

            // The business name to display      
            // The name cannot exceed 128 characters    
            displayOptions.businessName = "Toy Shop";
            requestSetPaymentOptions.displayOptions = displayOptions;

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

            // # API call
            // Invoke the SetPaymentOptions method in service wrapper object
            responseSetPaymentOptions = service.SetPaymentOptions(requestSetPaymentOptions);

            if (responseSetPaymentOptions != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "SetPaymentOptions API Operation - ";
                acknowledgement += responseSetPaymentOptions.responseEnvelope.ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responseSetPaymentOptions.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    responseSetPaymentOptions.responseEnvelope.ack.ToString();
                }
                // # Error Values                
                else
                {
                    List<ErrorData> errorMessages = responseSetPaymentOptions.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return responseSetPaymentOptions;
    }