Ejemplo n.º 1
0
def process_payment_request(amount, currency, token, payerid):
    """
    utility function to perform PayPal payment
    """
    #################
    # BEGIN ROUTINE #
    #################

    # call PayPal driver and perform the relevant PayPal API method to charge the money
    driver = PayPal()
    result = driver.DoExpressCheckoutPayment(currency=currency,
                                             amount=str(amount),
                                             token=token,
                                             payerid=payerid)

    # persist the response to the db with PayPalResponse instance
    paypal_response = PayPalResponse()
    paypal_response.fill_from_response(driver.GetPaymentResponse())
    paypal_response.status = PayPalResponse.get_default_status()

    if result == True:
        # Amount charged successfully.
        paypal_response.payment_received = True
        paypal_response.save()
        return True, paypal_response
    else:
        # Amount charged could not be charged successfully. Note that
        # the paypal_response is going to be saved.
        paypal_response.error = _(driver.doexpresscheckoutpaymenterror)
        paypal_response.save()
        return False, paypal_response
Ejemplo n.º 2
0
def process_refund_request(response, amount):
    """
    utility function to perform PayPal refund
    """
    #################
    # BEGIN ROUTINE #
    #################

    # call PayPal driver and perform the relevant PayPal API method to refund the money
    driver = PayPal()
    result = driver.RefundTransaction(response.trans_id,
                                      refundtype="Partial",
                                      amount=str(amount),
                                      currency=response.currencycode)

    # persist the response to the db with PayPalResponse instance
    paypal_response = PayPalResponse()
    paypal_response.fill_from_response(driver.GetRefundResponse(),
                                       action="Refund")
    paypal_response.status = PayPalResponse.get_cancel_status()

    if result == True:
        # Amount refunded successfully.
        paypal_response.payment_received = True
        paypal_response.save()
        return True, paypal_response
    else:
        # Amount charged could not be refunded successfully. Note that
        # the paypal_response is going to be saved
        paypal_response.error = _(driver.refundtransactionerror)
        paypal_response.save()
        return False, paypal_response
Ejemplo n.º 3
0
def deal_checkout_complete(request, slug, quantity):

  user_msg = ""
  quantity = int(quantity)

  try:
    deal = Deal.objects.get(slug=slug)
  except:
    return Http404()

  token = request.GET.get('token', None)
  payerid = request.GET.get('PayerID', None)

  if token and payerid:

    # TODO: i have no idea how many they bought!
    p = PayPal()
    rc = p.DoExpressCheckoutPayment("CAD", quantity * deal.deal_price, token, payerid, PAYMENTACTION="Authorization")

    if rc:  # payment is looking good

      response = PayPalResponse()
      response.fill_from_response(p.GetPaymentResponse())
      response.status = PayPalResponse.get_default_status()
      response.save()

      num_sold = deal.num_sold()

      # check if it's sold out!
      if num_sold > deal.max_available:
        pass
        #setup form error
        # Sold out!


      for i in range(quantity):
        coupon = Coupon()
        coupon.user = request.user
        coupon.deal = deal

        coupon.status = STATUS_ONHOLD

        coupon.save()
        num_sold = num_sold + 1

        # update the deal object 
        if not deal.is_deal_on and num_sold >= deal.tipping_point:
          deal.tipped_at = datetime.datetime.now()
          deal.is_deal_on = True
          deal.save()


      user_msg = 'Thanks for purchasing a Massive Coupon! It will arrive in your profile within 24 hours'
      return HttpResponseRedirect('/deals/nearby/?user_msg=' + user_msg )
    else:
      return Http404()

  else:
    return Http404()
