Hire Me

Implementing a PayPal Payment Button with ASP.NET WebForms

How to add a hosted PayPal button to an ASP.NET WebForms page

Posted on Tuesday, December 15, 2015 at 7:33 PM into paypal csharp code webforms by Steve Woods

One of the biggest problems with ASP.NET WebForms development is the fact that every single page is wrapped in a form tag for the postback functionality, and you can't nest forms within other forms.

This causes issues when integrating features like PayPal buttons which are normally placed on the page as a simple form template, with the parameters specified as hidden input fields.

I recently worked on a project for a colleague who's client needed a nice form to be submitted to PayPal so that a gift certificate could be dispatched, and was tasked with making this work in ASP.NET WebForms.

Because I couldn't place another form on the page (such as the ones that they recommend on the PayPal developer website) I had to construct a URL based on the WebForms form, and then redirect to the PayPal server once the postback has been initialised.

Here's the code for a hosted button

protected void SendButton_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        StringBuilder ppHref = new StringBuilder();

        ppHref.Append("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick");
        ppHref.Append("&hosted_button_id=[HOSTED BUTTON ID]);
        ppHref.Append("&on0=Voucher Amount");
        ppHref.Append("&os0=[PRE-DEFINED OPTION]");
        ppHref.Append("&on1=Name to send voucher");
        ppHref.Append("&os1=[RECIPIENT NAME]");
        ppHref.Append("&on2=Email to send voucher");
        ppHref.Append("&os2=[RECIPIENT EMAIL]");
        ppHref.Append("&on3=Personal Message");
        ppHref.Append("&os3=[YOUR MESSAGE HERE]");
        ppHref.Append("¤cy_code=GBP");

        Response.Redirect(ppHref.ToString(), true); 
        } 
}

Worked a treat :)

;

Comments

Please consider what you post!
Chillax if you're angry.