def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Get the all the activated methods for this API key.
        #
        params = {
            'amount': {
                'currency': 'EUR',
                'value': '100.00',
            }
        }
        methods = mollie_client.methods.list(**params)
        body = 'Your API key has {num} activated payment methods:<br>'.format(num=len(methods))

        for method in methods:
            body += '<div style="line-height:40px; vertical-align:top">'
            body += '<img src="{url}"> {desc} ({id})'.format(
                url=method.image_svg, desc=method.description, id=method.id)
            body += '</div>'

        return body

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#2
0
    def paid_method(self, request):
        try:
            from mollie.api.client import Client
        except:
            from pip._internal import main
            main(['install', 'mollie.api.client'])
            from mollie.api.client import Client
        url = request.query_params.get('url')  #hostname send from frontend
        mollie_client = Client()
        mollie_client.set_api_key('test_Cpf7MF9sAfpSmvnbqMRwuaFqBSRQF4')
        userid = request.query_params.get('userId')
        redirect_url = "http://127.0.0.1:8000/order/3/" if url == "127.0.0.1" else "http://" + settings.ALLOWED_HOSTS[
            0] + "/order/3/"
        print(self.total(userid))
        payment = mollie_client.payments.create({
            'amount': {
                'currency': 'EUR',
                'value': '{}.00'.format(self.total(userid))
                # 'value': '10.00'
            },
            'description': 'My first API payment',
            "redirectUrl": redirect_url,
            # 'webhookUrl': 'https://webshop.example.org/mollie-webhook/',
        })

        return Response(payment)
示例#3
0
def test_oauth_client_will_refresh_token_automatically(mocker, oauth_token,
                                                       response):
    """Initializing the client with an expired token will trigger a token refresh automatically."""
    # expire the token: set expiration time in the past.
    oauth_token["expires_at"] = time.time() - 5

    set_token_mock = mocker.Mock()

    client = Client()
    client.setup_oauth(
        client_id="client_id",
        client_secret="client_secret",
        redirect_uri="https://example.com/callback",
        scope=("organizations.read", ),
        token=oauth_token,
        set_token=set_token_mock,
    )

    # setup two request mocks: the token refresh and the actual data request
    response.post("https://api.mollie.com/oauth2/tokens", "token_single")
    response.get("https://api.mollie.com/v2/organizations/me",
                 "organization_current")

    organization = client.organizations.get('me')
    assert isinstance(organization,
                      Organization), "Unexpected result from request."
    assert response.assert_all_requests_are_fired, "Not all expected requests have been performed."

    # verify handling of the new token
    set_token_mock.assert_called_once()
    args, kwargs = set_token_mock.call_args
    assert isinstance(args[0],
                      dict), "set_token() did not receive a dictionary."
示例#4
0
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Get the all the activated methods for this API key.
        #
        params = {
            'amount': {
                'currency': 'EUR',
                'value': '100.00',
            }
        }
        methods = mollie_client.methods.list(**params)
        body = 'Your API key has {num} activated payment methods:<br>'.format(
            num=len(methods))

        for method in methods:
            body += '<div style="line-height:40px; vertical-align:top">'
            body += '<img src="{url}"> {desc} ({id})'.format(
                url=method.image_svg, desc=method.description, id=method.id)
            body += '</div>'

        return body

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#5
0
def mollieResponse(request, id):
    ticket = WorkspaceRequest.objects.get(id=id)
    if request.method == "POST":

        mollie_client = Client()
        mollie_client.set_api_key('test_TQW97evcmbKSDRKhKCG4GVnJfHCkRK')

        payment = mollie_client.payments.get(ticket.paymentId)
        print(ticket.paymentStatus)
        if payment.is_paid():
            ticket.paymentStatus = 1
            ticket.save()

            return 'Paid'
        elif payment.is_pending():

            return 'Pending'
        elif payment.is_open():

            return 'Open'
        else:

            return 'Cancelled'
    else:
        return render(request, 'access-denied.html')
示例#6
0
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Get the first page of payments for this API key ordered by newest.
        #
        payments = mollie_client.payments.list()

        body = ''

        if not len(payments):
            body += '<p>You have no payments. You can create one from the examples.</p>'
            return body

        body += '<p>Showing the first page of payments for this API key</p>'

        for payment in payments:
            body += "{curr} {value}, status: '{status}'<br>".format(
                curr=payment.amount['currency'], value=payment.amount['currency'], status=payment.status)

        return body

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#7
0
def client():
    """Setup a Mollie API client object."""
    api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')

    client = Client()
    client.set_api_key(api_key)
    return client
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        #  Refund all eligible items for your first order
        #
        # See: https://docs.mollie.com/reference/v2/orders-api/create-order-refund
        #
        body = '<p>Attempting to retrieve the first page of orders, and grabbing the first.</p>'

        order = next(mollie_client.orders.list())
        refund = order.create_refund()

        body += 'Refund {refund_id} was created for order {order_id}:'.format(refund_id=refund.id, order_id=order.id)

        return body
    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#9
0
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Retrieve the first shipment for your first order
        #
        # See: https://docs.mollie.com/reference/v2/shipments-api/get-shipment
        #
        body = '<p>Attempting to retrieve the first page of orders and grabbing the first.</p>'

        order = next(mollie_client.orders.list())
        if not len(order.shipments):
            body += '<p>You have no shipments. You can create one from the examples.</p>'
            return body

        shipment = next(order.shipments)
        body += 'Shipment with ID {shipment_id} for order with ID {order_id}'.format(
            shipment_id=shipment.id, order_id=order.id)

        for line in shipment.lines:
            body += '{name} Status: <b>{status}</b>'.format(name=line.name,
                                                            status=line.status)

        return body
    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#10
0
def client():
    """Setup a Mollie API client object."""
    api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')

    client = Client()
    client.set_api_key(api_key)
    return client
