Click here to Skip to main content
12,629,569 members (29,509 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# ASP.NET PayPal
I have used Credit Card as tender for Recurring Billing.
This code running fine.
But Now I want to use PaypalExpress Checkout and create recurring profile.
string msg = "";
            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo(
                ConfigurationManager.AppSettings["USER"],
                ConfigurationManager.AppSettings["VENDOR"],
                "PayPal", ConfigurationManager.AppSettings["PWD"]
                );
            // Create the Payflow  Connection data object with the required connection details.
            // The PAYFLOW_HOST property is defined in the App config file.
            PayflowConnectionData Connection = new PayflowConnectionData();
            // Create a new Invoice data object with the Amount, Billing Address etc. details.
            Invoice Inv = new Invoice();
            // Set Amount.
            Currency Amt = new Currency(new decimal(1), "USD");
            Inv.Amt = Amt;
            Inv.InvNum = "INV" + WooskieLibrary.Business.ConvertUtil.generateInvoiceNo();
            Inv.CustRef = Luser.Person.EMAIL_ADDRESS;
            Inv.Comment1 = "Order Number: " + Inv.InvNum;
            Inv.Comment2 = "Customer Email: " + Luser.Person.EMAIL_ADDRESS;
            // Set the Billing Address details.
            // Only Street and Zip are set below for AVS check; however, you would probably want
            // to include full name and address information.
            BillTo Bill = new BillTo();
            Bill.BillToStreet = Luser.Person.PERSON_ADDRESS.ADDRESS1 + ',' + Luser.Person.PERSON_ADDRESS.ADDRESS2;
            Bill.BillToZip = Luser.Person.PERSON_ADDRESS.ZIPCODE;
            Bill.BillToCountry = Luser.Person.PERSON_ADDRESS.COUNTRY;
            // Set the BillTo object into invoice.
            Inv.BillTo = Bill;
            // ECHODATA allows you to trigger data sent in the request to be returned in the request.
            // 'ADDRESS' will return both shipping and billing address data, if sent.
            //Inv.EchoData = "ADDRESS";

            // Shipping details may not be necessary if providing a
            // service or downloadable product such as software etc.
            //
            // Set the Shipping Address details.
            // The shipping details are for reporting purposes only.
            // It is suggested that you pass all the shipping details for enhanced reporting.
            //
            // Create the ShipTo object.
            //ShipTo Ship = new ShipTo();

            // To prevent an 'Address Mismatch' fraud trigger, we are shipping to the billing address.  However,
            // shipping parameters are listed.
            // Comment line below if you want a separate Ship To address.
            //Ship = Bill.Copy();

            //Inv.ShipTo = Ship;
            // ***  Create Customer Data ***
            // There are additional CustomerInfo parameters that are used for Level 2 Purchase Cards.
            // Refer to the Payflow Pro Developer’s Guide and consult with your Internet
            // Merchant Bank regarding what parameters to send.
            // Some of the parameters could include:
            //
            CustomerInfo CustInfo = new CustomerInfo();
            CustInfo.CustCode = Luser.USERNAME;    // Customer Code
            CustInfo.CustId = "CustId" + Luser.USERID;
            Inv.CustomerInfo = CustInfo;
            // Create a new Payment Device - Credit Card data object.
            // The input parameters are Credit Card Number and Expiration Date of the Credit Card.

            CreditCard CC = new CreditCard(Luser.Person.CLIENT_BILLING_INFO.CARD_NO, Luser.Person.CLIENT_BILLING_INFO.EXPIRED);
            // CVV2 is used for Optional Transaction (Sale or Authorization) Only.  It is not stored as
            // part of the profile, nor is it sent when payments are made.
            CC.Cvv2 = GetString(Luser.Person.CLIENT_BILLING_INFO.CVV2.ToArray());
            // Create a new Tender - Card Tender data object.
            CardTender Card = new CardTender(CC);
 
            RecurringInfo RecurInfo = new RecurringInfo();
            // The date that the first payment will be processed.
            // This will be of the format mmddyyyy.
            var now = DateTime.Now;
            RecurInfo.Start = string.Format("{0:MMddyyyy}", now);
            RecurInfo.ProfileName = "Requring_Profile@" + Luser.USERNAME; // User provided Profile Name.
            RecurInfo.RetryNumDays = 3;
            // Specifies how often the payment occurs. All PAYPERIOD values must use
            // capital letters and can be any of WEEK / BIWK / SMMO / FRWK / MONT /
            // QTER / SMYR / YEAR
            RecurInfo.PayPeriod = "MONT";
            RecurInfo.Term = 12; // Number of payments

            // Peform an Optional Transaction.
            RecurInfo.OptionalTrx = "S";  // S = Sale, A = Authorization
            // Set the amount if doing a "Sale" for the Optional Transaction.
            Currency oTrxAmt = new Currency(new decimal(1), "USD");
            RecurInfo.OptionalTrxAmt = oTrxAmt;
            // Create a new Recurring Add Transaction.
            RecurringAddTransaction Trans = new RecurringAddTransaction(
             User, Connection, Inv, Card, RecurInfo, PayflowUtility.RequestId);
            // Use ORIGID to create a profile based on the details of another transaction. See Reference Transaction.
            //Trans.OrigId = "<ORIGINAL_PNREF>";
            // Submit the Transaction
            Response Resp = Trans.SubmitTransaction();
            // Display the transaction response parameters.
            if (Resp != null)
            {
                // Get the Transaction Response parameters.
                TransactionResponse TrxnResponse = Resp.TransactionResponse;
                if (TrxnResponse != null)
                {
                    msg += string.Format("RESULT = " + TrxnResponse.Result);
                    msg += Environment.NewLine;
                    msg += string.Format("RESPMSG = " + TrxnResponse.RespMsg);
                    // Get the Recurring Response parameters.
                    RecurringResponse RecurResponse = Resp.RecurringResponse;
                    if (RecurResponse != null)
                    {
                        String ProfileMsg;
                        if (TrxnResponse.Result == 0)
                        {
                            ProfileMsg = "Profile Created.";
                            var recurringBillProfile = new RECURRING_BILL_PROFILE
                            {
                                ProfileId = RecurResponse.ProfileId,
                                PersonId = Luser.USERID,
                                Message = ProfileMsg,
                                Reference = RecurResponse.RPRef,
                                PROFILENAME = RecurResponse.ProfileName
                            };
                            using (var db = new WooskieDBInstance().WooskieDB)
                            {
 
                                var user = db.LOGIN_USERs.FirstOrDefault(u => u == Luser);
                                user.STATUS = 1;
                                user.Person.ISACTIVE = true;
                                db.RECURRING_BILL_PROFILEs.InsertOnSubmit(recurringBillProfile);
                                db.SubmitChanges();
                            }
                        }
                        else
                        {
                            ProfileMsg = "Error, Profile Not Created.";
                        }
                        msg += "<br/>";
                        msg += string.Format("------------------------------------------------------");
                        msg += "<br/>";
                        msg += string.Format(("Profile Status: " + ProfileMsg));
                        msg += "<br/>";
                        msg += string.Format("Recurring Profile Reference (RPREF) = " + RecurResponse.RPRef);
                        msg += "<br/>";
                        msg += string.Format("Recurring Profile ID (PROFILEID) = " + RecurResponse.ProfileId);
                        msg += "<br/>";
                        // Was an Optional Transaction processed?
                        if (RecurResponse.TrxResult != null)
                        {
 
                            msg += string.Format("------------------------------------------------------");
                            msg += "<br/>";
                            msg += string.Format("Optional Transaction Details:");
                            msg += "<br/>";
                            msg += string.Format("Transaction PNREF (TRXPNREF) = " + RecurResponse.TrxPNRef);
                            msg += "<br/>";
                            msg += string.Format("Transaction Result (TRXRESULT) = " + RecurResponse.TrxResult);
                            msg += "<br/>";
                            msg += string.Format("Transaction Message (TRXRESPMSG) = " + RecurResponse.TrxRespMsg);
                            msg += "<br/>";
                            msg += string.Format(("Authorization (AUTHCODE) = " + TrxnResponse.AuthCode));
                            msg += "<br/>";
                            msg += string.Format(("Security Code Match (CVV2MATCH) = " + TrxnResponse.CVV2Match));
                            msg += "<br/>";
                            msg += string.Format(("Street Address Match (AVSADDR) = " + TrxnResponse.AVSAddr));
                            msg += "<br/>";
                            msg += string.Format(("Streep Zip Match (AVSZIP) = " + TrxnResponse.AVSZip));
                            msg += "<br/>";
                            msg += string.Format(("International Card (IAVS) = " + TrxnResponse.IAVS));
                            msg += "<br/>";
                            // Was this a duplicate transaction?
                            // If this value is true, you will probably receive a result code 19, Original transaction ID not found.
                            msg += string.Format("------------------------------------------------------");
                            msg += "<br/>";
                            msg += string.Format("Duplicate Response:");
                            msg += "<br/>";
                            String DupMsg;
                            if (TrxnResponse.Duplicate == "1")
                            {
                                DupMsg = "Duplicate Transaction";
                            }
                            else
                            {
                                DupMsg = "Not a Duplicate Transaction";
                            }
                            msg += string.Format("Duplicate Transaction (DUPLICATE) = " + DupMsg);
                            msg += "<br/>";
                        }
                    }
                    // Display the response.
                    msg += string.Format(Environment.NewLine + PayflowUtility.GetStatus(Resp));
                    // Get the Transaction Context and check for any contained SDK specific errors (optional code).
                    Context TransCtx = Resp.TransactionContext;
                    if (TransCtx != null && TransCtx.getErrorCount() > 0)
                    {
                        msg += string.Format(Environment.NewLine + "Transaction Errors = " + TransCtx.ToString());
                    }
                }
 
            }
            return msg;


What will be the change here?
Posted 10-Jan-13 7:33am

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString.Count != 0)
            {
                if (Request.QueryString["token"] != null)
                {
                    if (Request.QueryString["token"] == "")
                    {
                        lMsg.Text = "Transction has been canceled";
                    }
                    else  lMsg.Text= RecuringPayments();
                }
                else
                {
                    ExpressCheckOut();
                }
            }
        }
        #region Paypal Express Checkout And Create Recuring Profile
        public void ExpressCheckOut()
        {
 
            NameValueCollection formdata = Request.QueryString ;
            LOGIN_USER user = null;
            CreateUser(formdata, ref user, "P");
            PayPalTenderRecuring(user);
            //Session["Luser"] = user;
        }
        private static void CreateUser(NameValueCollection formdata, ref LOGIN_USER user, string Tender)
        {
            using (var db = new WooskieDBInstance().WooskieDB)
            {
                try
                {
                    db.Connection.Open();
                    db.Transaction = db.Connection.BeginTransaction();
                    user = new LOGIN_USER();
                    user.USERNAME = formdata.Get(8);
                    user.STATUS = 0;
                    user.CreateDate = DateTime.UtcNow;
                    user.PASS = WooskieLibrary.Business.ConvertUtil.generatePassword(6);
                    user.Person = new Wooskie.Business.Person
                    {
                        EMAIL_ADDRESS = formdata.Get(7),
                        FIRSTNAME = formdata.Get(0),
                        LASTNAME = formdata.Get(1),
                        PERSONTYPEID = 2,
                        COMPANY_NAME = formdata.Get(0) + ' ' + formdata.Get(1),
                        ISACTIVE = false,
                        PERSON_ADDRESS = new PERSON_ADDRESS
                        {
                            ADDRESS1 = formdata[2],
                            ADDRESS2 = formdata[3],
                            CITY = formdata[4],
                            COUNTRY = formdata[9],
                            STATE = formdata[5],
                            ZIPCODE = formdata["ctl00$MainContent$txtZipcode"],
 

                        },
                        CLIENT_BILLING_INFO = new CLIENT_BILLING_INFO
                        {
                            BILLING_EMAIL = formdata[17],
                            PAYMENT_TYPE = Tender.Equals("P") ? 2 : Convert.ToInt32(formdata[11]),
                            CARD_NO = formdata[13],
                            CVV2 = GetBytes(formdata["ctl00$MainContent$txtCVV"]),
                            EXPIRED = formdata["ctl00$MainContent$ddlExpMonth"] + formdata["ctl00$MainContent$ddlExpYear"].Substring(2, 2)
                        }
                    };
                    db.LOGIN_USERs.InsertOnSubmit(user);
                    db.SubmitChanges();
                    //Commit Transaction
                    db.Transaction.Commit();
 

                }
                catch
                {
                    //Roleback Transaction
                    db.Transaction.Rollback();
                }
            }
        }
        private void PayPalTenderRecuring(LOGIN_USER Luser)
        {
 
            // Create the Data Objects.
            // Create the User data object with the required user details.
            UserInfo User = new UserInfo(
                ConfigurationManager.AppSettings["USER"],
                ConfigurationManager.AppSettings["VENDOR"],
                "PayPal", ConfigurationManager.AppSettings["PWD"]
                );
            // Create the Payflow  Connection data object with the required connection details.
            // The PAYFLOW_HOST property is defined in the App config file.
            PayflowConnectionData Connection = new PayflowConnectionData();
            // Create a new Invoice data object with the Amount, Billing Address etc. details.
            Invoice Inv = new Invoice();
            // Set Amount.
            Currency Amt = new Currency(new decimal(1), "USD");
            Inv.Amt = Amt;
            Inv.InvNum = "INV" + WooskieLibrary.Business.ConvertUtil.generateInvoiceNo();
            Inv.CustRef = Luser.Person.EMAIL_ADDRESS;
            Inv.Comment1 = "Order Number: " + Inv.InvNum;
            Inv.Comment2 = "Customer Email: " + Luser.Person.EMAIL_ADDRESS;
            // Set the Billing Address details.
            // Only Street and Zip are set below for AVS check; however, you would probably want
            // to include full name and address information.
            BillTo Bill = new BillTo();
            Bill.BillToStreet = Luser.Person.PERSON_ADDRESS.ADDRESS1 + ',' + Luser.Person.PERSON_ADDRESS.ADDRESS2;
            Bill.BillToZip = Luser.Person.PERSON_ADDRESS.ZIPCODE;
            Bill.BillToCountry = Luser.Person.PERSON_ADDRESS.COUNTRY;
            // Set the BillTo object into invoice.
            Inv.BillTo = Bill;
 
            CustomerInfo CustInfo = new CustomerInfo();
            CustInfo.CustCode = "TEST";    // Customer Code
            CustInfo.CustId = "CustId";
            Inv.CustomerInfo = CustInfo;
 
            string msg = "";
 
            ExpressCheckoutRequest currRequest = new ECSetRequest("http://localhost:9275/PaypalCheckout", "http://localhost:9275/PaypalCheckout");
            PayPalTender currTender = new PayPalTender(currRequest);
            SaleTransaction currTransaction = new SaleTransaction(User, Connection, Inv, currTender, PayflowUtility.RequestId);
            Response Resp = currTransaction.SubmitTransaction();
            if (Resp != null)
            {
                TransactionResponse TrxnResponse = Resp.TransactionResponse;
                ExpressCheckoutResponse eResponse = Resp.ExpressCheckoutSetResponse;
                if ((TrxnResponse != null) && (eResponse != null))
                {
                    if (TrxnResponse.Result == 0)
                    {
                        HttpContext.Current.Session["PaypalToken"] = eResponse.Token;
                        HttpContext.Current.Session["Luser"] = Luser;
                        HttpContext.Current.Response.Redirect("https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + eResponse.Token);
                        msg = String.Empty;
                    }
                    else
                        msg = TrxnResponse.RespMsg;
                }
                else
                    msg = Resp.ResponseString;
            }
            msg = "transaction error";
 

        }
        string RecuringPayments()
        {
            string PayerID = Request.QueryString["PayerID"];
            LOGIN_USER Luser = (LOGIN_USER)HttpContext.Current.Session["Luser"];
            UserInfo User = new UserInfo(
                 ConfigurationManager.AppSettings["USER"],
                 ConfigurationManager.AppSettings["VENDOR"],
                 "PayPal", ConfigurationManager.AppSettings["PWD"]
                 );
            // Create the Payflow  Connection data object with the required connection details.
            // The PAYFLOW_HOST property is defined in the App config file.
            PayflowConnectionData Connection = new PayflowConnectionData();
            // Create a new Invoice data object with the Amount, Billing Address etc. details.
            Invoice Inv = new Invoice();
            // Set Amount.
            Currency Amt = new Currency(new decimal(1), "USD");
            Inv.Amt = Amt;
            Inv.InvNum = "INV" + WooskieLibrary.Business.ConvertUtil.generateInvoiceNo();
            Inv.CustRef = Luser.Person.EMAIL_ADDRESS;
            Inv.Comment1 = "Order Number: " + Inv.InvNum;
            Inv.Comment2 = "Customer Email: " + Luser.Person.EMAIL_ADDRESS;
            // Set the Billing Address details.
            // Only Street and Zip are set below for AVS check; however, you would probably want
            // to include full name and address information.
            BillTo Bill = new BillTo();
            Bill.BillToStreet = Luser.Person.PERSON_ADDRESS.ADDRESS1 + ',' + Luser.Person.PERSON_ADDRESS.ADDRESS2;
            Bill.BillToZip = Luser.Person.PERSON_ADDRESS.ZIPCODE;
            Bill.BillToCountry = Luser.Person.PERSON_ADDRESS.COUNTRY;
            // Set the BillTo object into invoice.
            Inv.BillTo = Bill;
 
            CustomerInfo CustInfo = new CustomerInfo();
            CustInfo.CustCode = Luser.USERNAME;    // Customer Code
            CustInfo.CustId = "CustId" + Luser.USERID;
            Inv.CustomerInfo = CustInfo;
           
            ExpressCheckoutRequest currRequest = new ECDoRequest(HttpContext.Current.Session["PaypalToken"].ToString(),PayerID);
            PayPalTender currTender = new PayPalTender(currRequest);
 
            SaleTransaction currTransaction = new SaleTransaction(User, Connection, Inv, currTender, PayflowUtility.RequestId);
            Response Resp = currTransaction.SubmitTransaction();
            if (Resp != null)
            {
                TransactionResponse TrxnResponse = Resp.TransactionResponse;
                ECDoResponse eResponse = Resp.ExpressCheckoutDoResponse;
                if ((TrxnResponse != null) && (eResponse != null))
                {
                    if (TrxnResponse.Result == 0)
                    {
                        
                        RecurringInfo RecurInfo = new RecurringInfo();
                        RecurInfo.Start = DateTime.Now.ToString("MMddyyyy");
                        RecurInfo.ProfileName = "Requring_Profile@" + Luser.USERNAME; // User provided Profile Name.
                        RecurInfo.PayPeriod = "MONT";
                        RecurInfo.Term = 12;
                       
                        RecurringAddTransaction RecurringTrans = new RecurringAddTransaction(User, Connection, Inv, currTender, RecurInfo, PayflowUtility.RequestId);
                        RecurringTrans.OrigId = eResponse.BAId;
                        Response RecurringResp = RecurringTrans.SubmitTransaction();
                        if (RecurringResp != null)
                        {
                            TrxnResponse = RecurringResp.TransactionResponse;
                            RecurringResponse RecurResponse = RecurringResp.RecurringResponse;
                            if ((TrxnResponse != null) && (RecurResponse != null))
                            {
                                if (TrxnResponse.Result == 0)
                                {
                                    //CompaniesManager.setProfileID(currCompany.companyID, RecurResponse.ProfileId);
                                    //CompaniesManager.updateAccountExpireDate(currCompany.companyID, startBilling);
                                    SendMailToClient(Luser.Person.EMAIL_ADDRESS);
                                    return String.Empty;
                                }
                                else
                                {
                                    return TrxnResponse.Result + " " + TrxnResponse.RespMsg + RecurResponse.TrxRespMsg;
                                }
                            }
                            else
                                return Resp.ResponseString;
                        }
                        return "transaction error";
                    }
                    else
                        return TrxnResponse.RespMsg;
                }
                else
                    return Resp.ResponseString;
            }
            return "transaction error";
        }
 
        private void SendMailToClient(string p)
        {
            SmtpClient client = new SmtpClient("184.173.9.173");
            client.Credentials = new System.Net.NetworkCredential("user", "password");
            MailAddress mailFrom = new MailAddress("mymail@server.com");
            MailAddress mailTo = new MailAddress("yourmail@server.com");
            MailAddress mailReply = new MailAddress("mymail@server.com");
            MailMessage message = new MailMessage(mailFrom, mailTo);
            message.Body = "This is a test message.";
            message.Subject = "test message";
            message.SubjectEncoding = System.Text.Encoding.UTF8;
            message.BodyEncoding = System.Text.Encoding.UTF8;
            client.Send(message);
        }
 
        static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }
        static string GetString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }
        #endregion
    }
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.161205.3 | Last Updated 11 Jan 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100