Example #1
0
def oauth_return(request, *args, **kwargs):
    if 'payment_paypal_oauth_event' not in request.session:
        messages.error(request, _('An error occurred during connecting with PayPal, please try again.'))
        return redirect(reverse('control:index'))

    event = get_object_or_404(Event, pk=request.session['payment_paypal_oauth_event'])

    prov = Paypal(event)
    prov.init_api()

    try:
        tokeninfo = Tokeninfo.create(request.GET.get('code'))
        userinfo = Tokeninfo.create_with_refresh_token(tokeninfo['refresh_token']).userinfo()
    except:
        logger.exception('Failed to obtain OAuth token')
        messages.error(request, _('An error occurred during connecting with PayPal, please try again.'))
    else:
        messages.success(request,
                         _('Your PayPal account is now connected to pretix. You can change the settings in '
                           'detail below.'))

        event.settings.payment_paypal_connect_refresh_token = tokeninfo['refresh_token']
        event.settings.payment_paypal_connect_user_id = userinfo.email

    return redirect(reverse('control:event.settings.payment.provider', kwargs={
        'organizer': event.organizer.slug,
        'event': event.slug,
        'provider': 'paypal'
    }))
Example #2
0
    def checkout_prepare(self, request, cart):
        self.init_api()
        kwargs = {}
        if request.resolver_match and 'cart_namespace' in request.resolver_match.kwargs:
            kwargs['cart_namespace'] = request.resolver_match.kwargs[
                'cart_namespace']

        if request.event.settings.payment_paypal_connect_user_id:
            userinfo = Tokeninfo.create_with_refresh_token(
                request.event.settings.payment_paypal_connect_refresh_token
            ).userinfo()
            request.event.settings.payment_paypal_connect_user_id = userinfo.email
            payee = {
                "email": request.event.settings.payment_paypal_connect_user_id,
                # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                # we should use it instead of the merchant's eMail-address
                # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
            }
        else:
            payee = {}

        payment = paypalrestsdk.Payment({
            'intent':
            'sale',
            'payer': {
                "payment_method": "paypal",
            },
            "redirect_urls": {
                "return_url":
                build_absolute_uri(request.event,
                                   'plugins:paypal:return',
                                   kwargs=kwargs),
                "cancel_url":
                build_absolute_uri(request.event,
                                   'plugins:paypal:abort',
                                   kwargs=kwargs),
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name": __('Order for %s') % str(request.event),
                        "quantity": 1,
                        "price": self.format_price(cart['total']),
                        "currency": request.event.currency
                    }]
                },
                "amount": {
                    "currency": request.event.currency,
                    "total": self.format_price(cart['total'])
                },
                "description":
                __('Event tickets for {event}').format(
                    event=request.event.name),
                "payee":
                payee
            }]
        })
        request.session['payment_paypal_order'] = None
        return self._create_payment(request, payment)
Example #3
0
 def test_userinfo(self):
     Base.post.side_effect = paypal.UnauthorizedAccess('', '')
     self.assertRaises(paypal.UnauthorizedAccess, Tokeninfo().userinfo, {})
     Base.post.assert_called_once_with('v1/identity/openidconnect/userinfo',
                                       {
                                           'access_token': None,
                                           'schema': 'openid'
                                       })
Example #4
0
    def payment_prepare(self, request, payment_obj):
        self.init_api()

        if request.event.settings.payment_paypal_connect_user_id:
            userinfo = Tokeninfo.create_with_refresh_token(
                request.event.settings.payment_paypal_connect_refresh_token
            ).userinfo()
            request.event.settings.payment_paypal_connect_user_id = userinfo.email
            payee = {
                "email": request.event.settings.payment_paypal_connect_user_id,
                # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                # we should use it instead of the merchant's eMail-address
                # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
            }
        else:
            payee = {}

        payment = paypalrestsdk.Payment({
            'intent':
            'sale',
            'payer': {
                "payment_method": "paypal",
            },
            "redirect_urls": {
                "return_url":
                build_absolute_uri(request.event, 'plugins:paypal:return'),
                "cancel_url":
                build_absolute_uri(request.event, 'plugins:paypal:abort'),
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name":
                        __('Order {slug}-{code}').format(
                            slug=self.event.slug.upper(),
                            code=payment_obj.order.code),
                        "quantity":
                        1,
                        "price":
                        self.format_price(payment_obj.amount),
                        "currency":
                        payment_obj.order.event.currency
                    }]
                },
                "amount": {
                    "currency": request.event.currency,
                    "total": self.format_price(payment_obj.amount)
                },
                "description":
                __('Order {order} for {event}').format(
                    event=request.event.name, order=payment_obj.order.code),
                "payee":
                payee
            }]
        })
        request.session['payment_paypal_order'] = payment_obj.order.pk
        request.session['payment_paypal_payment'] = payment_obj.pk
        return self._create_payment(request, payment)