示例#11
0
def membership_buy_now():
    """
        Get a membership
    """
    from openstudio.os_customer_membership import CustomerMembership
    from openstudio.os_school_membership import SchoolMembership

    smID = request.vars['smID']

    # init mollie
    mollie = Client()
    mollie_api_key = get_sys_property('mollie_website_profile')
    mollie.set_api_key(mollie_api_key)

    # check if we have a mollie customer id
    create_mollie_customer(auth.user.id, mollie)

    # Create invoice
    sm = SchoolMembership(smID)
    cmID = sm.sell_to_customer(auth.user.id, TODAY_LOCAL)

    cm = CustomerMembership(cmID)
    iID = cm.get_linked_invoice()

    # Pay invoice ... SHOW ME THE MONEY!! :)
    redirect(URL('invoice_pay', vars={'iID': iID}))
示例#12
0
 def create_payment_load(self, cart, request):
     """
     Create a payment ID with UUID4, what is sent to the PSP
     """
     mollie_client = Client()
     mollie_client.set_api_key(settings.SHOP_MOLLIE['MOLLIE_KEY'])
     cart = CartModel.objects.get_from_request(request)
     order = OrderModel.objects.create_from_cart(cart, request)
     order.populate_from_cart(cart, request)
     order.save(with_notification=False)
     payment_data = {
         'amount': {
             'currency': 'EUR',
             'value': '%.2f' % cart.total
         },
         'description':
         'Test payment',
         'webhookUrl':
         self.build_absolute_url(request, 'mollie-webhook'),
         'redirectUrl':
         ''.join([
             'https://', settings.SHOP_MOLLIE['DOMAIN'],
             order.get_absolute_url()
         ]),
         'metadata': {
             'order_id': order.get_number(),
         },
         'method':
         settings.SHOP_MOLLIE[
             'MOLLIE_PAYMENT_METHODS'],  #array of payment methods via Mollie
     }
     payment = mollie_client.payments.create(payment_data)
     return payment
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Create a shipment for your entire first order
        #
        # See: https://docs.mollie.com/reference/v2/shipments-api/create-shipment
        #
        body = ''

        order_id = flask.request.args.get('order_id')

        if order_id is None:
            body += '<p>No order ID specified. Attempting to retrieve the first page of '
            body += 'orders and grabbing the first.</p>'

        order = mollie_client.orders.get(order_id) if order_id else next(mollie_client.orders.list())

        shipment = order.create_shipment()
        body += 'A shipment with ID {shipment_id} has been created for your order with ID {order_id}'.format(
            shipment_id=shipment.id, order_id=order.id)
        for line in shipment.lines:
            body += '{name} Status: <b>{status}</b>'.format(name=line.name, status=line.status)

        return body
    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#14
0
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Retrieve the first shipment for your first order
        #
        # See: https://docs.mollie.com/reference/v2/shipments-api/get-shipment
        #
        body = '<p>Attempting to retrieve the first page of orders and grabbing the first.</p>'

        order = next(mollie_client.orders.list())
        if not len(order.shipments):
            body += '<p>You have no shipments. You can create one from the examples.</p>'
            return body

        shipment = next(order.shipments)
        body += 'Shipment with ID {shipment_id} for order with ID {order_id}'.format(
            shipment_id=shipment.id, order_id=order.id)

        for line in shipment.lines:
            body += '{name} Status: <b>{status}</b>'.format(name=line.name, status=line.status)

        return body
    except Error as err:
        return 'API call failed: {error}'.format(error=err)
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        body = ''

        customer_id = flask.request.args.get('customer_id')

        # If no customer ID was provided in the URL, we grab the first customer
        if customer_id is None:
            customers = mollie_client.customers.list()

            body += '<p>No customer ID specified. Attempting to retrieve the first page of '
            body += 'customers and grabbing the first.</p>'

            if not len(customers):
                body += '<p>You have no customers. You can create one from the examples.</p>'
                return body

            customer = next(customers)
        else:
            customer = mollie_client.customers.get(customer_id)

        #
        # Generate a unique webshop order number for this example. It is important to include this unique attribute
        # in the redirectUrl (below) so a proper return page can be shown to the customer.
        #
        my_webshop_id = int(time.time())

        #
        # See: https://www.mollie.com/nl/docs/reference/customers/create-payment
        #
        payment = mollie_client.customer_payments.with_parent_id(customer.id).create({
            'amount': {
                'currency': 'EUR',
                'value': '100.00'
            },
            'description': 'My first API payment',
            'webhookUrl': '{root}02-webhook_verification'.format(root=flask.request.url_root),
            'redirectUrl': '{root}03-return-page?my_webshop_id={id}'.format(
                root=flask.request.url_root, id=my_webshop_id),
            'metadata': {
                'my_webshop_id': str(my_webshop_id)
            },
        })
        data = {'status': payment.status}
        database_write(my_webshop_id, data)

        return '<p>Created payment of {curr} {value} for {cust} ({id})<p>'.format(
            curr=payment.amount['currency'], value=payment.amount['value'], cust=customer.name, id=customer.id)

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#16
0
    def get_mollie_mandates(self):
        """
            Returns mollie mandates
        """
        get_sys_property = current.globalenv['get_sys_property']

        from mollie.api.client import Client
        from mollie.api.error import Error as MollieError
        # init mollie
        mollie = Client()
        mollie_api_key = get_sys_property('mollie_website_profile')
        mollie.set_api_key(mollie_api_key)

        # check if we have a mollie customer id
        if self.row.mollie_customer_id:
            mollie_customer_id = self.row.mollie_customer_id
            #print mollie_customer_id
        else:
            # create one
            mollie_customer_id = self.register_mollie_customer(mollie)

        mandates = mollie.customer_mandates.with_parent_id(
            mollie_customer_id).list()

        return mandates
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Get the first page of payments for this API key ordered by newest.
        #
        payments = mollie_client.payments.list()

        body = ''

        if not len(payments):
            body += '<p>You have no payments. You can create one from the examples.</p>'
            return body

        body += '<p>Showing the first page of payments for this API key</p>'

        for payment in payments:
            body += "{curr} {value}, status: '{status}'<br>".format(
                curr=payment.amount['currency'], value=payment.amount['currency'], status=payment.status)

        return body

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # See: https://www.mollie.com/nl/docs/reference/customers/create
        #
        customer = mollie_client.customers.create({
            'name': 'Mr. First Customer',
            'email': '*****@*****.**',
            'locale': 'nl_NL'
        })

        return "Created new customer '{name}' ({email})".format(
            name=customer.name, email=customer.email)

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#19
0
def mollie_webhook():
    try:
        mollie_client = Client()
        mollie_client.set_api_key(g.mollie)
        if 'id' not in request.form:
            abort(404, 'Unknown payment id')
        payment_id = request.form['id']
        payment = mollie_client.payments.get(payment_id)
        purchase = Purchase.query.filter(Purchase.purchase_id == payment.metadata["purchase_id"]).first()
        if purchase is not None:
            if payment.is_paid():
                # At this point you'd probably want to start the process of delivering the product to the customer.
                purchase.purchase_paid()
                db.session.commit()
                send_purchased_tickets(purchase)
                return 'Paid'
            elif payment.is_pending():
                # The payment has started but is not complete yet.
                purchase.purchase_pending()
                db.session.commit()
                return 'Pending'
            elif payment.is_open():
                # The payment has not started yet. Wait for it.
                return 'Open'
            else:
                # The payment has been unsuccessful.
                purchase.cancel_purchase()
                db.session.commit()
                return 'Cancelled'
        return "No purchase found"
    except Error as e:
        return 'Mollie Webhook call failed: {error}'.format(error=e)