Ejemplo n.º 4
0
def setcheckout(request,
                return_url,
                cancel_url,
                error_url,
                template="paypal/setcheckout.html",
                currency="USD"):
    """
    Django view to process PayPal SetExpressCheckout API call.
    If response 'Success' or 'SuccessWithWarning' comes, redirects user to the PayPal website to continue checkout process.
    If response 'Failed' or 'FailedWithWarning' comes, shows the error and redirects user to the 'payment page' to choose another POS or PayPal again.
    """

    #############################################################################
    # ROUTINES                                                                  #
    # 1) Perform and validate POST data                                         #
    # 2) Call Paypal driver                                                     #
    # 3) Execute the relevant method                                            #
    # 4) Accroding to the method response, redirect user to the given urls      #
    #############################################################################

    if request.POST:
        # normalize the given amount
        amount = request.POST.get("amount")
        try:
            amount = Decimal(amount)
            amount = str(amount.quantize(Decimal(".01"), rounding=ROUND_UP))
        except:
            if request.user.is_authenticated():
                request.user.message_set.create(message=_(
                    "No given valid amount. Please check the amount that will be charged."
                ))
            return HttpResponseRedirect(error_url)

        # call the PayPal driver (2)
        driver = PayPal()
        # call the relevant API method (3)
        result = driver.SetExpressCheckout(amount, currency, return_url,
                                           cancel_url)
        # perform the response (4)
        if not result:
            print driver.apierror
            # show the error message (comes from PayPal API) to the user and redirect him/her to the error page
            if request.user.is_authenticated():
                request.user.message_set.create(
                    message=_(driver.setexpresscheckouterror))
            return HttpResponseRedirect(error_url)

        # send him/her to the PayPal website to check his/her order details out
        redirect_url = driver.paypal_url()
        return HttpResponseRedirect(redirect_url)

    return render_to_response(template, {
        'currency': currency,
        'return_url': return_url,
        'cancel_url': cancel_url,
        'error_url': error_url,
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 5
0
def _checkout(deal, quantity):
    if settings.DEBUG:
        return {'error': False, 'redirect_url': reverse('deal-checkout-complete', args=(deal.slug, quantity))}
        
    # FIXME: I need to remove hardcodings
    total_price = quantity * deal.deal_price
    p = PayPal()
    rc = p.SetExpressCheckout(total_price, "CAD", "http://www.massivecoupon.com/deals/" + deal.slug + "/" + str(quantity) + "/checkout/complete/", "http://www.massivecoupon.com/", PAYMENTACTION="Authorization")
    if rc:
        token = p.api_response['TOKEN'][0]
        return {'error': False, 'redirect_url': p.paypal_url()}
    else:
        return {'error': True, 'redirect_url': reverse('deal-checkout-error')}
def setcheckout(request, return_url, cancel_url, error_url, template = "paypal/setcheckout.html", currency = "USD"):
    """
    Django view to process PayPal SetExpressCheckout API call.
    If response 'Success' or 'SuccessWithWarning' comes, redirects user to the PayPal website to continue checkout process.
    If response 'Failed' or 'FailedWithWarning' comes, shows the error and redirects user to the 'payment page' to choose another POS or PayPal again.
    """
    
    #############################################################################
    # ROUTINES                                                                  #
    # 1) Perform and validate POST data                                         #
    # 2) Call Paypal driver                                                     #
    # 3) Execute the relevant method                                            #
    # 4) Accroding to the method response, redirect user to the given urls      #
    #############################################################################

    if request.POST:
        # normalize the given amount
        amount = request.POST.get("amount")
        try:
            amount = Decimal(amount)
            amount = str(amount.quantize(Decimal(".01"), rounding = ROUND_UP))
        except:
            if request.user.is_authenticated():
                request.user.message_set.create(message = _("No given valid amount. Please check the amount that will be charged."))
            return HttpResponseRedirect(error_url)

        # call the PayPal driver (2)
        driver = PayPal()
        # call the relevant API method (3)
        result = driver.SetExpressCheckout(amount, currency, return_url, cancel_url)
        # perform the response (4)
        if not result:
            print driver.apierror
            # show the error message (comes from PayPal API) to the user and redirect him/her to the error page
            if request.user.is_authenticated():
                request.user.message_set.create(message = _(driver.setexpresscheckouterror))
            return HttpResponseRedirect(error_url)
        
        # send him/her to the PayPal website to check his/her order details out
        redirect_url = driver.paypal_url()
        return HttpResponseRedirect(redirect_url)
    
    return render_to_response(template,
                              {'currency': currency,
                               'return_url': return_url,
                               'cancel_url': cancel_url,
                               'error_url' : error_url,
                               }, context_instance = RequestContext(request))
Ejemplo n.º 7
0
def _paypal_checkout_complete(request, deal, quantity, token):
    result = {'error': True}
    token = request.GET.get('token', None)
    payerid = request.GET.get('PayerID', None)

    if token and payerid:
        # TODO: i have no idea how many they bought!
        p = PayPal()
        rc = p.DoExpressCheckoutPayment("CAD",
                                        quantity * deal.deal_price,
                                        token,
                                        payerid,
                                        PAYMENTACTION="Authorization")
        if rc:  # payment is looking good
            response = PayPalResponse()
            response.fill_from_response(p.GetPaymentResponse())
            response.status = PayPalResponse.get_default_status()
            response.save()
            result['error'] = False
        else:
            result['message'] = 'Empty payment'
    else:
        result['message'] = 'Token or payerid are empty.'
Ejemplo n.º 8
0
def _checkout(deal, quantity):
    if settings.DEBUG:
        return {
            'error':
            False,
            'redirect_url':
            reverse('deal-checkout-complete', args=(deal.slug, quantity))
        }

    # FIXME: I need to remove hardcodings
    total_price = quantity * deal.deal_price
    p = PayPal()
    rc = p.SetExpressCheckout(total_price,
                              "CAD",
                              "http://www.massivecoupon.com/deals/" +
                              deal.slug + "/" + str(quantity) +
                              "/checkout/complete/",
                              "http://www.massivecoupon.com/",
                              PAYMENTACTION="Authorization")
    if rc:
        token = p.api_response['TOKEN'][0]
        return {'error': False, 'redirect_url': p.paypal_url()}
    else:
        return {'error': True, 'redirect_url': reverse('deal-checkout-error')}
Ejemplo n.º 9
0
def deal_checkout(request, slug):

    user_msg = ""

    try:
        deal = Deal.objects.get(slug=slug)
    except:
        return HttpResponseRedirect('/')

    must_login_error = False
    must_login_email = None

    if request.method == 'POST':  # If the form has been submitted...
        form = DealCheckoutForm(request.POST)

        # before we do anything, check if this user has an account and isn't logged in
        if not request.user.is_authenticated():
            try:
                user = User.objects.get(email=request.POST['email'])
                must_login_error = True
                must_login_email = request.POST['email']
                form = DealCheckoutForm(initial={})
                user_msg = 'An account already exists for ' + user.email + '. Please sign in first.'
            except:
                pass

        else:
            user = request.user

        if not must_login_error and form.is_valid():
            cd = form.cleaned_data

            if not request.user.is_authenticated():
                # User in NOT Logged IN and doesn't exist
                # setup a new user
                user = User()
                user.username = cd.get('email')  #str(uuid.uuid4())[:30]
                user.first_name = cd.get('full_name')
                user.email = cd.get('email')
                user.save()
                user.set_password(cd.get('password'))
                user.save()

                user = authenticate(username=user.username,
                                    password=cd.get('password'))
                if user is not None:
                    if user.is_active:
                        login(request, user)
                        # Redirect to a success page.
                    else:
                        pass
                        # Return a 'disabled account' error message
                else:
                    # Return an 'invalid login' error message.
                    pass

            quantity = int(cd.get('quantity'))
            total_price = quantity * deal.deal_price

            p = PayPal()
            rc = p.SetExpressCheckout(total_price,
                                      "CAD",
                                      "http://www.massivecoupon.com/deals/" +
                                      deal.slug + "/" + str(quantity) +
                                      "/checkout/complete/",
                                      "http://www.massivecoupon.com/",
                                      PAYMENTACTION="Authorization")

            if rc:
                token = p.api_response['TOKEN'][0]
                return HttpResponseRedirect(p.paypal_url())
            else:
                return HttpResponseRedirect('/checkout/error')

    else:
        initial_data = {}
        form = DealCheckoutForm(initial=initial_data)

    cities = City.objects.all()

    return render_to_response('deal_checkout.html', {
        'form': form,
        'deal': deal,
        'user_msg': user_msg,
        'must_login_error': must_login_error,
        'must_login_email': must_login_email,
        'cities': cities,
    },
                              context_instance=RequestContext(request))
def deal_checkout(request, slug):

  user_msg = ""

  try:
    deal = Deal.objects.get(slug=slug)
  except:
    return HttpResponseRedirect('/')
 

  must_login_error = False
  must_login_email = None

  if request.method == 'POST': # If the form has been submitted...
    form = DealCheckoutForm(request.POST)

    # before we do anything, check if this user has an account and isn't logged in
    if not request.user.is_authenticated():
      try:
        user = User.objects.get(email=request.POST['email'])
        must_login_error = True
        must_login_email = request.POST['email']
        form = DealCheckoutForm(initial={})
        user_msg = 'An account already exists for ' + user.email  + '. Please sign in first.'
      except:
        pass

    else:
      user = request.user

    if not must_login_error and form.is_valid():
      cd = form.cleaned_data

      if not request.user.is_authenticated():
        # User in NOT Logged IN and doesn't exist
        # setup a new user
        user = User()
        user.username = cd.get('email')  #str(uuid.uuid4())[:30]
        user.first_name = cd.get('full_name')
        user.email = cd.get('email')
        user.save()
        user.set_password( cd.get('password') )
        user.save()


        user = authenticate(username=user.username, password=cd.get('password'))
        if user is not None:
          if user.is_active:
            login(request, user)
            # Redirect to a success page.
          else:
            pass
            # Return a 'disabled account' error message
        else:
          # Return an 'invalid login' error message.
          pass

      quantity = int(cd.get('quantity'))
      total_price = quantity * deal.deal_price

      p = PayPal()
      rc = p.SetExpressCheckout(total_price, "CAD", "http://www.massivecoupon.com/deals/" + deal.slug + "/" + str(quantity) + "/checkout/complete/", "http://www.massivecoupon.com/", PAYMENTACTION="Authorization")

      if rc:
        token = p.api_response['TOKEN'][0]
        return HttpResponseRedirect( p.paypal_url() )
      else:
        return HttpResponseRedirect('/checkout/error') 
 



  else:
    initial_data = {}
    form = DealCheckoutForm(initial=initial_data)

  cities = City.objects.all()

  return render_to_response('deal_checkout.html', {
                'form' : form,
                'deal' : deal,
                'user_msg' : user_msg,
                'must_login_error' : must_login_error,
                'must_login_email' : must_login_email,
                'cities' : cities,
              }, context_instance=RequestContext( request ) )