Example #5
0
 def test_refresh(self):
     Base.post.side_effect = paypal.ResourceNotFound('', '')
     self.assertRaises(paypal.ResourceNotFound, Tokeninfo().refresh, {})
     Base.post.assert_called_once_with(
         'v1/identity/openidconnect/tokenservice', {
             'client_secret': client_secret,
             'grant_type': 'refresh_token',
             'refresh_token': None,
             'client_id': client_id
         })
Example #6
0
    def payment_prepare(self, request, payment_obj):
        self.init_api()

        if request.event.settings.payment_paypal_connect_user_id:
            userinfo = Tokeninfo.create_with_refresh_token(request.event.settings.payment_paypal_connect_refresh_token).userinfo()
            request.event.settings.payment_paypal_connect_user_id = userinfo.email
            payee = {
                "email": request.event.settings.payment_paypal_connect_user_id,
                # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                # we should use it instead of the merchant's eMail-address
                # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
            }
        else:
            payee = {}

        payment = paypalrestsdk.Payment({
            'intent': 'sale',
            'payer': {
                "payment_method": "paypal",
            },
            "redirect_urls": {
                "return_url": build_absolute_uri(request.event, 'plugins:paypal:return'),
                "cancel_url": build_absolute_uri(request.event, 'plugins:paypal:abort'),
            },
            "transactions": [
                {
                    "item_list": {
                        "items": [
                            {
                                "name": __('Order {slug}-{code}').format(slug=self.event.slug.upper(),
                                                                         code=payment_obj.order.code),
                                "quantity": 1,
                                "price": self.format_price(payment_obj.amount),
                                "currency": payment_obj.order.event.currency
                            }
                        ]
                    },
                    "amount": {
                        "currency": request.event.currency,
                        "total": self.format_price(payment_obj.amount)
                    },
                    "description": __('Order {order} for {event}').format(
                        event=request.event.name,
                        order=payment_obj.order.code
                    ),
                    "payee": payee
                }
            ]
        })
        request.session['payment_paypal_order'] = payment_obj.order.pk
        request.session['payment_paypal_payment'] = payment_obj.pk
        return self._create_payment(request, payment)
Example #7
0
def login_via_paypal():
    try:
        options = configure_openid_request()

        login_url = Tokeninfo.authorize_url(options=options)
    except (ConnectionError, MissingParam, MissingConfig) as e:
        app.logger.exception(e)
        return internal_server_error()
    except Exception as e:
        app.logger.exception(e)
        return internal_server_error()

    #redirect to login page for approval
    return redirect(login_url)
Example #8
0
    def checkout_prepare(self, request, cart):
        self.init_api()
        kwargs = {}
        if request.resolver_match and 'cart_namespace' in request.resolver_match.kwargs:
            kwargs['cart_namespace'] = request.resolver_match.kwargs['cart_namespace']

        if request.event.settings.payment_paypal_connect_user_id:
            userinfo = Tokeninfo.create_with_refresh_token(request.event.settings.payment_paypal_connect_refresh_token).userinfo()
            request.event.settings.payment_paypal_connect_user_id = userinfo.email
            payee = {
                "email": request.event.settings.payment_paypal_connect_user_id,
                # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                # we should use it instead of the merchant's eMail-address
                # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
            }
        else:
            payee = {}

        payment = paypalrestsdk.Payment({
            'intent': 'sale',
            'payer': {
                "payment_method": "paypal",
            },
            "redirect_urls": {
                "return_url": build_absolute_uri(request.event, 'plugins:paypal:return', kwargs=kwargs),
                "cancel_url": build_absolute_uri(request.event, 'plugins:paypal:abort', kwargs=kwargs),
            },
            "transactions": [
                {
                    "item_list": {
                        "items": [
                            {
                                "name": __('Order for %s') % str(request.event),
                                "quantity": 1,
                                "price": self.format_price(cart['total']),
                                "currency": request.event.currency
                            }
                        ]
                    },
                    "amount": {
                        "currency": request.event.currency,
                        "total": self.format_price(cart['total'])
                    },
                    "description": __('Event tickets for {event}').format(event=request.event.name),
                    "payee": payee
                }
            ]
        })
        request.session['payment_paypal_order'] = None
        return self._create_payment(request, payment)