示例#20
0
 def get(self, request):
     mollie_client = Client()
     mollie_client.set_api_key(settings.IDEAL_API)
     # mollie_client.methods.get('ideal', include='issuers,pricing')
     list_bank = mollie_client.methods.get('ideal', include='issuers')
     # list_bank = mollie_client.methods.get(mollie.api.objects.Method.IDEAL, include='issuers')
     return render(request, 'payments/iDeal/start_ideal.html',
                   {'list_bank': list_bank})
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        body = ''

        customer_id = flask.request.args.get('customer_id')

        # If no customer ID was provided in the URL, we grab the first customer
        customer = None
        if customer_id is None:

            body += '<p>No customer ID specified. Attempting to retrieve the first page of customers '
            body += 'and grabbing the first.</p>'

            customers = mollie_client.customers.list()

            if not len(customers):
                body += '<p>You have no customers. You can create one from the examples.</p>'
                return body

            customer = next(customers)

        if not customer:
            customer = mollie_client.customers.get(customer_id)

        amount_of_payments_to_retrieve = 20

        #
        # Retrieve the latest payments for the customer
        #
        # See: https://www.mollie.com/nl/docs/reference/customers/list-payments
        #
        params = {
            'limit': amount_of_payments_to_retrieve,
        }
        payments = mollie_client.customer_payments.with_parent_id(
            customer_id).list(**params)

        body += '<p>Showing the last {num} payments for customer "{cust}"</p>'.format(
            num=len(payments), cust=customer.id)

        for payment in payments:
            body += "<p>Payment {id} ({value}) {curr}</p>".format(
                id=payment.id,
                value=payment.amount['value'],
                curr=payment.amount['currency'])
        return body

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#22
0
def test_client_will_propagate_retry_setting(response):
    response.get('https://api.mollie.com/v2/methods', 'methods_list')

    client = Client(retry=3)
    client.set_api_key("test_test")
    client.methods.list()

    adapter = client._client.adapters['https://']
    assert adapter.max_retries.connect == 3
示例#23
0
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Generate a unique webshop order id for this example. It is important to include this unique attribute
        # in the redirectUrl (below) so a proper return page can be shown to the customer.
        #
        my_webshop_id = int(time.time())

        #
        # Payment parameters:
        # amount        Currency and value. This example creates a € 120,- payment.
        # description   Description of the payment.
        # webhookUrl    Webhook location, used to report when the payment changes state.
        # redirectUrl   Redirect location. The customer will be redirected there after the payment.
        # metadata      Custom metadata that is stored with the payment.
        #
        payment = mollie_client.payments.create({
            'amount': {
                'currency': 'EUR',
                'value': '120.00'
            },
            'description':
            'My first API payment',
            'webhookUrl':
            '{root}02-webhook_verification'.format(
                root=flask.request.url_root),
            'redirectUrl':
            '{root}03-return-page?my_webshop_id={id}'.format(
                root=flask.request.url_root, id=my_webshop_id),
            'metadata': {
                'my_webshop_id': str(my_webshop_id)
            }
        })

        #
        # In this example we store the order with its payment status in a database.
        #
        data = {'status': payment.status}
        database_write(my_webshop_id, data)

        #
        # Send the customer off to complete the payment.
        #
        return flask.redirect(payment.checkout_url)

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#24
0
def test_client_generic_request_error(response):
    """
    When the remote server refuses connections or other request issues arise, an error should be raised.

    The 'response' fixture blocks all outgoing connections, also when no actual responses are configured.
    """
    client = Client()
    client.set_api_key('test_test')
    client.set_api_endpoint('https://api.mollie.invalid/')
    with pytest.raises(RequestError, match='Unable to communicate with Mollie: Connection refused'):
        client.customers.list()
示例#25
0
def test_client_no_cert_bundle(monkeypatch):
    """A request should raise an error when the certificate bundle is not available."""
    def mockreturn(modulepath, file):
        return ''

    monkeypatch.setattr(pkg_resources, 'resource_filename', mockreturn)

    client = Client()
    client.set_api_key('test_test')
    with pytest.raises(RequestSetupError) as excinfo:
        client.customers.list()
    assert excinfo.match('Unable to load cacert.pem')
