Search code examples
pythonhttp-redirectpython-3.xpaypalpaypal-rest-sdk

How to redirect user to a returned URL python


So im testing out the paypal rest sdk and im using python as my cgi language(i know its so too 2007), anyway i've hit a roadblock,in that I cant get it to redirect to the returned URL page.

I already tried the print Location method. And it did not work for me.

# Create Payment Using PayPal Sample
# This sample code demonstrates how you can process a
# PayPal Account based Payment.
# API used: /v1/payments/payment
from paypalrestsdk import Payment
import logging

logging.basicConfig(level=logging.INFO)

# Payment
# A Payment Resource; create one using
# the above types and intent as 'sale'
payment = Payment({
"intent": "sale",

# Payer
# A resource representing a Payer that funds a payment
# Payment Method as 'paypal'
"payer": {
    "payment_method": "paypal"},

# Redirect URLs
"redirect_urls": {
    "return_url": "http://localhost:3000/payment/execute",
    "cancel_url": "http://localhost:3000/"},

# Transaction
# A transaction defines the contract of a
# payment - what is the payment for and who
# is fulfilling it.
"transactions": [{

    # ItemList
    "item_list": {
        "items": [{
            "name": "item",
            "sku": "item",
            "price": "5.00",
            "currency": "USD",
            "quantity": 1}]},

    # Amount
    # Let's you specify a payment amount.
    "amount": {
        "total": "5.00",
        "currency": "USD"},
    "description": "This is the payment transaction description."}]})

 # Create Payment and return status
 if payment.create():
 print("Payment[%s] created successfully" % (payment.id))
  # Redirect the user to given approval url
for link in payment.links:
    if link.method == "REDIRECT":
        # Convert to str to avoid google appengine unicode issue
        # https://github.com/paypal/rest-api-sdk-python/pull/58
        redirect_url = str(link.href)
        print("Redirect for approval: %s" % (redirect_url))
else:
    print("Error while creating payment:")
    print(payment.error)

So it would really help me out if you guys new of anyway to throw a 301 or 302 on the users browser. Thank you.


Solution

  • I kinda solved it on my own. By add this to the code

    print 'Content-Type: text/html'
    print 'Location: %s' % redirectURL
    print # HTTP says you have to have a blank line between headers and content
    print '<html>'
    print '  <head>'
    print '    <meta http-equiv="refresh" content="0;url=%s" />' %redirectURL
    print '    <title>You are going to be redirected</title>'
    print '  </head>' 
    print '  <body>'
    print '    Redirecting... <a href="%s">Click here if you are not redirected</a>' % redirectURL
    print '  </body>'
    print '</html>'
    

    Know the script redirects the page like a charm.Thank you