Example #9
0
def login(request):

    #     return render(request, 'paypal/google_validation.html', {})

    print('Starting point')

    if 'logout_url' not in request.session:
        # Generate login url
        login_url = Tokeninfo.authorize_url(
            {"scope": "openid profile email"}
        )  #{ "scope": "openid profile email https://uri.paypal.com/services/expresscheckout"}
        return HttpResponseRedirect(login_url)

    else:
        return afterLogin(request)
Example #10
0
def login_return(request):

    authCode = request.GET.get('code', '')

    if not authCode:
        return HttpResponseRedirect('/')

    # Create tokeninfo with Authorize code
    tokeninfo = Tokeninfo.create(authCode)

    #     request.session['id_token'] = tokeninfo.id_token
    request.session['access_token'] = tokeninfo.access_token
    request.session['refresh_token'] = tokeninfo.refresh_token
    request.session['logout_url'] = tokeninfo.logout_url()
    #     request.session.set_expiry(float(tokeninfo.expires_in))

    # Get userinfo
    userinfo = tokeninfo.userinfo()
    request.session['email'] = userinfo.email
    request.session['name'] = userinfo.name
    checkUser(userinfo.email, True)

    return afterLogin(request)
Example #11
0
# if payment.create():
#   print("Payment[%s] created successfully" % (payment.id))
#   # PayerID is required to approve the payment.
#   if payment.execute({"payer_id": "DUFRQ8GWYMJXC"}):  # return True or False
#     print("Payment[%s] execute successfully" % (payment.id))
#   else:
#     print(payment.error)

# else:
#   print(payment.error)

from paypalrestsdk.openid_connect import Tokeninfo, Userinfo


# Generate login url
login_url = Tokeninfo.authorize_url({ "scope": "openid profile"})

# Create tokeninfo with Authorize code
tokeninfo = Tokeninfo.create("Replace with Authorize code")

# Refresh tokeninfo
tokeninfo = tokeninfo.refresh()

# Create tokeninfo with refresh_token
tokeninfo = Tokeninfo.create_with_refresh_token("Replace with refresh_token")

# Get userinfo
userinfo  = tokeninfo.userinfo()

# Get userinfo with access_token
userinfo  = Userinfo.get("Replace with access_token")
Example #12
0
#  tokeninfo = Tokeninfo.create(code)
#  print(tokeninfo)
#  # Response 200
#  tokeninfo = {
#    token_type: 'Bearer',
#    expires_in: '28800',
#    refresh_token: 'J5yFACP3Y5dqdWCdN3o9lNYz0XyR01IHNMQn-E4r6Ss38rqbQ1C4rC6PSBhJvB_tte4WZsWe8ealMl-U_GMSz30dIkKaovgN41Xf8Sz0EGU55da6tST5I6sg3Rw',
#    id_token: '<some value>',
#    access_token: '<some value>'
#  }
#end

# Step 4. You can use the refresh token to get the third party merchant's email address to use in the invoice, and then you can create an invoice on behalf of the third party merchant.
refresh_token = "J5yFACP3Y5dqdWCdN3o9lNYz0XyR01IHNMQn-E4r6Ss38rqbQ1C4rC6PSBhJvB_tte4WZsWe8ealMl-U_GMSz30dIkKaovgN41Xf8Sz0EGU55da6tST5I6sg3Rw"

token_info = Tokeninfo.create_with_refresh_token(refresh_token)

print(token_info)

user_info = token_info.userinfo()

print(user_info)