示例#26
0
    def _mollie_form_validate(self, data):
        reference = data.get('reference')
        acquirer = self.acquirer_id
        if self.state == 'done':
            _logger.info(
                'Mollie: trying to validate an already validated tx (ref %s)',
                reference)
            return True

        mollie_client = Client()
        tx = self._mollie_form_get_tx_from_data(data)
        transactionId = tx['acquirer_reference']
        _logger.info("Validated transfer payment forTx %s: set as pending" % (
            reference))

        mollie_api_key = acquirer._get_mollie_api_keys(
            acquirer.state)['mollie_api_key']
        mollie_client.set_api_key(mollie_api_key)
        mollie_response = mollie_client.payments.get(transactionId)
        try:
            # dateutil and pytz don't recognize abbreviations PDT/PST
            tzinfos = {
                'PST': -8 * 3600,
                'PDT': -7 * 3600,
            }
            date = dateutil.parser.parse(data.get('createdAt'),
                                         tzinfos=tzinfos).astimezone(pytz.utc)
        except:
            date = fields.Datetime.now()
        res = {
            'acquirer_reference': mollie_response.get('id', ''),
        }

        status = mollie_response.get("status", "undefined")

        if status in ["paid", "authorized"]:
            res.update(date=date)
            self._set_transaction_done()
            return self.write(res)

        elif status in ["cancelled", "expired", "failed"]:
            self._set_transaction_cancel()
            return self.write(res)

        elif status in ["open", "pending"]:
            self._set_transaction_pending()
            return self.write(res)

        else:
            msg = "Error/%s/%s" % (transactionId, reference)
            self._set_transaction_error(msg)
            return self.write(res)
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        body = ''

        customer_id = flask.request.args.get('customer_id')

        # If no customer ID was provided in the URL, we grab the first customer
        if customer_id is None:
            customers = mollie_client.customers.list()

            body += '<p>No customer ID specified. Attempting to retrieve the first page of customers '
            body += 'and grabbing the first.</p>'

            if not len(customers):
                body += '<p>You have no customers. You can create one from the examples.</p>'
                return body

            customer = next(customers)
        else:
            customer = mollie_client.customers.get(customer_id)

        amount_of_payments_to_retrieve = 20

        #
        # Retrieve the latest payments for the customer
        #
        # See: https://www.mollie.com/nl/docs/reference/customers/list-payments
        #
        params = {
            'limit': amount_of_payments_to_retrieve,
        }
        payments = mollie_client.customer_payments.with_parent_id(customer.id).list(**params)

        body += '<p>Showing the last {num} payments for customer "{cust}"</p>'.format(
            num=len(payments), cust=customer.id)

        for payment in payments:
            body += "<p>Payment {id} ({value}) {curr}</p>".format(
                id=payment.id, value=payment.amount['value'], curr=payment.amount['currency'])
        return body

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#28
0
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Generate a unique webshop order id for this example. It is important to include this unique attribute
        # in the redirectUrl (below) so a proper return page can be shown to the customer.
        #
        my_webshop_id = int(time.time())

        #
        # Payment parameters:
        # amount        Currency and value. This example creates a € 120,- payment.
        # description   Description of the payment.
        # webhookUrl    Webhook location, used to report when the payment changes state.
        # redirectUrl   Redirect location. The customer will be redirected there after the payment.
        # metadata      Custom metadata that is stored with the payment.
        #
        payment = mollie_client.payments.create({
            'amount': {
                'currency': 'EUR',
                'value': '120.00'
            },
            'description': 'My first API payment',
            'webhookUrl': '{root}02-webhook_verification'.format(root=flask.request.url_root),
            'redirectUrl': '{root}03-return-page?my_webshop_id={id}'.format(root=flask.request.url_root,
                                                                            id=my_webshop_id),
            'metadata': {
                'my_webshop_id': str(my_webshop_id)
            }
        })

        #
        # In this example we store the order with its payment status in a database.
        #
        data = {'status': payment.status}
        database_write(my_webshop_id, data)

        #
        # Send the customer off to complete the payment.
        #
        return flask.redirect(payment.checkout_url)

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#29
0
def order_pay():
    """
        Page to pay an order
    """
    coID = request.vars['coID']

    order = Order(coID)
    invoice_id = ''
    mollie_payment_id = ''

    # check if the order belongs to the currently logged in customer
    if not order.order.auth_customer_id == auth.user.id:
        session.flash = T("Unable to show order")
        redirect(URL('cart'))

    mollie = Client()
    mollie_api_key = get_sys_property('mollie_website_profile')
    mollie.set_api_key(mollie_api_key)

    amounts = order.get_amounts()

    # Go to Mollie for payment
    amount = format(amounts.TotalPriceVAT, '.2f')
    description = T('Order') + ' #' + unicode(coID)

    try:
        payment = mollie.payments.create({
            'amount': {
                'currency': CURRENCY,
                'value': amount
            },
            'description':
            description,
            'redirectUrl':
            'https://' + request.env.http_host + '/shop/complete?coID=' +
            unicode(coID),
            'webhookUrl':
            'https://' + request.env.http_host + '/mollie/webhook',
            'metadata': {
                'customers_orders_id': coID
            }
        })

        db.customers_orders_mollie_payment_ids.insert(
            customers_orders_id=coID, mollie_payment_id=payment['id'])

        # Send the customer off to complete the payment.
        redirect(payment.checkout_url)

    except MollieError as e:
        return 'API call failed: ' + e.message
