private CreditCardDetailsType MapCardDetails(string CCNumber, string FirstName, string LastName, string Address, string City, string Zip, string State, string Country, string Telephone, string DOB, string EmailAddress, string CardHolderName, string ExpiryMonth, string ExpiryYear, string CVC2) { var details = new CreditCardDetailsType(); var payerInfo = new PayerInfoType(); var address = new AddressType(); var personalNameType = new PersonNameType(); // var cardType = MapCardType(CardType); personalNameType.FirstName = FirstName; personalNameType.LastName = LastName; payerInfo.Address = address; payerInfo.ContactPhone = Telephone; payerInfo.PayerName = personalNameType; details.CardOwner = payerInfo; details.CreditCardNumber = CCNumber; // details.CreditCardType = cardType; details.CVV2 = CVC2; details.ExpMonth = int.Parse(ExpiryMonth); details.ExpYear = int.Parse(ExpiryYear); return(details); }
private void SetEmail(GetExpressCheckoutDetailsResponseDetailsType details) { if (string.IsNullOrWhiteSpace(_cart.OrderEmail)) { PayerInfoType payer = details.PayerInfo; if (payer != null && !string.IsNullOrWhiteSpace(payer.Payer)) { _cartManager.SetOrderEmail(payer.Payer); } } }
private static DoDirectPaymentResponseType MakePayment(PaymentModel paymentModel) { // Create request object var request = new DoDirectPaymentRequestType(); var requestDetails = new DoDirectPaymentRequestDetailsType(); request.DoDirectPaymentRequestDetails = requestDetails; var creditCard = new CreditCardDetailsType(); requestDetails.CreditCard = creditCard; var payer = new PayerInfoType(); // (Optional) First and last name of buyer. PersonNameType name = new PersonNameType(); name.FirstName = string.Format("{0} {1}", SessionWrapper.LoggedUser.FirstName, SessionWrapper.LoggedUser.LastName); name.LastName = SessionWrapper.LoggedUser.Email; //pass buyer email address. payer.PayerName = name; creditCard.CardOwner = payer; creditCard.CreditCardNumber = paymentModel.CreditCardModel.CardNumber; creditCard.CreditCardType = (CreditCardTypeType) Enum.Parse(typeof(CreditCardTypeType), paymentModel.CreditCardModel.CardType.ToUpper()); creditCard.CVV2 = paymentModel.CreditCardModel.SecurityCode; creditCard.ExpMonth = Convert.ToInt32(paymentModel.CreditCardModel.ExpMonth); creditCard.ExpYear = Convert.ToInt32(paymentModel.CreditCardModel.ExpYear); requestDetails.PaymentDetails = new PaymentDetailsType(); CurrencyCodeType currency = (CurrencyCodeType) Enum.Parse(typeof(CurrencyCodeType), "USD"); var paymentAmount = new BasicAmountType(currency, paymentModel.OrderDetailModel.TotalOrder.ToString()); requestDetails.PaymentDetails.OrderTotal = paymentAmount; // Invoke the API var wrapper = new DoDirectPaymentReq(); wrapper.DoDirectPaymentRequest = request; var service = new PayPalAPIInterfaceServiceService(); // API call return(service.DoDirectPayment(wrapper)); }
private static DoDirectPaymentResponseType MakePayment(PaymentWalletModal paymentModel) { // Create request object var request = new DoDirectPaymentRequestType(); var requestDetails = new DoDirectPaymentRequestDetailsType(); request.DoDirectPaymentRequestDetails = requestDetails; var creditCard = new CreditCardDetailsType(); requestDetails.CreditCard = creditCard; var payer = new PayerInfoType(); creditCard.CardOwner = payer; creditCard.CreditCardNumber = paymentModel.CardNumber; creditCard.CreditCardType = (CreditCardTypeType) Enum.Parse(typeof(CreditCardTypeType), paymentModel.CardType.ToUpper()); creditCard.CVV2 = paymentModel.SecurityCode; creditCard.ExpMonth = Convert.ToInt32(paymentModel.ExpMonth); creditCard.ExpYear = Convert.ToInt32(paymentModel.ExpYear); requestDetails.PaymentDetails = new PaymentDetailsType(); CurrencyCodeType currency = (CurrencyCodeType) Enum.Parse(typeof(CurrencyCodeType), "USD"); var paymentAmount = new BasicAmountType(currency, paymentModel.Amount); requestDetails.PaymentDetails.OrderTotal = paymentAmount; // Invoke the API var wrapper = new DoDirectPaymentReq(); wrapper.DoDirectPaymentRequest = request; var service = new PayPalAPIInterfaceServiceService(); // API call return(service.DoDirectPayment(wrapper)); }
/// <summary> /// Processes the checkout details from PayPal, update changed addresses appropriately. /// </summary> /// <param name="payerInfo">The PayPal payer info.</param> /// <param name="payPalAddress">The PayPal address.</param> /// <param name="orderAddress">The order address to process.</param> /// <param name="customerAddressType">The order address to process.</param> /// <param name="emptyAddressMsgKey">The empty address message language key in lang.xml file.</param> public string ProcessOrderAddress(PayerInfoType payerInfo, AddressType payPalAddress, IOrderAddress orderAddress, CustomerAddressTypeEnum customerAddressType, string emptyAddressMsgKey) { if (payPalAddress == null) { return(_localizationService.GetString(emptyAddressMsgKey)); } if (orderAddress == null) { return(_localizationService.GetString("/Commerce/Checkout/PayPal/CommitTranErrorCartReset")); } if (string.IsNullOrEmpty(payPalAddress.Phone) && !string.IsNullOrEmpty(payerInfo?.ContactPhone)) { payPalAddress.Phone = payerInfo.ContactPhone; } AddressHandling.UpdateOrderAddress(orderAddress, customerAddressType, payPalAddress, payerInfo.Payer); return(string.Empty); }
// ProcessCard() is used for Credit Card processing via Website Payments Pro, // just like other credit card gateways. // ProcessPaypal() is used for Express Checkout and PayPal payments. public override string ProcessCard(int OrderNumber, int CustomerID, decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, Address UseBillingAddress, string CardExtraCode, Address UseShippingAddress, string CAVV, string ECI, string XID, out string AVSResult, out string AuthorizationResult, out string AuthorizationCode, out string AuthorizationTransID, out string TransactionCommandOut, out string TransactionResponse) { String result = AppLogic.ro_OK; AuthorizationCode = String.Empty; AuthorizationResult = String.Empty; AuthorizationTransID = String.Empty; AVSResult = String.Empty; TransactionCommandOut = String.Empty; TransactionResponse = String.Empty; try { // the request details object contains all payment details DoDirectPaymentRequestDetailsType RequestDetails = new DoDirectPaymentRequestDetailsType(); // define the payment action to 'Sale' // (another option is 'Authorization', which would be followed later with a DoCapture API call) RequestDetails.PaymentAction = (PaymentActionCodeType)CommonLogic.IIF(AppLogic.TransactionModeIsAuthOnly(), (int)PaymentActionCodeType.Authorization, (int)PaymentActionCodeType.Sale); // define the total amount and currency for the transaction PaymentDetailsType PaymentDetails = new PaymentDetailsType(); BasicAmountType totalAmount = new BasicAmountType(); totalAmount.Value = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal); totalAmount.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true); PaymentDetails.OrderTotal = totalAmount; PaymentDetails.InvoiceID = OrderNumber.ToString(); PaymentDetails.ButtonSource = PayPal.BN + "_DP_US"; PaymentDetails.OrderDescription = AppLogic.AppConfig("StoreName"); // define the credit card to be used CreditCardDetailsType creditCard = new CreditCardDetailsType(); creditCard.CreditCardNumber = UseBillingAddress.CardNumber; creditCard.ExpMonth = Localization.ParseUSInt(UseBillingAddress.CardExpirationMonth); creditCard.ExpYear = Localization.ParseUSInt(UseBillingAddress.CardExpirationYear); creditCard.ExpMonthSpecified = true; creditCard.ExpYearSpecified = true; creditCard.CVV2 = CardExtraCode; if (UseBillingAddress.CardType == "AmericanExpress") { creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), "Amex", true); } else { creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), UseBillingAddress.CardType, true); } creditCard.CreditCardTypeSpecified = true; PayerInfoType cardHolder = new PayerInfoType(); PersonNameType oPersonNameType = new PersonNameType(); oPersonNameType.FirstName = UseBillingAddress.FirstName; oPersonNameType.LastName = UseBillingAddress.LastName; oPersonNameType.MiddleName = String.Empty; oPersonNameType.Salutation = String.Empty; oPersonNameType.Suffix = String.Empty; cardHolder.PayerName = oPersonNameType; AddressType PayerAddress = new AddressType(); PayerAddress.Street1 = UseBillingAddress.Address1; PayerAddress.CityName = UseBillingAddress.City; PayerAddress.StateOrProvince = UseBillingAddress.State; PayerAddress.PostalCode = UseBillingAddress.Zip; PayerAddress.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country), true); PayerAddress.CountrySpecified = true; if (UseShippingAddress != null) { AddressType shippingAddress = new AddressType(); shippingAddress.Name = (UseShippingAddress.FirstName + " " + UseShippingAddress.LastName).Trim(); shippingAddress.Street1 = UseShippingAddress.Address1; shippingAddress.Street2 = UseShippingAddress.Address2 + CommonLogic.IIF(UseShippingAddress.Suite != "", " Ste " + UseShippingAddress.Suite, ""); shippingAddress.CityName = UseShippingAddress.City; shippingAddress.StateOrProvince = UseShippingAddress.State; shippingAddress.PostalCode = UseShippingAddress.Zip; shippingAddress.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), AppLogic.GetCountryTwoLetterISOCode(UseShippingAddress.Country), true); shippingAddress.CountrySpecified = true; PaymentDetails.ShipToAddress = shippingAddress; } cardHolder.Address = PayerAddress; creditCard.CardOwner = cardHolder; RequestDetails.CreditCard = creditCard; RequestDetails.PaymentDetails = PaymentDetails; RequestDetails.IPAddress = CommonLogic.CustomerIpAddress(); // cart.ThisCustomer.LastIPAddress; if (RequestDetails.IPAddress == "::1") { RequestDetails.IPAddress = "127.0.0.1"; } // instantiate the actual request object PaymentRequest = new DoDirectPaymentRequestType(); PaymentRequest.Version = API_VER; PaymentRequest.DoDirectPaymentRequestDetails = RequestDetails; DDPReq = new DoDirectPaymentReq(); DDPReq.DoDirectPaymentRequest = PaymentRequest; DoDirectPaymentResponseType responseDetails = (DoDirectPaymentResponseType)IPayPal.DoDirectPayment(DDPReq); //if (LogToErrorTable) //{ // PayPalController.Log(XmlCommon.SerializeObject(DDPReq, DDPReq.GetType()), "DoDirectPayment Request"); // PayPalController.Log(XmlCommon.SerializeObject(responseDetails, responseDetails.GetType()), "DoDirectPayment Response"); //} if (responseDetails != null && responseDetails.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase)) { AuthorizationTransID = CommonLogic.IIF(TransactionMode.ToString().ToLower() == AppLogic.ro_TXModeAuthOnly.ToLower(), "AUTH=", "CAPTURE=") + responseDetails.TransactionID.ToString(); AuthorizationCode = responseDetails.CorrelationID; AVSResult = responseDetails.AVSCode; result = AppLogic.ro_OK; AuthorizationResult = responseDetails.Ack.ToString() + "|AVSCode=" + responseDetails.AVSCode.ToString() + "|CVV2Code=" + responseDetails.CVV2Code.ToString(); } else { if (responseDetails.Errors != null) { String Separator = String.Empty; for (int ix = 0; ix < responseDetails.Errors.Length; ix++) { AuthorizationResult += Separator; AuthorizationResult += responseDetails.Errors[ix].LongMessage; // record failed TX TransactionResponse += Separator; try { TransactionResponse += String.Format("|{0},{1},{2}|", responseDetails.Errors[ix].ShortMessage, responseDetails.Errors[ix].ErrorCode, responseDetails.Errors[ix].LongMessage); // record failed TX } catch { } Separator = ", "; } } result = AuthorizationResult; // just store something here, as there is no other way to get data out of this gateway about the failure for logging in failed transaction table } } catch { result = "Transaction Failed"; } return(result); }
public TransactionResult SubmitPaymentTransaction(CheckoutDetails details) { //init result structure TransactionResult ret = new TransactionResult(); //set up Request //instantiate DoDirectPaymentRequestType and RequestDetails objects DoDirectPaymentRequestType request = new DoDirectPaymentRequestType(); request.Version = PROCESSOR_VERSION; DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType(); request.DoDirectPaymentRequestDetails = requestDetails; //set payment action requestDetails.PaymentAction = PaymentActionCodeType.Sale; //set IP //requestDetails.IPAddress = Request.UserHostAddress; requestDetails.IPAddress = details[CheckoutKeys.IPAddress]; //set CreditCard info CreditCardDetailsType creditCardDetails = new CreditCardDetailsType(); requestDetails.CreditCard = creditCardDetails; creditCardDetails.CreditCardNumber = details[CheckoutKeys.CardNumber]; creditCardDetails.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), details[CheckoutKeys.CardType], true); creditCardDetails.CVV2 = details[CheckoutKeys.VerificationCode]; creditCardDetails.ExpMonth = Int32.Parse(details[CheckoutKeys.ExpireMonth]); creditCardDetails.ExpYear = Int32.Parse(details[CheckoutKeys.ExpireYear]); // Switch/Solo if (creditCardDetails.CreditCardType == CreditCardTypeType.Solo || creditCardDetails.CreditCardType == CreditCardTypeType.Switch) { creditCardDetails.StartMonth = Int32.Parse(details[CheckoutKeys.StartMonth]); creditCardDetails.StartYear = Int32.Parse(details[CheckoutKeys.StartYear]); creditCardDetails.IssueNumber = details[CheckoutKeys.IssueNumber]; } //set billing address PayerInfoType cardOwner = new PayerInfoType(); creditCardDetails.CardOwner = cardOwner; cardOwner.PayerName = new PersonNameType(); cardOwner.PayerName.FirstName = details[CheckoutKeys.FirstName]; cardOwner.PayerName.LastName = details[CheckoutKeys.LastName]; cardOwner.Address = new AddressType(); cardOwner.Address.Street1 = details[CheckoutKeys.Address]; //??? cardOwner.Address.Street2 = ""; cardOwner.Address.CityName = details[CheckoutKeys.City]; cardOwner.Address.StateOrProvince = details[CheckoutKeys.State]; cardOwner.Address.PostalCode = details[CheckoutKeys.Zip]; cardOwner.Address.CountrySpecified = true; cardOwner.Address.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), details[CheckoutKeys.Country], true); //set payment Details PaymentDetailsType paymentDetails = new PaymentDetailsType(); requestDetails.PaymentDetails = paymentDetails; paymentDetails.OrderTotal = new BasicAmountType(); //TODO: Add currency support paymentDetails.OrderTotal.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), details[CheckoutKeys.Currency]); //paymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD; //No currency symbol. Decimal separator must be a period (.), and the thousands separator must be a comma (,) paymentDetails.OrderTotal.Value = details[CheckoutKeys.Amount]; DoDirectPaymentReq paymentRequest = new DoDirectPaymentReq(); paymentRequest.DoDirectPaymentRequest = request; //FINISH set up req //setup request Header, API credentials PayPalAPIAASoapBinding paypalInterface = new PayPalAPIAASoapBinding(); UserIdPasswordType user = new UserIdPasswordType(); //set api credentials - username, password, signature user.Username = Username; user.Password = Password; user.Signature = Signature; // setup service url paypalInterface.Url = ServiceUrl; paypalInterface.RequesterCredentials = new CustomSecurityHeaderType(); paypalInterface.RequesterCredentials.Credentials = user; //make call return response DoDirectPaymentResponseType paymentResponse = new DoDirectPaymentResponseType(); paymentResponse = paypalInterface.DoDirectPayment(paymentRequest); //write response xml to the ret object ret.RawResponse = SerializeObject(paymentResponse); switch (paymentResponse.Ack) { case AckCodeType.Success: case AckCodeType.SuccessWithWarning: ret.Succeed = true; ret.TransactionId = paymentResponse.TransactionID; ret.TransactionStatus = TransactionStatus.Approved; break; default: // show errors if Ack is NOT Success ret.Succeed = false; ret.TransactionStatus = TransactionStatus.Declined; if (paymentResponse.Errors != null && paymentResponse.Errors.Length > 0) { ret.StatusCode = PayPalProKeys.ErrorPrefix + paymentResponse.Errors[0].ErrorCode; } break; } return(ret); }
protected void Submit_Click(object sender, EventArgs e) { // Create request object DoDirectPaymentRequestType request = new DoDirectPaymentRequestType(); DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType(); request.DoDirectPaymentRequestDetails = requestDetails; // (Optional) 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. // * Sale – This is a final sale for which you are requesting payment (default). // Note: Order is not allowed for Direct Payment. requestDetails.PaymentAction = (PaymentActionCodeType) Enum.Parse(typeof(PaymentActionCodeType), paymentType.SelectedValue); // (Required) Information about the credit card to be charged. CreditCardDetailsType creditCard = new CreditCardDetailsType(); requestDetails.CreditCard = creditCard; PayerInfoType payer = new PayerInfoType(); // (Optional) First and last name of buyer. PersonNameType name = new PersonNameType(); name.FirstName = firstName.Value; name.LastName = lastName.Value; payer.PayerName = name; // (Required) Details about the owner of the credit card. creditCard.CardOwner = payer; // (Required) Credit card number. creditCard.CreditCardNumber = creditCardNumber.Value; // (Optional) Type of credit card. For UK, only Maestro, MasterCard, Discover, and Visa are allowable. For Canada, only MasterCard and Visa are allowable and Interac debit cards are not supported. It is one of the following values: // * Visa // * MasterCard // * Discover // * Amex // * Maestro: See note. // Note: If the credit card type is Maestro, you must set currencyId to GBP. In addition, you must specify either StartMonth and StartYear or IssueNumber. creditCard.CreditCardType = (CreditCardTypeType) Enum.Parse(typeof(CreditCardTypeType), creditCardType.SelectedValue); // Card Verification Value, version 2. Your Merchant Account settings determine whether this field is required. To comply with credit card processing regulations, you must not store this value after a transaction has been completed. // Character length and limitations: For Visa, MasterCard, and Discover, the value is exactly 3 digits. For American Express, the value is exactly 4 digits. creditCard.CVV2 = cvv2Number.Value; string[] cardExpiryDetails = cardExpiryDate.Text.Split(new char[] { '/' }); if (cardExpiryDetails.Length == 2) { // (Required) Credit card expiration month. creditCard.ExpMonth = Convert.ToInt32(cardExpiryDetails[0]); // (Required) Credit card expiration year. creditCard.ExpYear = Convert.ToInt32(cardExpiryDetails[1]); } requestDetails.PaymentDetails = new PaymentDetailsType(); // (Optional) Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists. // Important: The notify URL applies only to DoExpressCheckoutPayment. This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails. requestDetails.PaymentDetails.NotifyURL = ipnNotificationUrl.Value.Trim(); // (Optional) Buyer's shipping address information. AddressType billingAddr = new AddressType(); if (firstName.Value != string.Empty && lastName.Value != string.Empty && street1.Value != string.Empty && country.Value != string.Empty) { billingAddr.Name = payerName.Value; // (Required) First street address. billingAddr.Street1 = street1.Value; // (Optional) Second street address. billingAddr.Street2 = street2.Value; // (Required) Name of city. billingAddr.CityName = city.Value; // (Required) State or province. billingAddr.StateOrProvince = state.Value; // (Required) Country code. billingAddr.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), country.Value); // (Required) U.S. ZIP code or other country-specific postal code. billingAddr.PostalCode = postalCode.Value; // (Optional) Phone number. billingAddr.Phone = phone.Value; payer.Address = billingAddr; } // (Required) The total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current subtotal of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. This field must be set to a value greater than 0. // Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies. CurrencyCodeType currency = (CurrencyCodeType) Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue); BasicAmountType paymentAmount = new BasicAmountType(currency, amount.Value); requestDetails.PaymentDetails.OrderTotal = paymentAmount; // Invoke the API DoDirectPaymentReq wrapper = new DoDirectPaymentReq(); wrapper.DoDirectPaymentRequest = 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 DoDirectPayment method in service wrapper object DoDirectPaymentResponseType response = service.DoDirectPayment(wrapper); // Check for API return status setKeyResponseObjects(service, response); }
// # DoDirectPaymentAPIOperation // The MassPay API operation makes a payment to one or more PayPal account holders. public DoDirectPaymentResponseType DoDirectPaymentAPIOperation() { // Create the DoDirectPaymentResponseType object DoDirectPaymentResponseType responseDoDirectPaymentResponseType = new DoDirectPaymentResponseType(); try { // Create the DoDirectPaymentReq object DoDirectPaymentReq doDirectPayment = new DoDirectPaymentReq(); DoDirectPaymentRequestDetailsType doDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType(); // Information about the credit card to be charged. CreditCardDetailsType creditCard = new CreditCardDetailsType(); // Type of credit card. For UK, only Maestro, MasterCard, Discover, and // Visa are allowable. For Canada, only MasterCard and Visa are // allowable and Interac debit cards are not supported. It is one of the // following values: // // * Visa // * MasterCard // * Discover // * Amex // * Solo // * Switch // * Maestro: See note. // `Note: // If the credit card type is Maestro, you must set currencyId to GBP. // In addition, you must specify either StartMonth and StartYear or // IssueNumber.` creditCard.CreditCardType = CreditCardTypeType.VISA; // Credit Card number creditCard.CreditCardNumber = "4770461107194023"; // ExpiryMonth of credit card creditCard.ExpMonth = Convert.ToInt32("12"); // Expiry Year of credit card creditCard.ExpYear = Convert.ToInt32("2021"); //Details about the owner of the credit card. PayerInfoType cardOwner = new PayerInfoType(); // Email address of buyer. cardOwner.Payer = "*****@*****.**"; creditCard.CardOwner = cardOwner; doDirectPaymentRequestDetails.CreditCard = creditCard; // Information about the payment PaymentDetailsType paymentDetails = new PaymentDetailsType(); // IPN URL // * PayPal Instant Payment Notification is a call back system that is initiated when a transaction is completed // * The transaction related IPN variables will be received on the call back URL specified in the request // * The IPN variables have to be sent back to the PayPal system for validation, upon validation PayPal will send a response string "VERIFIED" or "INVALID" // * PayPal would continuously resend IPN if a wrong IPN is sent paymentDetails.NotifyURL = "http://IPNhost"; // Total cost of the transaction to the buyer. If shipping cost and tax // charges are known, include them in this value. If not, this value // should be the current sub-total of the order. // // If the transaction includes one or more one-time purchases, this field must be equal to // the sum of the purchases. Set this field to 0 if the transaction does // not include a one-time purchase such as when you set up a billing // agreement for a recurring payment that is not immediately charged. // When the field is set to 0, purchase-specific fields are ignored. // // * `Currency Code` - You must set the currencyID attribute to one of the // 3-character currency codes for any of the supported PayPal // currencies. // * `Amount` BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.USD, "4.00"); paymentDetails.OrderTotal = orderTotal; doDirectPaymentRequestDetails.PaymentDetails = paymentDetails; // IP address of the buyer's browser. // `Note: // PayPal records this IP addresses as a means to detect possible fraud.` doDirectPaymentRequestDetails.IPAddress = "127.0.0.1"; DoDirectPaymentRequestType doDirectPaymentRequest = new DoDirectPaymentRequestType(doDirectPaymentRequestDetails); doDirectPayment.DoDirectPaymentRequest = doDirectPaymentRequest; // Create the service wrapper object to make the API call PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(); // # API call // Invoke the DoDirectPayment method in service wrapper object responseDoDirectPaymentResponseType = service.DoDirectPayment(doDirectPayment); if (responseDoDirectPaymentResponseType != null) { // Response envelope acknowledgement string acknowledgement = "DoDirectPayment API Operation - "; acknowledgement += responseDoDirectPaymentResponseType.Ack.ToString(); logger.Info(acknowledgement + "\n"); Console.WriteLine(acknowledgement + "\n"); // # Success values if (responseDoDirectPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS")) { // Unique identifier of the transaction logger.Info("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n"); Console.WriteLine("Transaction ID : " + responseDoDirectPaymentResponseType.TransactionID + "\n"); } // # Error Values else { List <ErrorType> errorMessages = responseDoDirectPaymentResponseType.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(responseDoDirectPaymentResponseType); }
protected void Submit_Click(object sender, EventArgs e) { // Create request object DoDirectPaymentRequestType request = new DoDirectPaymentRequestType(); DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType(); request.DoDirectPaymentRequestDetails = requestDetails; requestDetails.PaymentAction = (PaymentActionCodeType) Enum.Parse(typeof(PaymentActionCodeType), paymentType.SelectedValue); // Populate card requestDetails CreditCardDetailsType creditCard = new CreditCardDetailsType(); requestDetails.CreditCard = creditCard; PayerInfoType payer = new PayerInfoType(); PersonNameType name = new PersonNameType(); name.FirstName = firstName.Value; name.LastName = lastName.Value; payer.PayerName = name; creditCard.CardOwner = payer; creditCard.CreditCardNumber = creditCardNumber.Value; creditCard.CreditCardType = (CreditCardTypeType) Enum.Parse(typeof(CreditCardTypeType), creditCardType.SelectedValue); creditCard.CVV2 = cvv2Number.Value; string[] cardExpiryDetails = cardExpiryDate.Text.Split(new char[] { '/' }); if (cardExpiryDetails.Length == 2) { creditCard.ExpMonth = Int32.Parse(cardExpiryDetails[0]); creditCard.ExpYear = Int32.Parse(cardExpiryDetails[1]); } requestDetails.PaymentDetails = new PaymentDetailsType(); AddressType billingAddr = new AddressType(); if (firstName.Value != "" && lastName.Value != "" && street1.Value != "" && country.Value != "") { billingAddr.Name = payerName.Value; billingAddr.Street1 = street1.Value; billingAddr.Street2 = street2.Value; billingAddr.CityName = city.Value; billingAddr.StateOrProvince = state.Value; billingAddr.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), country.Value); billingAddr.PostalCode = postalCode.Value; //Fix for release billingAddr.Phone = phone.Value; payer.Address = billingAddr; } // Populate payment requestDetails CurrencyCodeType currency = (CurrencyCodeType) Enum.Parse(typeof(CurrencyCodeType), currencyCode.SelectedValue); BasicAmountType paymentAmount = new BasicAmountType(currency, amount.Value); requestDetails.PaymentDetails.OrderTotal = paymentAmount; // Invoke the API DoDirectPaymentReq wrapper = new DoDirectPaymentReq(); wrapper.DoDirectPaymentRequest = request; PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(); DoDirectPaymentResponseType response = service.DoDirectPayment(wrapper); // Check for API return status setKeyResponseObjects(service, response); }
protected void BtnPayNow_Click(object sender, EventArgs e) { Customer c = (Customer)Session["User"] as Customer; CreditCardDetailsType creditCard = new CreditCardDetailsType(); switch (rblCardType.SelectedValue) { case "visa": creditCard.CreditCardType = CreditCardTypeType.VISA; break; case "mastercard": creditCard.CreditCardType = CreditCardTypeType.MASTERCARD; break; //case "discover": // creditCard.CreditCardType = CreditCardTypeType.DISCOVER; // break; //case "amex": // creditCard.CreditCardType = CreditCardTypeType.AMEX; // break; } creditCard.CreditCardNumber = txtCardNumber.Text; creditCard.ExpMonth = Convert.ToInt16(ddlMonthExp.SelectedValue); creditCard.ExpYear = Convert.ToInt16(ddlExpYear.SelectedValue); AddressType adrs = new AddressType { Street1 = txtAddress.Text, StateOrProvince = ddlState.SelectedValue, PostalCode = txtPostalCode.Text, CityName = txtCity.Text }; PayerInfoType cardOwner = new PayerInfoType { Payer = c.Email }; switch (ddlCountry.SelectedValue) { case "CA": cardOwner.PayerCountry = CountryCodeType.CA; adrs.Country = CountryCodeType.CA; break; case "US": cardOwner.PayerCountry = CountryCodeType.US; adrs.Country = CountryCodeType.US; break; } cardOwner.Address = adrs; PersonNameType payer = new PersonNameType { FirstName = txtFirstNameOnCard.Text.ToUpper(), LastName = txtLastNameOnCard.Text.ToUpper() }; cardOwner.PayerName = payer; creditCard.CardOwner = cardOwner; switch (Request.QueryString["item"]) { case "ad": switch (Request.QueryString["size"]) { case "L": Session["AdType"] = "Business Ad Large"; GetPaid("ad", "Large Ad (rotating banner)", "599", creditCard); break; case "S": Session["AdType"] = "Business Ad Small"; GetPaid("ad", "Small Ad (rotating images)", "299", creditCard); break; } break; case "car": string amount = string.Empty; switch (Request.QueryString["adtype"]) { case "Business": Session["AdType"] = "Dealership item sales ad"; amount = "19.99"; break; case "Private": Session["AdType"] = "Private item sales ad"; amount = "0.99"; break; } switch (Request.QueryString["size"]) { case "1": GetPaid("car", "1 vehicle", amount, creditCard); break; case "8": GetPaid("car", "8 vehicles", "89.99", creditCard); break; case "20": GetPaid("car", "20 vehicles", "199.99", creditCard); break; } break; } }
public Response PerformRequest(Request request) { // Create request object DoDirectPaymentRequestType paypalRequest = new DoDirectPaymentRequestType(); DoDirectPaymentRequestDetailsType requestDetails = new DoDirectPaymentRequestDetailsType(); paypalRequest.DoDirectPaymentRequestDetails = requestDetails; // (Optional) 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. // * Sale – This is a final sale for which you are requesting payment (default). // Note: Order is not allowed for Direct Payment. requestDetails.PaymentAction = (PaymentActionCodeType) Enum.Parse(typeof(PaymentActionCodeType), gatewaySettings.PaymentAction.ToUpper()); // (Required) Information about the credit card to be charged. CreditCardDetailsType creditCard = new CreditCardDetailsType(); requestDetails.CreditCard = creditCard; PayerInfoType payer = new PayerInfoType(); // (Optional) First and last name of buyer. PersonNameType name = new PersonNameType(); name.FirstName = request.FirstName; name.LastName = request.LastName; payer.PayerName = name; // (Required) Details about the owner of the credit card. creditCard.CardOwner = payer; // (Required) Credit card number. creditCard.CreditCardNumber = request.CardNumber; // (Optional) Type of credit card. For UK, only Maestro, MasterCard, Discover, and Visa are allowable. For Canada, only MasterCard and Visa are allowable and Interac debit cards are not supported. It is one of the following values: // * Visa // * MasterCard // * Discover // * Amex // * Maestro: See note. // Note: If the credit card type is Maestro, you must set currencyId to GBP. In addition, you must specify either StartMonth and StartYear or IssueNumber. creditCard.CreditCardType = (CreditCardTypeType) Enum.Parse(typeof(CreditCardTypeType), UpdateCreditCardType(request.CardType)); // Card Verification Value, version 2. Your Merchant Account settings determine whether this field is required. To comply with credit card processing regulations, you must not store this value after a transaction has been completed. // Character length and limitations: For Visa, MasterCard, and Discover, the value is exactly 3 digits. For American Express, the value is exactly 4 digits. creditCard.CVV2 = request.CardCvv; // (Required) Credit card expiration month. creditCard.ExpMonth = request.ExpireDate.Month; // (Required) Credit card expiration year. creditCard.ExpYear = request.ExpireDate.Year; requestDetails.PaymentDetails = new PaymentDetailsType(); // (Optional) Your URL for receiving Instant Payment Notification (IPN) about this transaction. If you do not specify this value in the request, the notification URL from your Merchant Profile is used, if one exists. // Important: The notify URL applies only to DoExpressCheckoutPayment. This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails. //requestDetails.PaymentDetails.NotifyURL = ""; // (Optional) Buyer's shipping address information. AddressType billingAddr = new AddressType(); billingAddr.Name = request.FirstName + " " + request.LastName; // (Required) First street address. billingAddr.Street1 = request.Address1; // (Optional) Second street address. billingAddr.Street2 = request.Address2; // (Required) Name of city. billingAddr.CityName = request.City; // (Required) State or province. billingAddr.StateOrProvince = request.State; // (Required) Country code. billingAddr.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), request.Country); // (Required) U.S. ZIP code or other country-specific postal code. billingAddr.PostalCode = request.ZipCode; // (Optional) Phone number. billingAddr.Phone = request.Phone; payer.Address = billingAddr; AddressType shippingAddr = new AddressType(); shippingAddr.Name = request.ShipToFirstName + " " + request.ShipToLastName; shippingAddr.Street1 = request.ShipToAddress; shippingAddr.CityName = request.ShipToCity; shippingAddr.StateOrProvince = request.ShipToState; shippingAddr.PostalCode = request.ShipToZipCode; shippingAddr.Country = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), request.ShipToCountry); requestDetails.PaymentDetails.ShipToAddress = shippingAddr; // (Required) The total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current subtotal of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. This field must be set to a value greater than 0. // Note: You must set the currencyID attribute to one of the 3-character currency codes for any of the supported PayPal currencies. CurrencyCodeType currency = (CurrencyCodeType) Enum.Parse(typeof(CurrencyCodeType), gatewaySettings.CurrencyCode); BasicAmountType paymentAmount = new BasicAmountType(currency, request.Amount.ToString("N2")); requestDetails.PaymentDetails.OrderTotal = paymentAmount; requestDetails.PaymentDetails.ItemTotal = new BasicAmountType(currency, Convert.ToDouble(request.SubTotal ?? "0").ToString("N2")); requestDetails.PaymentDetails.ShippingTotal = new BasicAmountType(currency, Convert.ToDouble(request.ShippingTotal ?? "0").ToString("N2")); requestDetails.PaymentDetails.TaxTotal = new BasicAmountType(currency, Convert.ToDouble(request.Tax ?? "0").ToString("N2")); // add skus List <PaymentDetailsItemType> items = new List <PaymentDetailsItemType>(); foreach (PaymentSku sku in request.SkuItems) { PaymentDetailsItemType item = new PaymentDetailsItemType(); item.Amount = new BasicAmountType(currency, (sku.InitialPrice * sku.Quantity).ToString("N2")); item.Quantity = sku.Quantity; item.Name = sku.Title; item.Number = sku.SkuCode; item.Description = sku.LongDescription; items.Add(item); } requestDetails.PaymentDetails.PaymentDetailsItem = items; // Invoke the API DoDirectPaymentReq wrapper = new DoDirectPaymentReq(); wrapper.DoDirectPaymentRequest = paypalRequest; // Create the PayPalAPIInterfaceServiceService service object to make the API call Dictionary <string, string> config = new Dictionary <string, string>(); // enforce 30000 minimum for timeout specification (30 secs) int timeout = 30000; timeout = Math.Max(timeout, Convert.ToInt32(gatewaySettings.Timeout ?? "0")); config.Add("account0.apiUsername", gatewaySettings.User); config.Add("account0.apiPassword", gatewaySettings.Password); config.Add("account0.apiSignature", gatewaySettings.Signature); config.Add("account0.applicationId", gatewaySettings.AppID); config.Add("connectionTimeout", timeout.ToString()); config.Add("mode", gatewaySettings.Mode); PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(config); // # API call // Invoke the DoDirectPayment method in service wrapper object DoDirectPaymentResponseType paypalResponse = service.DoDirectPayment(wrapper); // Check for API return status return(ParseResponse(service, paypalResponse)); }