invoice = Invoice({
    "merchant_info": {
        # The email address used here would be of a third party.
        "email": user_info.email,
        "first_name": "Dennis",
        "last_name": "Doctor",
        "business_name": "Medical Professionals, LLC",
        "phone": {
Example #13
0
 def test_logout_url_using_tokeninfo(self):
     url = Tokeninfo({'id_token': '1234'}).logout_url()
     assert_regex_matches(self, url, 'id_token=1234')
Example #14
0
 def test_authorize_url_using_tokeninfo(self):
     url = Tokeninfo.authorize_url({'scope': 'openid profile'})
     assert_regex_matches(self, url, 'scope=openid\+profile')
Example #15
0
 def test_userinfo(self):
     self.assertRaises(paypal.UnauthorizedAccess, Tokeninfo().userinfo, {})
Example #16
0
    def checkout_prepare(self, request, cart):
        self.init_api()
        kwargs = {}
        if request.resolver_match and 'cart_namespace' in request.resolver_match.kwargs:
            kwargs['cart_namespace'] = request.resolver_match.kwargs[
                'cart_namespace']

        if request.event.settings.payment_paypal_connect_user_id:
            try:
                userinfo = Tokeninfo.create_with_refresh_token(
                    request.event.settings.payment_paypal_connect_refresh_token
                ).userinfo()
            except BadRequest as ex:
                ex = json.loads(ex.content)
                messages.error(
                    request, '{}: {} ({})'.format(
                        _('We had trouble communicating with PayPal'),
                        ex['error_description'], ex['correlation_id']))
                return

            request.event.settings.payment_paypal_connect_user_id = userinfo.email
            payee = {
                "email": request.event.settings.payment_paypal_connect_user_id,
                # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                # we should use it instead of the merchant's eMail-address
                # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
            }
        else:
            payee = {}

        payment = paypalrestsdk.Payment({
            'header': {
                'PayPal-Partner-Attribution-Id': 'ramiioSoftwareentwicklung_SP'
            },
            'intent':
            'sale',
            'payer': {
                "payment_method": "paypal",
            },
            "redirect_urls": {
                "return_url":
                build_absolute_uri(request.event,
                                   'plugins:paypal:return',
                                   kwargs=kwargs),
                "cancel_url":
                build_absolute_uri(request.event,
                                   'plugins:paypal:abort',
                                   kwargs=kwargs),
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name": __('Order for %s') % str(request.event),
                        "quantity": 1,
                        "price": self.format_price(cart['total']),
                        "currency": request.event.currency
                    }]
                },
                "amount": {
                    "currency": request.event.currency,
                    "total": self.format_price(cart['total'])
                },
                "description":
                __('Event tickets for {event}').format(
                    event=request.event.name),
                "payee":
                payee
            }]
        })
        request.session['payment_paypal_order'] = None
        return self._create_payment(request, payment)
import paypalrestsdk
from paypalrestsdk.openid_connect import Tokeninfo

paypalrestsdk.configure({ 'openid_client_id': 'CLIENT_ID',
  'openid_client_secret': 'CLIENT_SECRET',
  'openid_redirect_uri': 'http://example.com' })

login_url = Tokeninfo.authorize_url({ 'scope': 'openid profile'})

print(login_url)

code = raw_input('Authorize code: ')

tokeninfo = Tokeninfo.create(code)

print(tokeninfo)

userinfo  = tokeninfo.userinfo()

print(userinfo)

tokeninfo = tokeninfo.refresh()

print(tokeninfo)

logout_url = tokeninfo.logout_url()

print(logout_url)
Example #18
0
def refreshToken(request):

    refreshtoken = request.session['refresh_token']
    tokeninfo = Tokeninfo.create_with_refresh_token(refreshtoken)
    request.session['id_token'] = tokeninfo.id_token
    request.session['access_token'] = tokeninfo.access_token
 def test_refresh(self):
     self.assertRaises(paypal.BadRequest, Tokeninfo().refresh, {})
Example #20
0
    def payment_prepare(self, request, payment_obj):
        self.init_api()

        try:
            if request.event.settings.payment_paypal_connect_user_id:
                try:
                    tokeninfo = Tokeninfo.create_with_refresh_token(
                        request.event.settings.
                        payment_paypal_connect_refresh_token)
                except BadRequest as ex:
                    ex = json.loads(ex.content)
                    messages.error(
                        request, '{}: {} ({})'.format(
                            _('We had trouble communicating with PayPal'),
                            ex['error_description'], ex['correlation_id']))
                    return

                # Even if the token has been refreshed, calling userinfo() can fail. In this case we just don't
                # get the userinfo again and use the payment_paypal_connect_user_id that we already have on file
                try:
                    userinfo = tokeninfo.userinfo()
                    request.event.settings.payment_paypal_connect_user_id = userinfo.email
                except UnauthorizedAccess:
                    pass

                payee = {
                    "email":
                    request.event.settings.payment_paypal_connect_user_id,
                    # If PayPal ever offers a good way to get the MerchantID via the Identifity API,
                    # we should use it instead of the merchant's eMail-address
                    # "merchant_id": request.event.settings.payment_paypal_connect_user_id,
                }
            else:
                payee = {}

            payment = paypalrestsdk.Payment({
                'header': {
                    'PayPal-Partner-Attribution-Id':
                    'ramiioSoftwareentwicklung_SP'
                },
                'intent':
                'sale',
                'payer': {
                    "payment_method": "paypal",
                },
                "redirect_urls": {
                    "return_url":
                    build_absolute_uri(request.event, 'plugins:paypal:return'),
                    "cancel_url":
                    build_absolute_uri(request.event, 'plugins:paypal:abort'),
                },
                "transactions": [{
                    "item_list": {
                        "items": [{
                            "name": ('{} '.format(self.settings.prefix)
                                     if self.settings.prefix else '') +
                            __('Order {slug}-{code}').format(
                                slug=self.event.slug.upper(),
                                code=payment_obj.order.code),
                            "quantity":
                            1,
                            "price":
                            self.format_price(payment_obj.amount),
                            "currency":
                            payment_obj.order.event.currency
                        }]
                    },
                    "amount": {
                        "currency": request.event.currency,
                        "total": self.format_price(payment_obj.amount)
                    },
                    "description":
                    ('{} '.format(self.settings.prefix) if self.settings.prefix
                     else '') + __('Order {order} for {event}').format(
                         event=request.event.name,
                         order=payment_obj.order.code),
                    "payee":
                    payee
                }]
            })
            request.session['payment_paypal_payment'] = payment_obj.pk
            return self._create_payment(request, payment)
        except paypalrestsdk.exceptions.ConnectionError as e:
            messages.error(request,
                           _('We had trouble communicating with PayPal'))
            logger.exception('Error on creating payment: ' + str(e))