示例#30
0
def test_client_response_404_but_no_payload(response):
    """
    An error response from the API should raise an error.

    When the response returns an error, but no valid error data is available in the response,
    we should still raise an error. The API v1 formatted error in the test is missing the required 'status' field.
    """
    response.get('https://api.mollie.com/v3/customers', 'v1_api_error', status=404)
    client = Client()
    client.api_version = 'v3'
    client.set_api_key('test_test')

    with pytest.raises(ResponseHandlingError, match='Invalid API version'):
        client.customers.list()
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        #  Update the tracking information for a shipment
        #
        # See: https://docs.mollie.com/reference/v2/shipments-api/update-shipment
        #
        body = '<p>Attempting to retrieve the first page of orders, and grabbing the first.</p>'
        order = next(mollie_client.orders.list())

        if not len(order.shipments):
            body += '<p>You have no shipments. You can create one from the examples.</p>'
            return body

        body = '<p>Attempting to retrieve the first page of shipments if your order, and grabbing the first.</p>'
        shipment = next(order.shipments)

        tracking = {
            'carrier':
            'PostNL',
            'code':
            '3SKABA000000000',
            'url':
            'http://postnl.nl/tracktrace/?B=3SKABA000000000&P=1016EE&D=NL&T=C',
        }
        shipment = order.update_shipment(shipment.id, tracking)

        body += 'Shipment {shipment_id} for order {order_id}:'.format(
            shipment_id=shipment.id, order_id=order.id)
        body += 'Tracking information updated:'
        body += 'Carrier: {carrier}'.format(
            carrier=shipment.tracking['carrier'])
        body += 'Code: {code}'.format(code=shipment.tracking['code'])
        body += 'Url: {url}'.format(url=shipment.tracking_url)

        for line in shipment.lines:
            body += '{name} Status: <b>{status}</b>'.format(name=line.name,
                                                            status=line.status)

        return body
    except Error as err:
        return 'API call failed: {error}'.format(error=err)
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Retrieve the payment's current state.
        #
        if 'id' not in flask.request.form:
            flask.abort(404, 'Unknown payment id')

        payment_id = flask.request.form['id']
        payment = mollie_client.payments.get(payment_id)
        my_webshop_id = payment.metadata['my_webshop_id']

        #
        # Update the order in the database.
        #
        data = {'status': payment.status}
        database_write(my_webshop_id, data)

        if payment.is_paid():
            #
            # At this point you'd probably want to start the process of delivering the product to the customer.
            #
            return 'Paid'
        elif payment.is_pending():
            #
            # The payment has started but is not complete yet.
            #
            return 'Pending'
        elif payment.is_open():
            #
            # The payment has not started yet. Wait for it.
            #
            return 'Open'
        else:
            #
            # The payment isn't paid, pending nor open. We can assume it was aborted.
            #
            return 'Cancelled'

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#33
0
    def _mollie_form_validate(self, data):
        reference = data.get("reference")
        acquirer = self.acquirer_id
        if self.state == "done":
            _logger.info(
                "Mollie: trying to validate an already validated tx (ref %s)",
                reference,
            )
            return True

        mollie_client = Client()
        tx = self._mollie_form_get_tx_from_data(data)
        transactionId = tx["acquirer_reference"]
        _logger.info("Validated transfer payment forTx %s: set as pending" %
                     (reference))

        mollie_api_key = acquirer._get_mollie_api_keys(
            acquirer.state)["mollie_api_key"]
        mollie_client.set_api_key(mollie_api_key)
        mollie_response = mollie_client.payments.get(transactionId)
        try:
            # dateutil and pytz don't recognize abbreviations PDT/PST
            tzinfos = {"PST": -8 * 3600, "PDT": -7 * 3600}
            date = dateutil.parser.parse(data.get("createdAt"),
                                         tzinfos=tzinfos).astimezone(pytz.utc)
        except Exception:
            date = fields.Datetime.now()
        res = {"acquirer_reference": mollie_response.get("id", "")}

        status = mollie_response.get("status", "undefined")

        if status in ["paid", "authorized"]:
            res.update(date=date)
            self._set_transaction_done()
            return self.write(res)

        elif status in [
                "canceled", "expired", "failed"
        ]:  # In the v1 API, canceled status was misspelled as cancelled [19430].
            self._set_transaction_cancel()
            return self.write(res)

        elif status in ["open", "pending"]:
            self._set_transaction_pending()
            return self.write(res)

        else:
            msg = "Error/%s/%s" % (transactionId, reference)
            self._set_transaction_error(msg)
            return self.write(res)
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Retrieve the payment's current state.
        #
        if 'id' not in flask.request.form:
            flask.abort(404, 'Unknown payment id')

        payment_id = flask.request.form['id']
        payment = mollie_client.payments.get(payment_id)
        my_webshop_id = payment.metadata['my_webshop_id']

        #
        # Update the order in the database.
        #
        data = {'status': payment.status}
        database_write(my_webshop_id, data)

        if payment.is_paid():
            #
            # At this point you'd probably want to start the process of delivering the product to the customer.
            #
            return 'Paid'
        elif payment.is_pending():
            #
            # The payment has started but is not complete yet.
            #
            return 'Pending'
        elif payment.is_open():
            #
            # The payment has not started yet. Wait for it.
            #
            return 'Open'
        else:
            #
            # The payment isn't paid, pending nor open. We can assume it was aborted.
            #
            return 'Cancelled'

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#35
0
def test_client_response_404_but_no_payload(response):
    """
    An error response from the API should raise an error.

    When the response returns an error, but no valid error data is available in the response,
    we should still raise an error. The API v1 formatted error in the test is missing the required 'status' field.
    """
    response.get('https://api.mollie.com/v3/customers', 'v1_api_error', status=404)
    client = Client()
    client.api_version = 'v3'
    client.set_api_key('test_test')

    with pytest.raises(ResponseHandlingError) as excinfo:
        client.customers.list()
    assert excinfo.match('Invalid API version')
示例#36
0
def test_client_broken_cert_bundle(monkeypatch):
    """A request should raise an error when the certificate bundle is not available.

    Under circumstances it could be possible that the certifi package is not correctly installed, broken,
    or just plain too old. Connecting to the Mollie API should fail with an error when the certificate
    cannot be verified.
    """
    monkeypatch.setenv("REQUESTS_CA_BUNDLE", "/does/not/exist")

    client = Client()
    client.set_api_key('test_test')
    with pytest.raises(OSError) as excinfo:
        client.customers.list()
    assert 'Could not find a suitable TLS CA certificate bundle, invalid path: /does/not/exist' in str(
        excinfo.value)
示例#37
0
    def _api_mollie_get_client(self):
        mollie_client = MollieClient()
        # TODO: [PGA] Add partical validation for keys e.g. production key should start from live_

        if self.state == 'enabled':
            mollie_client.set_api_key(self.mollie_api_key_prod)
        elif self.state == 'test':
            mollie_client.set_api_key(self.mollie_api_key_test)

        mollie_client.set_user_agent_component('Odoo', service.common.exp_version()['server_version'])
        mollie_client.set_user_agent_component('MollieOdoo', self.env.ref('base.module_payment_mollie_official').installed_version)
        return mollie_client
示例#38
0
def test_client_set_user_agent_component(response):
    """We should be able to add useragent components.

    Note: we don't use the fixture client because it is shared between tests, and we don't want it
    to be clobbered with random User-Agent strings.
    """
    client = Client()
    assert 'Hoeba' not in client.user_agent
    client.set_user_agent_component('Hoeba', '1.0.0')
    assert 'Hoeba/1.0.0' in client.user_agent

    response.get('https://api.mollie.com/v2/methods', 'methods_list')
    client.set_api_key('test_123')
    client.methods.list()
    request = response.calls[0].request
    assert 'Hoeba/1.0.0' in request.headers['User-Agent']
示例#39
0
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)
        #
        # After your webhook has been called with the order ID in its body, you'd like
        # to handle the order's status change. This is how you can do that.
        #
        # See: https://docs.mollie.com/reference/v2/orders-api/get-order
        #
        if 'id' not in flask.request.form:
            flask.abort(404, 'Unknown order id')

        order_id = flask.request.form['id']
        order = mollie_client.orders.get(order_id)
        my_webshop_id = order.metadata['my_webshop_id']
        #
        # Update the order in the database.
        #
        data = {'order_id': order.id, 'status': order.status}
        database_write(my_webshop_id, data)

        if order.is_paid() or order.is_authorized():
            #
            # At this point you'd probably want to start the process of delivering the product to the customer.
            #
            return 'Paid'
        if order.is_canceled():
            #
            # At this point you'd probably want to inform the customer that the order has been canceled.
            #
            return 'Canceled'
        if order.is_completed():
            #
            # At this point you could inform the customer that all deliveries to the customer have started.
            #
            return 'Completed'

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
def test_client_api_key_during_init_deprecated(recwarn):
    """Setting the api key during init should work but raise a warning."""
    with pytest.warns(
            DeprecationWarning,
            match=
            'Setting the API key during init will be removed in the future'):
        client = Client(api_key='test_123')
    assert client.api_key == 'test_123'
示例#41
0
def test_client_broken_cert_bundle(monkeypatch):
    """
    A request should raise an error when the certificate bundle is not available.

    Under circumstances it could be possible that the certifi package is not correctly installed, broken,
    or just plain too old. Connecting to the Mollie API should fail with an error when the certificate
    cannot be verified.

    We monkeypatch requests with a non-existent path at the location where certifi normally sets the correct path.
    """
    monkeypatch.setattr(requests.adapters, 'DEFAULT_CA_BUNDLE_PATH', '/does/not/exist')

    client = Client()
    client.set_api_key('test_test')
    with pytest.raises(
            RequestError,
            match='Could not find a suitable TLS CA certificate bundle, invalid path: /does/not/exist'):
        client.customers.list()
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        #  Update the tracking information for a shipment
        #
        # See: https://docs.mollie.com/reference/v2/shipments-api/update-shipment
        #
        body = '<p>Attempting to retrieve the first page of orders, and grabbing the first.</p>'
        order = next(mollie_client.orders.list())

        if not len(order.shipments):
            body += '<p>You have no shipments. You can create one from the examples.</p>'
            return body

        body = '<p>Attempting to retrieve the first page of shipments if your order, and grabbing the first.</p>'
        shipment = next(order.shipments)

        tracking = {
            'carrier': 'PostNL',
            'code': '3SKABA000000000',
            'url': 'http://postnl.nl/tracktrace/?B=3SKABA000000000&P=1016EE&D=NL&T=C',
        }
        shipment = order.update_shipment(shipment.id, tracking)

        body += 'Shipment {shipment_id} for order {order_id}:'.format(shipment_id=shipment.id, order_id=order.id)
        body += 'Tracking information updated:'
        body += 'Carrier: {carrier}'.format(carrier=shipment.tracking['carrier'])
        body += 'Code: {code}'.format(code=shipment.tracking['code'])
        body += 'Url: {url}'.format(url=shipment.tracking_url)

        for line in shipment.lines:
            body += '{name} Status: <b>{status}</b>'.format(name=line.name, status=line.status)

        return body
    except Error as err:
        return 'API call failed: {error}'.format(error=err)
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Listing shipments for the first order.
        #
        # See: https://docs.mollie.com/reference/v2/shipments-api/list-shipments
        #
        body = '<p>Attempting to retrieve the first page of orders, and grabbing the first.</p>'
        order = next(mollie_client.orders.list())
        shipments = order.shipments

        body += 'Shipments for order with ID {order_id}:'.format(order_id=order.id)
        body += """
            <table>
                <thead>
                    <tr>
                        <th>Shipment ID</th>
                        <th>Tracking url</th>
                        <th>Created at</th>
                    </tr>
                </thead>
                <tbody>
        """
        for shipment in shipments:
            body += '<tr>'
            body += '<td>{id}</td>'.format(id=shipment.id)
            body += '<td>{url}</td>'.format(url=shipment.tracking_url)
            body += '<td>{created}</td>'.format(created=shipment.created_at)
            body += '</tr>'

        body += "</tbody></table>"

        return body
    except Error as err:
        return 'API call failed: {error}'.format(error=err)