Example #21
0
    def get_connect_url(self, request):
        request.session['payment_paypal_oauth_event'] = request.event.pk

        self.init_api()
        return Tokeninfo.authorize_url({'scope': 'openid profile email'})
Example #22
0
    def get_connect_url(self, request):
        request.session['payment_paypal_oauth_event'] = request.event.pk

        self.init_api()
        return Tokeninfo.authorize_url({'scope': 'openid profile email'})
Example #23
0
 def test_refresh(self):
     self.assertRaises(paypal.ResourceNotFound, Tokeninfo().refresh, {})
 def test_authorize_url_using_tokeninfo(self):
   url = Tokeninfo.authorize_url({ 'scope': 'openid profile' })
   assert_regex_matches(self, url, 'scope=openid\+profile')
Example #25
0
def create_session():
    data = request.args
    user = None
    registered = False

    if 'code' in data:
        code = data.get('code')

        try:
            options = configure_openid_request(code=code)

            tokeninfo = Tokeninfo.create(options=options)
            userinfo = tokeninfo.userinfo(options=options)

            userinfo_dict = userinfo.to_dict()

            if 'email' in userinfo_dict:
                email = userinfo_dict.get('email')

                user = User.query\
                    .filter_by(email=email)\
                    .first()

                if user is None:
                    user = create_user_from_userinfo(userinfo_dict)
                    registered = True
                    app.logger.debug("Paypal User %s created using userinfo" %
                                     email)
                else:
                    app.logger.debug("User %s found using email" % email)
            else:
                app.logger.debug("No email found using email")

            if user is not None:
                if not user.is_active:
                    app.logger.debug("User provided is inactive.")

                    flash("Your e-mail is not verified. Please check your "
                          "inbox to verify & activate your account.")

                    try:
                        response = send_verification_notification(user)
                        app.logger.info(response)

                        app.logger.debug(
                            'Sent verification notification to %s' %
                            user.email)
                    except Exception as e:
                        app.logger.exception(e)

                    app.logger.debug('Redirecting to %s' %
                                     url_for("account_verification"))
                    return redirect(url_for("account_verification"))
                else:
                    app.logger.debug("User provided is active.")

                    if login_user(user, remember=True):
                        app.logger.debug("logged in user: %s" % user.email)
                        app.logger.debug('session == %s' % session)

                        if not registered and clean_phone_no(user.phone):
                            return render_template("authenticated_popup.html",
                                                   token=session['token'],
                                                   user=user,
                                                   redirect_to=url_for('home'))
                        elif registered:
                            if not clean_phone_no(user.phone):
                                return redirect(
                                    url_for('mpesa_mobile_phone_no'))
                            else:
                                flash(
                                    "You have been registered successfully "
                                    "check your e-mail and phone for verification codes."
                                )

                                send_registration_notification(user)
                                return redirect(
                                    url_for("account_verification"))
                    else:
                        app.logger.debug("Could not login user")
                        return jsonify(
                            success=False,
                            message="Forbidden: error logging you in."), 403
            else:
                return jsonify(
                    success=False,
                    message="could not authenticate via paypal"), 403
        except Exception as e:
            app.logger.exception(e)
            return internal_server_error(e)

    elif 'error_uri' in data:
        error_uri = data.get('error_uri')
        error_description = data.get('error_description')
        error = data.get('error')

        return internal_server_error(error)

    return page_not_found()