def main():
    try:
        #
        # List the most recent orders
        #
        # See: https://docs.mollie.com/reference/v2/orders-api/list-orders
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Fetch a list of orders and use the first.
        # Cancel the first order line.
        #
        # See: https://docs.mollie.com/reference/v2/orders-api/cancel-order-line
        #
        body = '<p>Attempting to retrieve the first page of orders, and grabbing the first.</p>'
        order = next(mollie_client.orders.list())
        line = next(order.lines)

        if line and line.is_cancelable:
            data = {
                'lines': [
                    {
                        'id': line.id,
                        'quantity': 1
                    }
                ]
            }
            order.cancel_lines(data)

            order = mollie_client.orders.get(order.id)
            body += 'Your order {order_id} was updated:'.format(order_id=order.id)
            for line in order.lines:
                body += '{name} Status: <b>{status}</b>'.format(name=line.name, status=line.status)
        else:
            body += 'Unable to cancel line {line_id} for your order {order_id}'.format(line_id=line.id,
                                                                                       order_id=order.id)
        return body

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #

        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        body = ''
        payment_id = ''

        body += '<p>Attempting to retrieve the first page of payments and grabbing the first.</p>'

        payments = mollie_client.payments.list()

        if not len(payments):
            body += '<p>You have no payments. You can create one from the examples.</p>'
            return body

        payment = next(payments)

        if payment.can_be_refunded() and payment.amount_remaining['currency'] == 'EUR' \
                and float(payment.amount_remaining['value']) >= 2.0:
            data = {
                'amount': {'value': '2.00', 'currency': 'EUR'}
            }
            refund = mollie_client.payment_refunds.with_parent_id(payment_id).create(data)
            body += '<p>{curr} {value} of payment {id} refunded</p>'.format(
                curr=refund.amount['currency'], value=refund.amount['value'], id=payment_id)
        else:
            body += '<p>Payment {id} can not be refunded</p>'.format(id=payment_id)
        return body
    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#46
0
def test_client_api_key():
    """Setting up a valid api key or access token should be possible."""
    client = Client()

    client.set_access_token('access_123')
    assert client.api_key == 'access_123'

    client.set_api_key('live_123')
    assert client.api_key == 'live_123'

    client.set_api_key('test_123')
    assert client.api_key == 'test_123'
def main():
    api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
    mollie_client = Client()
    mollie_client.set_api_key(api_key)

    if 'my_webshop_id' not in flask.request.args:
        flask.abort(404, 'Unknown webshop id')

    data = database_read(flask.request.args['my_webshop_id'])

    order = mollie_client.orders.get(data['order_id'])

    if order.is_paid():
        return 'The payment for your order {order_id} has been processed'.format(order_id=order.id)

    elif order.is_canceled():
        return 'Your order {order_id} has been canceled'.format(order_id=order.id)

    elif order.is_shipping():
        return 'Your order {order_id} is shipping'.format(order_id=order.id)

    elif order.is_created():
        return 'Your order {order_id} has been created'.format(order_id=order.id)

    elif order.is_authorized():
        return 'Your order {order_id} is authorized'.format(order_id=order.id)

    elif order.is_refunded():
        return 'Your order {order_id} has been refunded'.format(order_id=order.id)

    elif order.is_expired():
        return 'Your order {order_id} has expired'.format(order_id=order.id)

    elif order.is_completed():
        return 'Your order {order_id} is completed'.format(order_id=order.id)

    else:
        return 'The status of your order {order_id} is: {status}'.format(order_id=order.id, status=order.status)
示例#48
0
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # Cancel the order.
        #
        # See: https://docs.mollie.com/reference/v2/orders-api/cancel-order
        #
        body = ''

        order_id = flask.request.args.get('order_id')

        if order_id is None:
            body += '<p>No order ID specified. Attempting to retrieve the first page of '
            body += 'orders and grabbing the first.</p>'

        order = mollie_client.orders.get(order_id) if order_id else next(mollie_client.orders.list())

        if order.is_cancelable:
            mollie_client.orders.delete(order.id)
            body += 'Your order {order_id} has been canceled'.format(order_id=order.id)

        else:
            body += 'Unable to cancel your order {order_id}'.format(order_id=order.id)

        return body

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#49
0
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # See: https://www.mollie.com/nl/docs/reference/customers/create
        #
        customer = mollie_client.customers.create({
            'name': 'Mr. First Customer',
            'email': '*****@*****.**',
            'locale': 'nl_NL'
        })

        return "Created new customer '{name}' ({email})".format(name=customer.name, email=customer.email)

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#50
0
def test_client_update_user_agent_component():
    """We should be able to update the User-Agent component when using the same key."""
    client = Client()
    client.set_user_agent_component('Test', '1.0.0')
    assert 'Test/1.0.0' in client.user_agent

    # now update the component using the same key
    client.set_user_agent_component('Test', '2.0.0')
    assert 'Test/2.0.0' in client.user_agent
    assert 'Test/1.0.0' not in client.user_agent

    # and update with a key that will be converted to the same value
    client.set_user_agent_component('TEST', '3.0.0')
    assert 'Test/3.0.0' in client.user_agent
    assert 'Test/2.0.0' not in client.user_agent
    assert 'Test/1.0.0' not in client.user_agent
示例#51
0
def test_client_invalid_api_key():
    """Setting up an invalid api key raises an error."""
    client = Client()

    with pytest.raises(RequestSetupError, match="Invalid API key: 'invalid'"):
        client.set_api_key('invalid')

    with pytest.raises(RequestSetupError, match="Invalid API key: 'access_123'"):
        client.set_api_key('access_123')

    with pytest.raises(RequestSetupError, match="Invalid access token: 'invalid'"):
        client.set_access_token('invalid')

    with pytest.raises(RequestSetupError, match="Invalid access token: 'live_123'"):
        client.set_access_token('live_123')

    with pytest.raises(RequestSetupError, match="Invalid access token: 'test_123'"):
        client.set_access_token('test_123')
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        amount_of_customers_to_retrieve = 20
        params = {
            'limit': amount_of_customers_to_retrieve,
        }

        #
        # Get the latest 20 customers
        #
        # See: https://www.mollie.com/nl/docs/reference/customers/list
        #
        customers = mollie_client.customers.list(**params)

        body = ''

        if not len(customers):
            body += '<p>You have no customers. You can create one from the examples.</p>'
            return body

        body += '<p>Showing the last {num} customers for your API key.</p>'.format(num=len(customers))

        body += """
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Payment creation</th>
                        <th>Payment History</th>
                    </tr>
                </thead>
                <tbody>
        """

        for customer in customers:
            body += '<tr>'
            body += '<td>{id}</td>'.format(id=customer.id)
            body += '<td>{name}</td>'.format(name=customer.name)
            body += '<td>{email}</td>'.format(email=customer.email)
            body += '<td><a href="/09-create-customer-payment?customer_id={id}">' \
                'Create payment for customer</a></td>'.format(id=customer.id)
            body += '<td><a href="/10-customer-payment-history?customer_id={id}">Show payment history</a>'.format(
                id=customer.id)
            body += '</tr>'

        body += "</tbody></table>"

        return body

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        #
        # First, let the customer pick the bank in a simple HTML form. This step is actually optional.
        #
        if 'issuer' not in flask.request.form:
            body = '<form method="post">Select your bank: <select name="issuer">'
            for issuer in mollie_client.methods.get('ideal', include='issuers').issuers:
                body += '<option value="{id}">{issuer}</option>'.format(id=issuer.id, issuer=issuer.name)
            body += '<option value="">or select later</option>'
            body += '</select><button>OK</button></form>'
            return body

        else:
            #
            # Get the posted issuer id.
            #
            issuer_id = None

            if flask.request.form['issuer']:
                issuer_id = str(flask.request.form['issuer'])

        #
        # Generate a unique webshop order id for this example. It is important to include this unique attribute
        # in the redirectUrl (below) so a proper return page can be shown to the customer.
        #
        my_webshop_id = int(time.time())

        #
        # Payment parameters:
        # amount        Currency and value. This example creates a € 10,- payment.
        # description   Description of the payment.
        # webhookUrl    Webhook location, used to report when the payment changes state.
        # redirectUrl   Redirect location. The customer will be redirected there after the payment.
        # metadata      Custom metadata that is stored with the payment.
        # method        Payment method "ideal".
        # issuer        The customer's bank. If empty the customer can select it later.
        #
        payment = mollie_client.payments.create({
            'amount': {
                'currency': 'EUR',
                'value': '10.00'
            },
            'description': 'My first API payment',
            'webhookUrl': '{root}02-webhook_verification'.format(root=flask.request.url_root),
            'redirectUrl': '{root}03-return-page?my_webshop_id={id}'.format(
                root=flask.request.url_root, id=my_webshop_id),
            'metadata': {
                'my_webshop_id': str(my_webshop_id),
            },
            'method': 'ideal',
            'issuer': issuer_id,
        })

        #
        # In this example we store the order with its payment status in a database.
        #
        data = {'status': payment.status}
        database_write(my_webshop_id, data)

        #
        # Send the customer off to complete the payment.
        #
        return flask.redirect(payment.checkout_url)

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#54
0
def test_client_user_agent_with_oauth():
    """When authenticating with an access token, the User-Agent should cont an OAuth component."""
    client = Client()
    assert 'OAuth'.lower() not in client.user_agent.lower()
    client.set_access_token('access_123')
    assert 'OAuth/2.0' in client.user_agent
示例#55
0
def main():
    try:
        #
        # Initialize the Mollie API library with your API key.
        #
        # See: https://www.mollie.com/dashboard/settings/profiles
        #
        api_key = os.environ.get('MOLLIE_API_KEY', 'test_test')
        mollie_client = Client()
        mollie_client.set_api_key(api_key)

        # Generate a unique webshop order id for this example.
        my_webshop_id = int(time.time())

        #
        # Order creation parameters.
        #
        # See: https://docs.mollie.com/reference/v2/orders-api/create-order
        #
        order = mollie_client.orders.create({
            'amount': {
                'value': '299.00',
                'currency': 'EUR'
            },
            'billingAddress': {
                'streetAndNumber': 'Keizersgracht 313',
                'city': 'Amsterdam',
                'region': 'Noord-Holland',
                'postalCode': '1234AB',
                'country': 'NL',
                'givenName': 'Piet',
                'familyName': 'Mondriaan',
                'email': '*****@*****.**',
            },
            'shippingAddress': {
                'streetAndNumber': 'Prinsengracht 313',
                'city': 'Haarlem',
                'region': 'Noord-Holland',
                'postalCode': '5678AB',
                'country': 'NL',
                'givenName': 'Chuck',
                'familyName': 'Norris',
                'email': '*****@*****.**'
            },
            'metadata': {
                'my_webshop_id': str(my_webshop_id),
                'description': 'Lego cars'
            },
            'consumerDateOfBirth': '1958-01-31',
            'locale': 'nl_NL',
            'orderNumber': '1337',
            'redirectUrl': '{root}17-order-return-page?my_webshop_id={id}'.format(root=flask.request.url_root,
                                                                                  id=my_webshop_id),
            'webhookUrl': '{root}13-order-webhook-verification'.format(root=flask.request.url_root),
            'lines': [
                {
                    'type': 'physical',
                    'sku': '5702016116977',
                    'name': 'LEGO 42083 Bugatti Chiron',
                    'productUrl': 'https://shop.lego.com/nl-NL/Bugatti-Chiron-42083',
                    'imageUrl': 'https://sh-s7-live-s.legocdn.com/is/image//LEGO/42083_alt1?$main$',
                    'quantity': 1,
                    'vatRate': '21.00',
                    'unitPrice': {
                        'currency': 'EUR',
                        'value': '399.00'
                    },
                    'totalAmount': {
                        'currency': 'EUR',
                        'value': '299.00'
                    },
                    'discountAmount': {
                        'currency': 'EUR',
                        'value': '100.00'
                    },
                    'vatAmount': {
                        'currency': 'EUR',
                        'value': '51.89'
                    }
                },

            ]
        })
        data = {'status': order.status, 'order_id': order.id}
        database_write(my_webshop_id, data)

        #
        # Send the customer off to complete the order payment.
        #
        return flask.redirect(order.checkout_url)

    except Error as err:
        return 'API call failed: {error}'.format(error=err)
示例#56
0
def test_client_set_user_agent_component_correct_value_syntax(value, expected):
    """When we receive UA component values that don't adhere to the proposed syntax, they are corrected."""
    client = Client()
    client.set_user_agent_component('Something', value)
    assert "Something/{expected}".format(expected=expected) in client.user_agent
示例#57
0
def test_client_set_user_agent_component_correct_key_syntax(key, expected):
    """When we receive UA component keys that don't adhere to the proposed syntax, they are corrected."""
    client = Client()
    client.set_user_agent_component(key, '1.0.0')
    assert "{expected}/1.0.0".format(expected=expected) in client.user_agent