def paypal_form_generate_values(self, values): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') paypal_tx_values = dict(values) paypal_tx_values.update({ 'cmd': '_xclick', 'business': self.paypal_email_account, 'item_name': '%s: %s' % (self.company_id.name, values['reference']), 'item_number': values['reference'], 'amount': values['amount'], 'currency_code': values['currency'] and values['currency'].name or '', 'address1': values.get('partner_address'), 'city': values.get('partner_city'), 'country': values.get('partner_country') and values.get('partner_country').code or '', 'state': values.get('partner_state') and (values.get('partner_state').code or values.get('partner_state').name) or '', 'email': values.get('partner_email'), 'zip_code': values.get('partner_zip'), 'first_name': values.get('partner_first_name'), 'last_name': values.get('partner_last_name'), 'paypal_return': urls.url_join(base_url, PaypalController._return_url), 'notify_url': urls.url_join(base_url, PaypalController._notify_url), 'cancel_return': urls.url_join(base_url, PaypalController._cancel_url), 'handling': '%.2f' % paypal_tx_values.pop('fees', 0.0) if self.fees_active else False, 'custom': json.dumps({'return_url': '%s' % paypal_tx_values.pop('return_url')}) if paypal_tx_values.get('return_url') else False, }) return paypal_tx_values
def _get_alipay_tx_values(self, values): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') alipay_tx_values = ({ '_input_charset': 'utf-8', 'notify_url': urls.url_join(base_url, AlipayController._notify_url), 'out_trade_no': values.get('reference'), 'partner': self.alipay_merchant_partner_id, 'return_url': urls.url_join(base_url, AlipayController._return_url), 'subject': values.get('reference'), 'total_fee': values.get('amount') + values.get('fees'), }) if self.alipay_payment_method == 'standard_checkout': alipay_tx_values.update({ 'service': 'create_forex_trade', 'product_code': 'NEW_OVERSEAS_SELLER', 'currency': values.get('currency').name, }) else: alipay_tx_values.update({ 'service': 'create_direct_pay_by_user', 'payment_type': 1, 'seller_email': self.alipay_seller_email, }) sign = self._build_sign(alipay_tx_values) alipay_tx_values.update({ 'sign_type': 'MD5', 'sign': sign, }) return alipay_tx_values
def ogone_form_generate_values(self, values): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') ogone_tx_values = dict(values) temp_ogone_tx_values = { 'PSPID': self.ogone_pspid, 'ORDERID': values['reference'], 'AMOUNT': float_repr(float_round(values['amount'], 2) * 100, 0), 'CURRENCY': values['currency'] and values['currency'].name or '', 'LANGUAGE': values.get('partner_lang'), 'CN': values.get('partner_name'), 'EMAIL': values.get('partner_email'), 'OWNERZIP': values.get('partner_zip'), 'OWNERADDRESS': values.get('partner_address'), 'OWNERTOWN': values.get('partner_city'), 'OWNERCTY': values.get('partner_country') and values.get('partner_country').code or '', 'OWNERTELNO': values.get('partner_phone'), 'ACCEPTURL': urls.url_join(base_url, OgoneController._accept_url), 'DECLINEURL': urls.url_join(base_url, OgoneController._decline_url), 'EXCEPTIONURL': urls.url_join(base_url, OgoneController._exception_url), 'CANCELURL': urls.url_join(base_url, OgoneController._cancel_url), 'PARAMPLUS': 'return_url=%s' % ogone_tx_values.pop('return_url') if ogone_tx_values.get('return_url') else False, } if self.save_token in ['ask', 'always']: temp_ogone_tx_values.update({ 'ALIAS': 'ODOO-NEW-ALIAS-%s' % time.time(), # something unique, 'ALIASUSAGE': values.get('alias_usage') or self.ogone_alias_usage, }) shasign = self._ogone_generate_shasign('in', temp_ogone_tx_values) temp_ogone_tx_values['SHASIGN'] = shasign ogone_tx_values.update(temp_ogone_tx_values) return ogone_tx_values
def ccavenue_form_generate_values(self, values): self.ensure_one() base_url = self.env['ir.config_parameter'].get_param('web.base.url') ccavenue_values = dict(access_code=self.ccavenue_access_code, merchant_id=self.ccavenue_merchant_id, order_id=values.get('reference'), currency=values.get('currency').name, amount=values.get('amount'), redirect_url=urls.url_join(base_url, CCAvenueController._return_url), cancel_url=urls.url_join(base_url, CCAvenueController._cancel_url), language='EN', customer_identifier=values.get('partner_email'), delivery_name=values.get('partner_name'), delivery_address=values.get('partner_address'), delivery_city=values.get('partner_city'), delivery_state=values.get('partner_state').name, delivery_zip=values.get('partner_zip'), delivery_country=values.get('partner_country').name, delivery_tel=values.get('partner_phone'), billing_name=values.get('billing_partner_name'), billing_address=values.get('billing_partner_address'), billing_city=values.get('billing_partner_city'), billing_state=values.get('billing_partner_state').name, billing_zip=values.get('billing_partner_zip'), billing_country=values.get('billing_partner_country').name, billing_tel=values.get('billing_partner_phone'), billing_email=values.get('billing_partner_email'), ) ccavenue_values['encRequest'] = self._ccavenue_encrypt_text(urls.url_encode(ccavenue_values)) return ccavenue_values
def test_10_Authorize_form_render(self): self.assertEqual(self.authorize.environment, 'test', 'test without test environment') # ---------------------------------------- # Test: button direct rendering # ---------------------------------------- base_url = self.env['ir.config_parameter'].get_param('web.base.url') form_values = { 'x_login': self.authorize.authorize_login, 'x_trans_key': self.authorize.authorize_transaction_key, 'x_amount': '320.0', 'x_show_form': 'PAYMENT_FORM', 'x_type': 'AUTH_CAPTURE', 'x_method': 'CC', 'x_fp_sequence': '%s%s' % (self.authorize.id, int(time.time())), 'x_version': '3.1', 'x_relay_response': 'TRUE', 'x_fp_timestamp': str(int(time.time())), 'x_relay_url': urls.url_join(base_url, AuthorizeController._return_url), 'x_cancel_url': urls.url_join(base_url, AuthorizeController._cancel_url), 'return_url': None, 'x_currency_code': 'USD', 'x_invoice_num': 'SO004', 'x_first_name': 'Norbert', 'x_last_name': 'Buyer', 'x_address': 'Huge Street 2/543', 'x_city': 'Sin City', 'x_zip': '1000', 'x_country': 'Belgium', 'x_phone': '0032 12 34 56 78', 'x_email': '*****@*****.**', 'x_state': None, 'x_ship_to_first_name': 'Norbert', 'x_ship_to_last_name': 'Buyer', 'x_ship_to_address': 'Huge Street 2/543', 'x_ship_to_city': 'Sin City', 'x_ship_to_zip': '1000', 'x_ship_to_country': 'Belgium', 'x_ship_to_phone': '0032 12 34 56 78', 'x_ship_to_email': '*****@*****.**', 'x_ship_to_state': None, } form_values['x_fp_hash'] = self._authorize_generate_hashing(form_values) # render the button res = self.authorize.render('SO004', 320.0, self.currency_usd.id, values=self.buyer_values) # check form result tree = objectify.fromstring(res) self.assertEqual(tree.get('action'), 'https://test.authorize.net/gateway/transact.dll', 'Authorize: wrong form POST url') for el in tree.iterfind('input'): values = list(pycompat.values(el.attrib)) if values[1] in ['submit', 'x_fp_hash', 'return_url', 'x_state', 'x_ship_to_state']: continue self.assertEqual( unicode(values[2], "utf-8"), form_values[values[1]], 'Authorize: wrong value for input %s: received %s instead of %s' % (values[1], values[2], form_values[values[1]]) )
def _compute_survey_url(self): """ Computes a public URL for the survey """ base_url = '/' if self.env.context.get('relative_url') else \ self.env['ir.config_parameter'].sudo().get_param('web.base.url') for survey in self: survey.public_url = urls.url_join(base_url, "survey/start/%s" % (slug(survey))) survey.print_url = urls.url_join(base_url, "survey/print/%s" % (slug(survey))) survey.result_url = urls.url_join(base_url, "survey/results/%s" % (slug(survey))) survey.public_url_html = '<a href="%s">%s</a>' % (survey.public_url, _("Click here to start survey"))
def test_url_joining(self): self.assert_strict_equal(urls.url_join('/foo', '/bar'), '/bar') self.assert_strict_equal(urls.url_join('http://example.com/foo', '/bar'), 'http://example.com/bar') self.assert_strict_equal(urls.url_join('file:///tmp/', 'test.html'), 'file:///tmp/test.html') self.assert_strict_equal(urls.url_join('file:///tmp/x', 'test.html'), 'file:///tmp/test.html') self.assert_strict_equal(urls.url_join('file:///tmp/x', '../../../x.html'), 'file:///x.html')
def test_url_joining(): strict_eq(urls.url_join('/foo', '/bar'), '/bar') strict_eq(urls.url_join('http://example.com/foo', '/bar'), 'http://example.com/bar') strict_eq(urls.url_join('file:///tmp/', 'test.html'), 'file:///tmp/test.html') strict_eq(urls.url_join('file:///tmp/x', 'test.html'), 'file:///tmp/test.html') strict_eq(urls.url_join('file:///tmp/x', '../../../x.html'), 'file:///x.html')
def init_restful(self, api, prefix='/api/multimedia/image/'): """Set up the urls. :param str prefix: the url perfix .. note:: In IIIF Image API the Image Request URI Syntax must following ``{scheme}://{server}{/prefix}/{identifier}/ {region}/{size}/{rotation}/{quality}.{format}`` pattern, the default prefix is ``/api/multimedia/image`` but this can be changes by changing the ``prefix`` paremeter. The ``prefix`` MUST always start and end with `/` .. seealso:: `IIIF IMAGE API URI Syntax <http://iiif.io/api/image/2.0/#uri-syntax>` """ from .restful import IIIFImageAPI, IIIFImageInfo, IIIFImageBase if not prefix.startswith('/') or not prefix.endswith('/'): raise RuntimeError( "The `prefix` must always start and end with `/`" ) api.add_resource( IIIFImageAPI, url_join( prefix, ( "<string:version>/<string:uuid>/" "<string:region>/<string:size>/<string:rotation>/" "<string:quality>.<string:image_format>" ) ) ) api.add_resource( IIIFImageInfo, url_join( prefix, "<string:version>/<string:uuid>/info.json" ) ) api.add_resource( IIIFImageBase, url_join( prefix, "<string:version>/<string:uuid>" ) )
def authorize_form_generate_values(self, values): self.ensure_one() # State code is only supported in US, use state name by default # See https://developer.authorize.net/api/reference/ state = values['partner_state'].name if values.get('partner_state') else '' if values.get('partner_country') and values.get('partner_country') == self.env.ref('base.us', False): state = values['partner_state'].code if values.get('partner_state') else '' billing_state = values['billing_partner_state'].name if values.get('billing_partner_state') else '' if values.get('billing_partner_country') and values.get('billing_partner_country') == self.env.ref('base.us', False): billing_state = values['billing_partner_state'].code if values.get('billing_partner_state') else '' base_url = self.env['ir.config_parameter'].get_param('web.base.url') authorize_tx_values = dict(values) temp_authorize_tx_values = { 'x_login': self.authorize_login, 'x_trans_key': self.authorize_transaction_key, 'x_amount': float_repr(values['amount'], values['currency'].decimal_places if values['currency'] else 2), 'x_show_form': 'PAYMENT_FORM', 'x_type': 'AUTH_CAPTURE' if not self.capture_manually else 'AUTH_ONLY', 'x_method': 'CC', 'x_fp_sequence': '%s%s' % (self.id, int(time.time())), 'x_version': '3.1', 'x_relay_response': 'TRUE', 'x_fp_timestamp': str(int(time.time())), 'x_relay_url': urls.url_join(base_url, AuthorizeController._return_url), 'x_cancel_url': urls.url_join(base_url, AuthorizeController._cancel_url), 'x_currency_code': values['currency'] and values['currency'].name or '', 'address': values.get('partner_address'), 'city': values.get('partner_city'), 'country': values.get('partner_country') and values.get('partner_country').name or '', 'email': values.get('partner_email'), 'zip_code': values.get('partner_zip'), 'first_name': values.get('partner_first_name'), 'last_name': values.get('partner_last_name'), 'phone': values.get('partner_phone'), 'state': state, 'billing_address': values.get('billing_partner_address'), 'billing_city': values.get('billing_partner_city'), 'billing_country': values.get('billing_partner_country') and values.get('billing_partner_country').name or '', 'billing_email': values.get('billing_partner_email'), 'billing_zip_code': values.get('billing_partner_zip'), 'billing_first_name': values.get('billing_partner_first_name'), 'billing_last_name': values.get('billing_partner_last_name'), 'billing_phone': values.get('billing_partner_phone'), 'billing_state': billing_state, } temp_authorize_tx_values['returndata'] = authorize_tx_values.pop('return_url', '') temp_authorize_tx_values['x_fp_hash'] = self._authorize_generate_hashing(temp_authorize_tx_values) temp_authorize_tx_values.pop('x_trans_key') # We remove this value since it is secret and isn't needed on the form authorize_tx_values.update(temp_authorize_tx_values) return authorize_tx_values
def test_10_paypal_form_render(self): base_url = self.env['ir.config_parameter'].get_param('web.base.url') # be sure not to do stupid things self.paypal.write({'paypal_email_account': '*****@*****.**', 'fees_active': False}) self.assertEqual(self.paypal.environment, 'test', 'test without test environment') # ---------------------------------------- # Test: button direct rendering # ---------------------------------------- # render the button res = self.paypal.render( 'test_ref0', 0.01, self.currency_euro.id, values=self.buyer_values) form_values = { 'cmd': '_xclick', 'business': '*****@*****.**', 'item_name': '%s: test_ref0' % (self.paypal.company_id.name), 'item_number': 'test_ref0', 'first_name': 'Norbert', 'last_name': 'Buyer', 'amount': '0.01', 'currency_code': 'EUR', 'address1': 'Huge Street 2/543', 'city': 'Sin City', 'zip': '1000', 'country': 'BE', 'email': '*****@*****.**', 'return': urls.url_join(base_url, PaypalController._return_url), 'notify_url': urls.url_join(base_url, PaypalController._notify_url), 'cancel_return': urls.url_join(base_url, PaypalController._cancel_url), 'custom': '{"return_url": "/payment/process"}', } # check form result tree = objectify.fromstring(res) data_set = tree.xpath("//input[@name='data_set']") self.assertEqual(len(data_set), 1, 'paypal: Found %d "data_set" input instead of 1' % len(data_set)) self.assertEqual(data_set[0].get('data-action-url'), 'https://www.sandbox.paypal.com/cgi-bin/webscr', 'paypal: wrong form POST url') for form_input in tree.input: if form_input.get('name') in ['submit', 'data_set']: continue self.assertEqual( form_input.get('value'), form_values[form_input.get('name')], 'paypal: wrong value for input %s: received %s instead of %s' % (form_input.get('name'), form_input.get('value'), form_values[form_input.get('name')]) )
def test_10_alipay_form_render(self): base_url = self.env['ir.config_parameter'].get_param('web.base.url') self.assertEqual(self.alipay.environment, 'test', 'test without test environment') # ---------------------------------------- # Test: button direct rendering # ---------------------------------------- # render the button res = self.alipay.render( 'test_ref0', 0.01, self.currency_euro.id, values=self.buyer_values) form_values = { '_input_charset': 'utf-8', 'notify_url': urls.url_join(base_url, AlipayController._notify_url), 'out_trade_no': 'SO12345-1', 'partner': self.alipay.alipay_merchant_partner_id, 'return_url': urls.url_join(base_url, AlipayController._return_url) + '?' + urls.url_encode({'redirect_url': '/payment/process'}), 'subject': 'test_ref0', 'total_fee': '0.01', } if self.alipay.alipay_payment_method == 'standard_checkout': form_values.update({ 'service': 'create_forex_trade', 'currency': 'EUR', 'product_code': 'NEW_OVERSEAS_SELLER', }) else: form_values.update({ 'payment_type': '1', 'seller_email': self.alipay.alipay_seller_email, 'service': 'create_direct_pay_by_user' }) sign = self.alipay._build_sign(form_values) form_values.update({'sign': sign, 'sign_type': 'MD5'}) # check form result tree = objectify.fromstring(res) data_set = tree.xpath("//input[@name='data_set']") self.assertEqual(len(data_set), 1, 'Alipay: Found %d "data_set" input instead of 1' % len(data_set)) self.assertEqual(data_set[0].get('data-action-url'), 'https://openapi.alipaydev.com/gateway.do', 'alipay: wrong form POST url') for form_input in tree.input: if form_input.get('name') in ['submit', 'data_set', 'sign', 'out_trade_no']: continue self.assertEqual(form_input.get('value'), form_values[form_input.get('name')], 'alipay: wrong value for input %s: received %s instead of %s' % (form_input.get('name'), form_input.get('value'), form_values[form_input.get('name')]))
def url_for(endpoint, **values): if endpoint == 'admin.static': filename = values.pop('filename') query = url_encode(values) url_prefix = current_app.config['ADMIN_STATIC_URL'] return '{}?{}'.format(url_join(url_prefix, filename), query) return flask_url_for(endpoint, **values)
def test_08_survey_urls(self): def validate_url(url): """ Reference: https://github.com/django/django/blob/master/django/core/validators.py """ url_regex = re.compile( r'^https?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$', re.IGNORECASE) return True if url_regex.match(url) else False base_url = self.env['ir.config_parameter'].get_param('web.base.url') urltypes = {'public': 'start', 'print': 'print', 'result': 'results'} for urltype, urltxt in pycompat.items(urltypes): survey_url = getattr(self.survey1, urltype + '_url') survey_url_relative = getattr(self.survey1.with_context({'relative_url': True}), urltype + '_url') self.assertTrue(validate_url(survey_url)) url = "survey/%s/%s" % (urltxt, slug(self.survey1)) full_url = urls.url_join(base_url, url) self.assertEqual(full_url, survey_url) self.assertEqual('/' + url, survey_url_relative) if urltype == 'public': url_html = '<a href="%s">Click here to start survey</a>' self.assertEqual(url_html % full_url, getattr(self.survey1, urltype + '_url_html'), msg="Public URL is incorrect") self.assertEqual(url_html % ('/' + url), getattr(self.survey1.with_context({'relative_url': True}), urltype + '_url_html'), msg="Public URL is incorrect.")
def _compute_website_url(self, website_path, xml_id): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') link = website_path or xml_id or (self.id and '%d' % self.id) or '' if base_url and link: path = '%s/%s' % ('/website/action', link) return urls.url_join(base_url, path) return ''
def url_for(path_or_uri, lang=None): if isinstance(path_or_uri, unicode): path_or_uri = path_or_uri.encode('utf-8') current_path = request.httprequest.path if isinstance(current_path, unicode): current_path = current_path.encode('utf-8') location = path_or_uri.strip() force_lang = lang is not None url = urls.url_parse(location) if request and not url.netloc and not url.scheme and (url.path or force_lang): location = urls.url_join(current_path, location) lang = lang or request.context.get('lang') langs = [lg[0] for lg in request.website.get_languages()] if (len(langs) > 1 or force_lang) and is_multilang_url(location, langs): ps = location.split('/') if ps[1] in langs: # Replace the language only if we explicitly provide a language to url_for if force_lang: ps[1] = lang.encode('utf-8') # Remove the default language unless it's explicitly provided elif ps[1] == request.website.default_lang_code: ps.pop(1) # Insert the context language or the provided language elif lang != request.website.default_lang_code or force_lang: ps.insert(1, lang.encode('utf-8')) location = '/'.join(ps) return location.decode('utf-8')
def _send_confirmation_email(self, partner_ids, unsubscribe=False): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') route = "/groups/%(action)s/%(channel)s/%(partner)s/%(token)s" if unsubscribe: template = self.env.ref('website_mail_channel.mail_template_list_unsubscribe') action = 'unsubscribe' else: template = self.env.ref('website_mail_channel.mail_template_list_subscribe') action = 'subscribe' for partner_id in partner_ids: # generate a new token per subscriber token = self._generate_action_token(partner_id, action=action) token_url = urls.url_join(base_url, route % { 'action': action, 'channel': self.id, 'partner': partner_id, 'token': token, }) template.with_context(token_url=token_url).send_mail(self.id, force_send=True, email_values={'recipient_ids': [(4, partner_id)]} ) return True
def _rebuild(self): # url_for already creates an absolute url (e.g. /indico/whatever) but since it starts # with a slash this is not a problem. It overwrites the path part in baseURL but it's # the same one. maybe we could even get rid of the baseURL stuff at some point... It's # only really important when we change from SSL to non-SSL or vice versa anyway anchor = self.fragment or None self._url = url_join(self._base_url, _url_for(self._endpoint, _anchor=anchor, **self._get_fixed_params()))
def make_absolute_url(self, url): """Given a URL this makes it absolute if this is possible.""" base_url = self.db.config['SITE'].get('url') if base_url is None: raise RuntimeError('To use absolute URLs you need to configure ' 'the URL in the project config.') return url_join(base_url.rstrip('/') + '/', url.lstrip('/'))
def parse_meta(content, link=None): """Parse og information from HTML content. :param content: HTML content to be parsed. unicode required. """ head = content.split(u'</head>', 1)[0] pairs = {} def parse_pair(kv): name = kv.get(u'name') if not name: name = kv.get(u'property') if not name: return if name in pairs: return content = kv.get(u'content') if not content: return pairs[name] = content for text in META_TAG.findall(head): kv = META_ATTR.findall(text) if kv: parse_pair(dict(kv)) rv = {} def get_og_value(key): for name in [u'og:%s' % key, u'twitter:%s' % key]: if name in pairs: rv[key] = pairs[name] for key in [u'title', u'image', u'description', u'url']: get_og_value(key) if u'twitter:creator' in pairs: rv[u'twitter'] = pairs[u'twitter:creator'] if u'title' not in rv: m = TITLE.findall(head) if m: rv[u'title'] = m[0] if u'description' not in rv: desc = rv.get(u'description') if desc: rv[u'description'] = desc # format absolute link if link and u'image' in rv: rv[u'image'] = url_join(link, rv[u'image']) rv.update(parse_embed(pairs)) for key in [u'title', u'description']: if rv.get(key): rv[key] = unescape(rv[key]) return rv
def jquery_url(app, jquery_path): app.register_blueprint(Blueprint( 'jquery', __name__, static_folder='jquery', static_url_path='/static/jquery' )) return url_join( 'http://localhost:5000/static/jquery/', os.path.basename(jquery_path) )
def get_cdn_url(self, uri): # Currently only usable in a website_enable request context if request and request.website and not request.debug and request.website.user_id.id == request.uid: cdn_url = request.website.cdn_url cdn_filters = (request.website.cdn_filters or '').splitlines() for flt in cdn_filters: if flt and re.match(flt, uri): return urls.url_join(cdn_url, uri) return uri
def buckaroo_form_generate_values(self, values): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') buckaroo_tx_values = dict(values) buckaroo_tx_values.update({ 'Brq_websitekey': self.brq_websitekey, 'Brq_amount': values['amount'], 'Brq_currency': values['currency'] and values['currency'].name or '', 'Brq_invoicenumber': values['reference'], 'brq_test': False if self.environment == 'prod' else True, 'Brq_return': urls.url_join(base_url, BuckarooController._return_url), 'Brq_returncancel': urls.url_join(base_url, BuckarooController._cancel_url), 'Brq_returnerror': urls.url_join(base_url, BuckarooController._exception_url), 'Brq_returnreject': urls.url_join(base_url, BuckarooController._reject_url), 'Brq_culture': (values.get('partner_lang') or 'en_US').replace('_', '-'), 'add_returndata': buckaroo_tx_values.pop('return_url', '') or '', }) buckaroo_tx_values['Brq_signature'] = self._buckaroo_generate_digital_sign('in', buckaroo_tx_values) return buckaroo_tx_values
def get_cdn_url(self, uri): self.ensure_one() if not uri: return '' cdn_url = self.cdn_url cdn_filters = (self.cdn_filters or '').splitlines() for flt in cdn_filters: if flt and re.match(flt, uri): return urls.url_join(cdn_url, uri) return uri
def _compute_url(self): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') for source in self: source.url = urls.url_join(base_url, "%s?%s" % (source.job_id.website_url, urls.url_encode({ 'utm_campaign': self.env.ref('hr_recruitment.utm_campaign_job').name, 'utm_medium': self.env.ref('utm.utm_medium_website').name, 'utm_source': source.source_id.name }) ))
def adyen_form_generate_values(self, values): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') # tmp import datetime from dateutil import relativedelta if self.provider == 'adyen' and len(self.adyen_skin_hmac_key) == 64: tmp_date = datetime.datetime.today() + relativedelta.relativedelta(days=1) values.update({ 'merchantReference': values['reference'], 'paymentAmount': '%d' % int(tools.float_round(values['amount'], 2) * 100), 'currencyCode': values['currency'] and values['currency'].name or '', 'shipBeforeDate': tmp_date.strftime('%Y-%m-%d'), 'skinCode': self.adyen_skin_code, 'merchantAccount': self.adyen_merchant_account, 'shopperLocale': values.get('partner_lang', ''), 'sessionValidity': tmp_date.isoformat('T')[:19] + "Z", 'resURL': urls.url_join(base_url, AdyenController._return_url), 'merchantReturnData': json.dumps({'return_url': '%s' % values.pop('return_url')}) if values.get('return_url', '') else False, 'shopperEmail': values.get('partner_email', ''), }) values['merchantSig'] = self._adyen_generate_merchant_sig_sha256('in', values) else: tmp_date = datetime.date.today() + relativedelta.relativedelta(days=1) values.update({ 'merchantReference': values['reference'], 'paymentAmount': '%d' % int(tools.float_round(values['amount'], 2) * 100), 'currencyCode': values['currency'] and values['currency'].name or '', 'shipBeforeDate': tmp_date, 'skinCode': self.adyen_skin_code, 'merchantAccount': self.adyen_merchant_account, 'shopperLocale': values.get('partner_lang'), 'sessionValidity': tmp_date, 'resURL': urls.url_join(base_url, AdyenController._return_url), 'merchantReturnData': json.dumps({'return_url': '%s' % values.pop('return_url')}) if values.get('return_url') else False, 'merchantSig': self._adyen_generate_merchant_sig('in', values), }) return values
def authorize_form_feedback(self, **post): _logger.info('Authorize: entering form_feedback with post data %s', pprint.pformat(post)) if post: request.env['payment.transaction'].sudo().form_feedback(post, 'authorize') base_url = request.env['ir.config_parameter'].sudo().get_param('web.base.url') # Authorize.Net is expecting a response to the POST sent by their server. # This response is in the form of a URL that Authorize.Net will pass on to the # client's browser to redirect them to the desired location need javascript. return request.render('payment_authorize.payment_authorize_redirect', { 'return_url': urls.url_join(base_url, "/payment/process") })
def payumoney_form_generate_values(self, values): self.ensure_one() base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') payumoney_values = dict(values, key=self.payumoney_merchant_key, txnid=values['reference'], amount=values['amount'], productinfo=values['reference'], firstname=values.get('partner_name'), email=values.get('partner_email'), phone=values.get('partner_phone'), service_provider='payu_paisa', surl=urls.url_join(base_url, '/payment/payumoney/return'), furl=urls.url_join(base_url, '/payment/payumoney/error'), curl=urls.url_join(base_url, '/payment/payumoney/cancel') ) payumoney_values['udf1'] = payumoney_values.pop('return_url', '/') payumoney_values['hash'] = self._payumoney_generate_sign('in', payumoney_values) return payumoney_values
def authorize_form_generate_values(self, values): self.ensure_one() base_url = self.env['ir.config_parameter'].get_param('web.base.url') authorize_tx_values = dict(values) temp_authorize_tx_values = { 'x_login': self.authorize_login, 'x_trans_key': self.authorize_transaction_key, 'x_amount': str(values['amount']), 'x_show_form': 'PAYMENT_FORM', 'x_type': 'AUTH_CAPTURE' if not self.capture_manually else 'AUTH_ONLY', 'x_method': 'CC', 'x_fp_sequence': '%s%s' % (self.id, int(time.time())), 'x_version': '3.1', 'x_relay_response': 'TRUE', 'x_fp_timestamp': str(int(time.time())), 'x_relay_url': urls.url_join(base_url, AuthorizeController._return_url), 'x_cancel_url': urls.url_join(base_url, AuthorizeController._cancel_url), 'x_currency_code': values['currency'] and values['currency'].name or '', 'address': values.get('partner_address'), 'city': values.get('partner_city'), 'country': values.get('partner_country') and values.get('partner_country').name or '', 'email': values.get('partner_email'), 'zip_code': values.get('partner_zip'), 'first_name': values.get('partner_first_name'), 'last_name': values.get('partner_last_name'), 'phone': values.get('partner_phone'), 'state': values.get('partner_state') and values['partner_state'].code or '', 'billing_address': values.get('billing_partner_address'), 'billing_city': values.get('billing_partner_city'), 'billing_country': values.get('billing_partner_country') and values.get('billing_partner_country').name or '', 'billing_email': values.get('billing_partner_email'), 'billing_zip_code': values.get('billing_partner_zip'), 'billing_first_name': values.get('billing_partner_first_name'), 'billing_last_name': values.get('billing_partner_last_name'), 'billing_phone': values.get('billing_partner_phone'), 'billing_state': values.get('billing_partner_state') and values['billing_partner_state'].code or '', } temp_authorize_tx_values['returndata'] = authorize_tx_values.pop('return_url', '') temp_authorize_tx_values['x_fp_hash'] = self._authorize_generate_hashing(temp_authorize_tx_values) authorize_tx_values.update(temp_authorize_tx_values) return authorize_tx_values
def _get_cephalopod_data(self): if not cephalopod_settings.get('joined'): return None, {'enabled': False} url = url_join(config.COMMUNITY_HUB_URL, 'api/instance/{}'.format(cephalopod_settings.get('uuid'))) data = {'enabled': cephalopod_settings.get('joined'), 'contact': cephalopod_settings.get('contact_name'), 'email': cephalopod_settings.get('contact_email'), 'url': config.BASE_URL, 'organization': core_settings.get('site_organization')} return url, data
def adyen_payments(self, acquirer_id, reference, converted_amount, currency_id, partner_id, payment_method, access_token, browser_info=None): """ Make a payment request and handle the response. :param int acquirer_id: The acquirer handling the transaction, as a `payment.acquirer` id :param str reference: The reference of the transaction :param int converted_amount: The amount of the transaction in minor units of the currency :param int currency_id: The currency of the transaction, as a `res.currency` id :param int partner_id: The partner making the transaction, as a `res.partner` id :param dict payment_method: The details of the payment method used for the transaction :param str access_token: The access token used to verify the provided values :param dict browser_info: The browser info to pass to Adyen :return: The JSON-formatted content of the response :rtype: dict """ # Check that the transaction details have not been altered. This allows preventing users # from validating transactions by paying less than agreed upon. if not payment_utils.check_access_token(access_token, reference, converted_amount, partner_id): raise ValidationError("Adyen: " + _("Received tampered payment request data.")) # Make the payment request to Adyen acquirer_sudo = request.env['payment.acquirer'].sudo().browse( acquirer_id).exists() tx_sudo = request.env['payment.transaction'].sudo().search([ ('reference', '=', reference) ]) data = { 'merchantAccount': acquirer_sudo.adyen_merchant_account, 'amount': { 'value': converted_amount, 'currency': request.env['res.currency'].browse( currency_id).name, # ISO 4217 }, 'reference': reference, 'paymentMethod': payment_method, 'shopperReference': acquirer_sudo._adyen_compute_shopper_reference(partner_id), 'recurringProcessingModel': 'CardOnFile', # Most susceptible to trigger a 3DS check 'shopperIP': payment_utils.get_customer_ip_address(), 'shopperInteraction': 'Ecommerce', 'storePaymentMethod': tx_sudo.tokenize, # True by default on Adyen side 'additionalData': { 'allow3DS2': True }, 'channel': 'web', # Required to support 3DS 'origin': acquirer_sudo.get_base_url(), # Required to support 3DS 'browserInfo': browser_info, # Required to support 3DS 'returnUrl': urls.url_join( acquirer_sudo.get_base_url(), # Include the reference in the return url to be able to match it after redirection. # The key 'merchantReference' is chosen on purpose to be the same than that returned # by the /payments endpoint of Adyen. f'/payment/adyen/return?merchantReference={reference}'), } response_content = acquirer_sudo._adyen_make_request( url_field_name='adyen_checkout_api_url', endpoint='/payments', payload=data, method='POST') # Handle the payment request response _logger.info("payment request response:\n%s", pprint.pformat(response_content)) request.env['payment.transaction'].sudo()._handle_feedback_data( 'adyen', dict(response_content, merchantReference=reference), # Match the transaction ) if 'action' in response_content and response_content['action'][ 'type'] == 'redirect': tx_sudo.adyen_payment_data = response_content['paymentData'] return response_content
def _compute_survey_url(self): """ Computes a public URL for the survey """ base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') for survey in self: survey.public_url = urls.url_join(base_url, "survey/start/%s" % (survey.access_token))
def get_callback(self): base_url = self.get_base_url() return urls.url_join(base_url, PosMpesaController._callback_url)
def test_regular_track(self): """ Check that push reminders are sent to attendees that have wishlisted the track. """ [track_1, track_2] = self.env['event.track'].create([{ 'name': 'Track 1', 'event_id': self.event_0.id, 'date': fields.Datetime.now() + relativedelta(hours=2), }, { 'name': 'Track 2', 'event_id': self.event_0.id, 'date': fields.Datetime.now() + relativedelta(hours=2), }]) visitors_track_1 = self.env['website.visitor'].create([{ 'name': 'Wishlisting Visitor 1', 'event_track_visitor_ids': [(0, 0, { 'is_wishlisted': True, 'track_id': track_1.id })], 'push_token': 'AAAAAA', 'event_registration_ids': [(0, 0, { 'event_id': self.event_0.id })] }, { 'name': 'Wishlisting Visitor 2', 'event_track_visitor_ids': [(0, 0, { 'is_wishlisted': True, 'track_id': track_1.id })], 'push_token': 'BBBBBB', 'event_registration_ids': [(0, 0, { 'event_id': self.event_0.id })] }]) self.env['website.visitor'].create({ 'name': 'Wishlisting Visitor 3', 'event_track_visitor_ids': [(0, 0, { 'is_wishlisted': True, 'track_id': track_2.id })], 'push_token': 'AAAAAA', 'event_registration_ids': [(0, 0, { 'event_id': self.event_0.id })] }) track_1.write({ 'push_reminder': True, 'push_reminder_delay': 10 }) track_1.flush(['push_reminder']) track_2.write({'push_reminder': True}) track_2.flush(['push_reminder']) push_reminder = self.env['social.post'].search([('event_track_id', '=', track_1.id)]) self.assertTrue(bool(push_reminder)) self.assertEqual("Your wishlisted track 'Track 1' will start in 10 minutes!", push_reminder.message) self.assertEqual( url_join(track_1.event_id.get_base_url(), track_1.website_url), push_reminder.push_notification_target_url) self.assertEqual('scheduled', push_reminder.post_method) self.assertEqual(False, push_reminder.use_visitor_timezone) self.assertEqual(track_1.date - relativedelta(minutes=10), push_reminder.scheduled_date) targeted_visitors = self.env['website.visitor'].search(literal_eval(push_reminder.visitor_domain)) self.assertEqual(targeted_visitors, visitors_track_1) track_1.write({ 'name': 'New Name', 'push_reminder_delay': 20, 'date': fields.Datetime.now() + relativedelta(hours=3) }) track_1.flush(['name', 'date']) push_reminder = self.env['social.post'].search([('event_track_id', '=', track_1.id)]) self.assertEqual("Your wishlisted track 'New Name' will start in 20 minutes!", push_reminder.message) self.assertEqual(track_1.date - relativedelta(minutes=20), push_reminder.scheduled_date) track_1.write({'push_reminder': False}) track_1.flush(['push_reminder']) push_reminder = self.env['social.post'].search([('event_track_id', '=', track_1.id)]) self.assertFalse(bool(push_reminder))
def authorize_form_generate_values(self, values): self.ensure_one() # State code is only supported in US, use state name by default # See https://developer.authorize.net/api/reference/ state = values['partner_state'].name if values.get( 'partner_state') else '' if values.get('partner_country') and values.get( 'partner_country') == self.env.ref('base.us', False): state = values['partner_state'].code if values.get( 'partner_state') else '' billing_state = values['billing_partner_state'].name if values.get( 'billing_partner_state') else '' if values.get('billing_partner_country') and values.get( 'billing_partner_country') == self.env.ref('base.us', False): billing_state = values['billing_partner_state'].code if values.get( 'billing_partner_state') else '' base_url = self.env['ir.config_parameter'].get_param('web.base.url') authorize_tx_values = dict(values) temp_authorize_tx_values = { 'x_login': self.authorize_login, 'x_amount': float_repr( values['amount'], values['currency'].decimal_places if values['currency'] else 2), 'x_show_form': 'PAYMENT_FORM', 'x_type': 'AUTH_CAPTURE' if not self.capture_manually else 'AUTH_ONLY', 'x_method': 'CC', 'x_fp_sequence': '%s%s' % (self.id, int(time.time())), 'x_version': '3.1', 'x_relay_response': 'TRUE', 'x_fp_timestamp': str(int(time.time())), 'x_relay_url': urls.url_join(base_url, AuthorizeController._return_url), 'x_cancel_url': urls.url_join(base_url, AuthorizeController._cancel_url), 'x_currency_code': values['currency'] and values['currency'].name or '', 'address': values.get('partner_address'), 'city': values.get('partner_city'), 'country': values.get('partner_country') and values.get('partner_country').name or '', 'email': values.get('partner_email'), 'zip_code': values.get('partner_zip'), 'first_name': values.get('partner_first_name'), 'last_name': values.get('partner_last_name'), 'phone': values.get('partner_phone'), 'state': state, 'billing_address': values.get('billing_partner_address'), 'billing_city': values.get('billing_partner_city'), 'billing_country': values.get('billing_partner_country') and values.get('billing_partner_country').name or '', 'billing_email': values.get('billing_partner_email'), 'billing_zip_code': values.get('billing_partner_zip'), 'billing_first_name': values.get('billing_partner_first_name'), 'billing_last_name': values.get('billing_partner_last_name'), 'billing_phone': values.get('billing_partner_phone'), 'billing_state': billing_state, } temp_authorize_tx_values['returndata'] = authorize_tx_values.pop( 'return_url', '') temp_authorize_tx_values[ 'x_fp_hash'] = self._authorize_generate_hashing( temp_authorize_tx_values) authorize_tx_values.update(temp_authorize_tx_values) return authorize_tx_values
def mscolab_register_user(app, msc_url, email, password, username): # Duplicate of imported register_user data = {'email': email, 'password': password, 'username': username} url = url_join(msc_url, 'register') response = app.test_client().post(url, data=data) return response
def test_10_paypal_form_render(self): base_url = self.env['ir.config_parameter'].get_param('web.base.url') # be sure not to do stupid things self.paypal.write({ 'paypal_email_account': '*****@*****.**', 'fees_active': False }) self.assertEqual(self.paypal.environment, 'test', 'test without test environment') # ---------------------------------------- # Test: button direct rendering # ---------------------------------------- # render the button res = self.paypal.render('test_ref0', 0.01, self.currency_euro.id, values=self.buyer_values) form_values = { 'cmd': '_xclick', 'business': '*****@*****.**', 'item_name': '%s: test_ref0' % (self.paypal.company_id.name), 'item_number': 'test_ref0', 'first_name': 'Norbert', 'last_name': 'Buyer', 'amount': '0.01', 'currency_code': 'EUR', 'address1': 'Huge Street 2/543', 'city': 'Sin City', 'zip': '1000', 'rm': '2', 'country': 'BE', 'email': '*****@*****.**', 'return': urls.url_join(base_url, PaypalController._return_url), 'notify_url': urls.url_join(base_url, PaypalController._notify_url), 'cancel_return': urls.url_join(base_url, PaypalController._cancel_url), 'custom': '{"return_url": "/payment/process"}', } # check form result tree = objectify.fromstring(res) data_set = tree.xpath("//input[@name='data_set']") self.assertEqual( len(data_set), 1, 'paypal: Found %d "data_set" input instead of 1' % len(data_set)) self.assertEqual(data_set[0].get('data-action-url'), 'https://www.sandbox.paypal.com/cgi-bin/webscr', 'paypal: wrong form POST url') for form_input in tree.input: if form_input.get('name') in ['submit', 'data_set']: continue self.assertEqual( form_input.get('value'), form_values[form_input.get('name')], 'paypal: wrong value for input %s: received %s instead of %s' % (form_input.get('name'), form_input.get('value'), form_values[form_input.get('name')]))
def authorize_form_generate_values(self, values): self.ensure_one() base_url = self.env['ir.config_parameter'].get_param('web.base.url') authorize_tx_values = dict(values) temp_authorize_tx_values = { 'x_login': self.authorize_login, 'x_trans_key': self.authorize_transaction_key, 'x_amount': str(values['amount']), 'x_show_form': 'PAYMENT_FORM', 'x_type': 'AUTH_CAPTURE' if not self.capture_manually else 'AUTH_ONLY', 'x_method': 'CC', 'x_fp_sequence': '%s%s' % (self.id, int(time.time())), 'x_version': '3.1', 'x_relay_response': 'TRUE', 'x_fp_timestamp': str(int(time.time())), 'x_relay_url': urls.url_join(base_url, AuthorizeController._return_url), 'x_cancel_url': urls.url_join(base_url, AuthorizeController._cancel_url), 'x_currency_code': values['currency'] and values['currency'].name or '', 'address': values.get('partner_address'), 'city': values.get('partner_city'), 'country': values.get('partner_country') and values.get('partner_country').name or '', 'email': values.get('partner_email'), 'zip_code': values.get('partner_zip'), 'first_name': values.get('partner_first_name'), 'last_name': values.get('partner_last_name'), 'phone': values.get('partner_phone'), 'state': values.get('partner_state') and values['partner_state'].code or '', 'billing_address': values.get('billing_partner_address'), 'billing_city': values.get('billing_partner_city'), 'billing_country': values.get('billing_partner_country') and values.get('billing_partner_country').name or '', 'billing_email': values.get('billing_partner_email'), 'billing_zip_code': values.get('billing_partner_zip'), 'billing_first_name': values.get('billing_partner_first_name'), 'billing_last_name': values.get('billing_partner_last_name'), 'billing_phone': values.get('billing_partner_phone'), 'billing_state': values.get('billing_partner_state') and values['billing_partner_state'].code or '', } temp_authorize_tx_values['returndata'] = authorize_tx_values.pop( 'return_url', '') temp_authorize_tx_values[ 'x_fp_hash'] = self._authorize_generate_hashing( temp_authorize_tx_values) authorize_tx_values.update(temp_authorize_tx_values) return authorize_tx_values
def extract_path_info(environ_or_baseurl, path_or_url, charset='utf-8', errors='werkzeug.url_quote', collapse_http_schemes=True): """Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info('http://example.com/app', '/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello', ... collapse_http_schemes=False) is None True Instead of providing a base URL you can also pass a WSGI environment. :param environ_or_baseurl: a WSGI environment dict, a base URL or base IRI. This is the root of the application. :param path_or_url: an absolute path from the server root, a relative path (in which case it's the path info) or a full URL. Also accepts IRIs and unicode parameters. :param charset: the charset for byte data in URLs :param errors: the error handling on decode :param collapse_http_schemes: if set to `False` the algorithm does not assume that http and https on the same server point to the same resource. .. versionchanged:: 0.15 The ``errors`` parameter defaults to leaving invalid bytes quoted instead of replacing them. .. versionadded:: 0.6 """ def _normalize_netloc(scheme, netloc): parts = netloc.split(u'@', 1)[-1].split(u':', 1) if len(parts) == 2: netloc, port = parts if (scheme == u'http' and port == u'80') or \ (scheme == u'https' and port == u'443'): port = None else: netloc = parts[0] port = None if port is not None: netloc += u':' + port return netloc # make sure whatever we are working on is a IRI and parse it path = uri_to_iri(path_or_url, charset, errors) if isinstance(environ_or_baseurl, dict): environ_or_baseurl = get_current_url(environ_or_baseurl, root_only=True) base_iri = uri_to_iri(environ_or_baseurl, charset, errors) base_scheme, base_netloc, base_path = url_parse(base_iri)[:3] cur_scheme, cur_netloc, cur_path, = \ url_parse(url_join(base_iri, path))[:3] # normalize the network location base_netloc = _normalize_netloc(base_scheme, base_netloc) cur_netloc = _normalize_netloc(cur_scheme, cur_netloc) # is that IRI even on a known HTTP scheme? if collapse_http_schemes: for scheme in base_scheme, cur_scheme: if scheme not in (u'http', u'https'): return None else: if not (base_scheme in (u'http', u'https') and base_scheme == cur_scheme): return None # are the netlocs compatible? if base_netloc != cur_netloc: return None # are we below the application path? base_path = base_path.rstrip(u'/') if not cur_path.startswith(base_path): return None return u'/' + cur_path[len(base_path):].lstrip(u'/')
def _prepare_statistics_email_values(self): """Return some statistics that will be displayed in the mailing statistics email. Each item in the returned list will be displayed as a table, with a title and 1, 2 or 3 columns. """ self.ensure_one() mailing_type = self._get_pretty_mailing_type() kpi = {} if self.mailing_type == 'mail': kpi = { 'kpi_fullname': _('Engagement on %(expected)i %(mailing_type)s Sent', expected=self.expected, mailing_type=mailing_type ), 'kpi_col1': { 'value': f'{self.received_ratio}%', 'col_subtitle': _('RECEIVED (%i)', self.delivered), }, 'kpi_col2': { 'value': f'{self.opened_ratio}%', 'col_subtitle': _('OPENED (%i)', self.opened), }, 'kpi_col3': { 'value': f'{self.replied_ratio}%', 'col_subtitle': _('REPLIED (%i)', self.replied), }, 'kpi_action': None, } random_tip = self.env['digest.tip'].search( [('group_id.category_id', '=', self.env.ref('base.module_category_marketing_email_marketing').id)] ) if random_tip: random_tip = random.choice(random_tip).tip_description formatted_date = tools.format_datetime( self.env, self.sent_date, self.user_id.tz, 'MMM dd, YYYY', self.user_id.lang ) if self.sent_date else False web_base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') return { 'title': _('24H Stats of %(mailing_type)s "%(mailing_name)s"', mailing_type=mailing_type, mailing_name=self.subject ), 'top_button_label': _('More Info'), 'top_button_url': url_join(web_base_url, f'/web#id={self.id}&model=mailing.mailing&view_type=form'), 'kpi_data': [ kpi, { 'kpi_fullname': _('Business Benefits on %(expected)i %(mailing_type)s Sent', expected=self.expected, mailing_type=mailing_type ), 'kpi_action': None, 'kpi_col1': {}, 'kpi_col2': {}, 'kpi_col3': {}, }, ], 'tips': [random_tip] if random_tip else False, 'formatted_date': formatted_date, }
def test_10_Authorize_form_render(self): self.assertEqual(self.authorize.state, 'test', 'test without test environment') # ---------------------------------------- # Test: button direct rendering # ---------------------------------------- base_url = self.env['ir.config_parameter'].get_param('web.base.url') form_values = { 'x_login': self.authorize.authorize_login, 'x_amount': '56.16', 'x_show_form': 'PAYMENT_FORM', 'x_type': 'AUTH_CAPTURE', 'x_method': 'CC', 'x_fp_sequence': '%s%s' % (self.authorize.id, int(time.time())), 'x_version': '3.1', 'x_relay_response': 'TRUE', 'x_fp_timestamp': str(int(time.time())), 'x_relay_url': urls.url_join(base_url, AuthorizeController._return_url), 'x_cancel_url': urls.url_join(base_url, AuthorizeController._cancel_url), 'return_url': None, 'x_currency_code': 'USD', 'x_invoice_num': 'SO004', 'x_first_name': 'Norbert', 'x_last_name': 'Buyer', 'x_company': 'Big Company', 'x_address': 'Huge Street 2/543', 'x_city': 'Sin City', 'x_zip': '1000', 'x_country': 'Belgium', 'x_phone': '0032 12 34 56 78', 'x_email': '*****@*****.**', 'x_state': None, 'x_ship_to_first_name': 'Norbert', 'x_ship_to_last_name': 'Buyer', 'x_ship_to_address': 'Huge Street 2/543', 'x_ship_to_city': 'Sin City', 'x_ship_to_zip': '1000', 'x_ship_to_country': 'Belgium', 'x_ship_to_phone': '0032 12 34 56 78', 'x_ship_to_email': '*****@*****.**', 'x_ship_to_state': None, } form_values['x_fp_hash'] = self.authorize._authorize_generate_hashing( form_values) # render the button res = self.authorize.render('SO004', 56.16, self.currency_usd.id, values=self.buyer_values) # check form result tree = objectify.fromstring(res) data_set = tree.xpath("//input[@name='data_set']") self.assertEqual( len(data_set), 1, 'Authorize: Found %d "data_set" input instead of 1' % len(data_set)) self.assertEqual(data_set[0].get('data-action-url'), 'https://test.authorize.net/gateway/transact.dll', 'Authorize: wrong data-action-url POST url') for el in tree.iterfind('input'): values = list(el.attrib.values()) if values[1] in [ 'submit', 'x_fp_hash', 'return_url', 'x_state', 'x_ship_to_state', 'data_set' ]: continue self.assertEqual( values[2], form_values[values[1]], 'Authorize: wrong value for input %s: received %s instead of %s' % (values[1], values[2], form_values[values[1]]))
def request(self, method, url, *args, **kwargs): url = url_join('http://127.0.0.1:%d/' % web_config_port, url) return Session.request(self, method, url, *args, **kwargs)
def _compute_short_url(self): base_url = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url') self.short_url = urls.url_join(base_url, '/r/%(code)s' % {'code': self.code})
def send_completed_document(self): self.ensure_one() if len(self.request_item_ids) <= 0 or self.state != 'signed': return False if not self.completed_document: self.generate_completed_document() base_url = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url') attachment = self.env['ir.attachment'].create({ 'name': "%s.pdf" % self.reference if self.reference.split('.')[-1] != 'pdf' else self.reference, 'datas': self.completed_document, 'type': 'binary', 'res_model': self._name, 'res_id': self.id, }) report_action = self.env.ref('sign.action_sign_request_print_logs') # print the report with the public user in a sudoed env # public user because we don't want groups to pollute the result # (e.g. if the current user has the group Sign Manager, # some private information will be sent to *all* signers) # sudoed env because we have checked access higher up the stack public_user = self.env.ref('base.public_user', raise_if_not_found=False) if not public_user: # public user was deleted, fallback to avoid crash (info may leak) public_user = self.env.user pdf_content, __ = report_action.with_user( public_user).sudo()._render_qweb_pdf(self.id) attachment_log = self.env['ir.attachment'].create({ 'name': "Certificate of completion - %s.pdf" % time.strftime('%Y-%m-%d - %H:%M:%S'), 'datas': base64.b64encode(pdf_content), 'type': 'binary', 'res_model': self._name, 'res_id': self.id, }) tpl = self.env.ref('sign.sign_template_mail_completed') for signer in self.request_item_ids: if not signer.signer_email: continue signer_lang = get_lang(self.env, lang_code=signer.partner_id.lang).code tpl = tpl.with_context(lang=signer_lang) body = tpl._render( { 'record': self, 'link': url_join( base_url, 'sign/document/%s/%s' % (self.id, signer.access_token)), 'subject': '%s signed' % self.reference, 'body': False, }, engine='ir.qweb', minimal_qcontext=True) if not self.create_uid.email: raise UserError( _("Please configure the sender's email address")) if not signer.signer_email: raise UserError( _("Please configure the signer's email address")) self.env['sign.request']._message_send_mail( body, 'mail.mail_notification_light', {'record_name': self.reference}, { 'model_description': 'signature', 'company': self.create_uid.company_id }, { 'email_from': self.create_uid.email_formatted, 'author_id': self.create_uid.partner_id.id, 'email_to': signer.partner_id.email_formatted, 'subject': _('%s has been signed', self.reference), 'attachment_ids': [(4, attachment.id), (4, attachment_log.id)] }, force_send=True, lang=signer_lang, ) tpl = self.env.ref('sign.sign_template_mail_completed') for follower in self.mapped('message_follower_ids.partner_id' ) - self.request_item_ids.mapped( 'partner_id'): if not follower.email: continue if not self.create_uid.email: raise UserError( _("Please configure the sender's email address")) tpl_follower = tpl.with_context( lang=get_lang(self.env, lang_code=follower.lang).code) body = tpl._render( { 'record': self, 'link': url_join( base_url, 'sign/document/%s/%s' % (self.id, self.access_token)), 'subject': '%s signed' % self.reference, 'body': '', }, engine='ir.qweb', minimal_qcontext=True) self.env['sign.request']._message_send_mail( body, 'mail.mail_notification_light', {'record_name': self.reference}, { 'model_description': 'signature', 'company': self.create_uid.company_id }, { 'email_from': self.create_uid.email_formatted, 'author_id': self.create_uid.partner_id.id, 'email_to': follower.email_formatted, 'subject': _('%s has been signed', self.reference) }, lang=follower.lang, ) return True
def _compute_short_url_host(self): for tracker in self: base_url = tracker.get_base_url() tracker.short_url_host = urls.url_join(base_url, '/r/')
def _get_linkedin_redirect_uri(self): return url_join( self.env['ir.config_parameter'].sudo().get_param('web.base.url'), 'social_linkedin/callback')
def _compute_short_url(self): for tracker in self: tracker.short_url = urls.url_join( tracker.short_url_host, '%(code)s' % {'code': tracker.code})
def mscolab_login(app, msc_url, email='a', password='******'): data = {'email': email, 'password': password} url = url_join(msc_url, 'token') response = app.test_client().post(url, data=data) return response
def full_url(url): return url_join(get('locations')['base_url'], url)
def mscolab_register_and_login(app, msc_url, email, password, username): register_user(email, password, username) data = {'email': email, 'password': password} url = url_join(msc_url, 'token') response = app.test_client().post(url, data=data) return response
def generate_global_file(): locations = Location.find_all() if config.ENABLE_ROOMBOOKING else [] location_names = {loc.name: loc.name for loc in locations} default_location = next((loc.name for loc in locations if loc.is_default), None) ext_auths = [{ 'name': auth.name, 'title': auth.title, 'supports_groups': auth.supports_groups } for auth in multipass.identity_providers.itervalues() if auth.supports_search] indico_vars = { 'Urls': { 'Base': config.BASE_URL, 'BasePath': url_parse(config.BASE_URL).path.rstrip('/'), 'JsonRpcService': url_for('api.jsonrpc'), 'ExportAPIBase': url_for('api.httpapi', prefix='export'), 'APIBase': url_for('api.httpapi', prefix='api'), 'ImagesBase': config.IMAGES_BASE_URL, 'Login': url_for_login(), 'Favorites': url_for('users.user_favorites'), 'FavoriteUserAdd': url_for('users.user_favorites_users_add'), 'FavoriteUserRemove': url_rule_to_js('users.user_favorites_user_remove'), 'AttachmentManager': url_rule_to_js('attachments.management'), 'ManagementAttachmentInfoColumn': url_rule_to_js('attachments.management_info_column'), 'RoomBooking': { 'room': { 'check_available': url_rule_to_js('rooms_new.check_room_available'), }, 'calendar': url_join(url_for('rooms_new.roombooking'), 'calendar') }, 'RoomBookingBookRoom': url_rule_to_js('rooms.room_book'), 'RoomBookingBook': url_rule_to_js('rooms.book'), 'RoomBookingDetails': url_rule_to_js('rooms.roomBooking-roomDetails'), 'RoomBookingCloneBooking': url_rule_to_js('rooms.roomBooking-cloneBooking'), 'APIKeyCreate': url_for('api.key_create'), 'APIKeyTogglePersistent': url_for('api.key_toggle_persistent'), 'FontSassBundle': current_app.manifest['fonts.css']._paths, 'EventCreation': url_rule_to_js('events.create'), 'PermissionsDialog': url_rule_to_js('event_management.permissions_dialog'), 'RegistrationForm': { 'section': { 'add': url_rule_to_angular('event_registration.add_section'), 'modify': url_rule_to_angular('event_registration.modify_section'), 'toggle': url_rule_to_angular('event_registration.toggle_section'), 'move': url_rule_to_angular('event_registration.move_section') }, 'field': { 'add': url_rule_to_angular('event_registration.add_field'), 'modify': url_rule_to_angular('event_registration.modify_field'), 'toggle': url_rule_to_angular('event_registration.toggle_field'), 'move': url_rule_to_angular('event_registration.move_field') }, 'text': { 'add': url_rule_to_angular('event_registration.add_text'), 'modify': url_rule_to_angular('event_registration.modify_text'), 'toggle': url_rule_to_angular('event_registration.toggle_text'), 'move': url_rule_to_angular('event_registration.move_text') } }, 'Timetable': { 'management': url_rule_to_js('timetable.management'), 'default_pdf': url_rule_to_js('timetable.export_default_pdf'), 'pdf': url_rule_to_js('timetable.export_pdf'), 'reschedule': url_rule_to_js('timetable.reschedule'), 'breaks': { 'add': url_rule_to_js('timetable.add_break') }, 'contributions': { 'add': url_rule_to_js('timetable.add_contribution'), 'notScheduled': url_rule_to_js('timetable.not_scheduled'), 'schedule': url_rule_to_js('timetable.schedule'), 'protection': url_rule_to_js('contributions.manage_contrib_protection'), 'clone': url_rule_to_js('timetable.clone_contribution') }, 'sessionBlocks': { 'add': url_rule_to_js('timetable.add_session_block'), 'fit': url_rule_to_js('timetable.fit_session_block') }, 'sessions': { 'add': url_rule_to_js('timetable.add_session') }, 'entries': { 'delete': url_rule_to_js('timetable.delete_entry'), 'edit': url_rule_to_js('timetable.edit_entry'), 'editDatetime': url_rule_to_js('timetable.edit_entry_datetime'), 'editTime': url_rule_to_js('timetable.edit_entry_time'), 'move': url_rule_to_js('timetable.move_entry'), 'shift': url_rule_to_js('timetable.shift_entries'), 'swap': url_rule_to_js('timetable.swap_entries'), 'info': { 'display': url_rule_to_js('timetable.entry_info'), 'manage': url_rule_to_js('timetable.entry_info_manage'), }, } }, 'Contributions': { 'display_contribution': url_rule_to_js('contributions.display_contribution') }, 'Sessions': { 'display_session': url_rule_to_js('sessions.display_session') }, 'Categories': { 'info': url_rule_to_js('categories.info'), 'infoFrom': url_rule_to_js('categories.info_from'), 'search': url_rule_to_js('categories.search') } }, 'Data': { 'WeekDays': [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ], 'DefaultLocation': default_location, 'Locations': location_names }, 'Settings': { 'ExtAuthenticators': ext_auths, 'RoomBookingModuleActive': config.ENABLE_ROOMBOOKING, }, 'FileRestrictions': { 'MaxUploadFilesTotalSize': config.MAX_UPLOAD_FILES_TOTAL_SIZE, 'MaxUploadFileSize': config.MAX_UPLOAD_FILE_SIZE } } return render_template('assets/vars_globals.js', indico_vars=indico_vars, config=config)
def _compute_short_url_host(self): for tracker in self: base_url = self.env['website'].get_current_website().get_base_url() tracker.short_url_host = urls.url_join(base_url, '/r/')
def poschapin_s2s_create_json_3ds(self, verify_validity=False, **kwargs): logging.warn('TESTIING') logging.warn(kwargs) hora = int(time.time()) logging.warn('hora') logging.warn(hora) dt = datetime.datetime.now() utc_time = dt.replace(tzinfo=timezone.utc) utc_timestamp = utc_time.timestamp() hora = str(int(utc_timestamp)) logging.warn(hora) string_hash = "POSCHAPINTESTA1" + "|" + kwargs[ 'amount'] + "|" + hora + "|" + "YSAJRBSB_key_private_E3QY0CL0" logging.warn('string_hash') logging.warn(string_hash) hash = hashlib.md5(string_hash.encode('utf-8')).hexdigest() # hash = hashlib.md5(string_hash.encode().hexdigest()) logging.warn('hash') logging.warn(hash) url = urls.url_join("https://pos-chapin.appspot.com/", "transaccion/json") logging.warn('URL') logging.warn(url) # headers = { # 'AUTHORIZATION': 'Bearer %s' % self.sudo().stripe_secret_key, # 'Stripe-Version': '2019-05-16', # SetupIntent need a specific version # } # "redirect": "http://*****:*****@gmail.com", "card_number": kwargs['card_number'].replace(" ", ""), "ccexp": kwargs['ccexp'].replace(" / ", ""), "cvv": kwargs['cvv'], "first_name": kwargs['first_name'], "last_name": kwargs['first_name'], "address1": "aaa", "city": "Guatemala", "state": "AA", "zip": "01018", "country": "GT", "phone": "58772265", } # extra_url = urllib.parse.urlencode(data) # logging.warn(extra_url) token = False error = None try: token = request.env['payment.acquirer'].browse( int(kwargs.get('acquirer_id'))).s2s_process(kwargs) logging.warn('try') logging.warn(kwargs) logging.warn(token) except Exception as e: error = str(e) # headers = {"content-type": "x-www-form-urlencoded"} # json_data = json.dumps(data) # u = urllib.parse.quote(json_data.encode('utf-8')) # logging.warn('U') # logging.warn(u) # # resp = requests.head("https://pos-chapin.appspot.com/transaccion/json") # logging.warn(resp.headers) # resp = requests.request("POST", "https://pos-chapin.appspot.com/transaccion/json", data=dict(data=json.dumps(data))) # resp = requests.request("POST", "https://pos-chapin.appspot.com/transaccion/json", data=extra_url) # # logging.warn(resp) # requote = requote_uri(json.dumps(data, indent=4, separators=(".", " = "))) # logging.warn(requote) # urr= "https://pos-chapin.appspot.com/transaccion/json?" +str(json.dumps(data)) # logging.warn('urr') # logging.warn(urr) # stripped = re.sub('<[^<]+?>', '', resp.text) # # print(stripped) # logging.warn(stripped) # logging.warn(resp.text) # with urllib.request.urlopen('https://pos-chapin.appspot.com/transaccion/json',data=bytes(json.dumps(headers), encoding="utf-8")) as f: # print(f.read(300)) # headers = {"content-type": "application/json"} # js ={'Authorization':'a74524fdcccf575b9219572978855df8','amount':'20.0'} # x = requests.post('https://pos-chapin.appspot.com/transaccion/json', json= js,headers=headers,verify=False) # js ={'key_public':'5834f6987a623afd644bdc1b7eb2f5c1'} # logging.warn(json.dumps(js)) # logging.warn(kwargs['cc_number'].replace(" ", "")) # data = { # "key_public": "5834f6987a623afd644bdc1b7eb2f5c1", # "amount": "1.00", # "redirect": "https://4memethod.com.gt/shop/payment", # "orderid": "POSCHAPINTESTA1", # "hash": hash, # "time": hora, # "email": "*****@*****.**", # "card_number": kwargs['card_number'].replace(" ", ""), # "ccexp": kwargs['ccexp'].replace(" ", ""), # "cvv": kwargs['cvv'], # "first_name": kwargs['first_name'], # "last_name": kwargs['first_name'], # "address1": "aaa", # "city":"Guatemala", # "state": "AA", # "zip": "01018", # "country": "GT", # "phone": "58772265", # } # logging.warn(json.dumps(data)) # x = requests.post('https://pos-chapin.appspot.com/transaccion/json', data= data,headers = {"content-type":"application/x-www-form-urlencoded"}) # self.testa(data) # return redirect("https://pos-chapin.appspot.com/transaccion/json?"+str(dict(data=json.dumps(data)))) # self.testa("https://pos-chapin.appspot.com/transaccion/json?"+str(f)) # token = request.env['payment.token'].create({ # 'name': 'test', # 'partner_id': int(kwargs.get('partner_id')), # 'acquirer_id': int(kwargs.get('acquirer_id')), # 'acquirer_ref': 'test' # # }) # if token: # logging.warn('el token') # logging.warn(token) # # res = { # 'result': True, # 'id': token.id, # 'short_name': 'test', # '3d_secure': False, # 'verified': True, # } # baseurl = request.env['ir.config_parameter'].sudo().get_param('web.base.url') # kwargs['return_url'] = '/shop' # logging.warn('kwargs') # logging.warn(kwargs.get('return_url', baseurl)) # params = { # 'accept_url': baseurl + '/payment/ogone/validate/accept', # 'decline_url': baseurl + '/payment/ogone/validate/decline', # 'exception_url': baseurl + '/payment/ogone/validate/exception', # 'return_url': kwargs.get('return_url', baseurl) # } # tx = token.validate(**params) # logging.warn('tx') # logging.warn(tx.html_3ds) # res['verified'] = token.verified # # if tx and tx.html_3ds: # logging.warn(tx.html_3ds) # res['3d_secure'] = tx.html_3ds # datos = self._get_response('https://pos-chapin.appspot.com/transaccion/json',data) return { 'result': True, 'id': 5, 'short_name': 'test', '3d_secure': False, 'verified': True, }
def adyen_form_generate_values(self, values): base_url = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url') # tmp import datetime from dateutil import relativedelta if self.provider == 'adyen' and len(self.adyen_skin_hmac_key) == 64: tmp_date = datetime.datetime.today() + relativedelta.relativedelta( days=1) values.update({ 'merchantReference': values['reference'], 'paymentAmount': '%d' % int(tools.float_round(values['amount'], 2) * 100), 'currencyCode': values['currency'] and values['currency'].name or '', 'shipBeforeDate': tmp_date.strftime('%Y-%m-%d'), 'skinCode': self.adyen_skin_code, 'merchantAccount': self.adyen_merchant_account, 'shopperLocale': values.get('partner_lang', ''), 'sessionValidity': tmp_date.isoformat('T')[:19] + "Z", 'resURL': urls.url_join(base_url, AdyenController._return_url), 'merchantReturnData': json.dumps({'return_url': '%s' % values.pop('return_url')}) if values.get('return_url', '') else False, 'shopperEmail': values.get('partner_email', ''), }) values['merchantSig'] = self._adyen_generate_merchant_sig_sha256( 'in', values) else: tmp_date = datetime.date.today() + relativedelta.relativedelta( days=1) values.update({ 'merchantReference': values['reference'], 'paymentAmount': '%d' % int(tools.float_round(values['amount'], 2) * 100), 'currencyCode': values['currency'] and values['currency'].name or '', 'shipBeforeDate': tmp_date, 'skinCode': self.adyen_skin_code, 'merchantAccount': self.adyen_merchant_account, 'shopperLocale': values.get('partner_lang'), 'sessionValidity': tmp_date, 'resURL': urls.url_join(base_url, AdyenController._return_url), 'merchantReturnData': json.dumps({'return_url': '%s' % values.pop('return_url')}) if values.get('return_url') else False, }) values['merchantSig'] = self._adyen_generate_merchant_sig( 'in', values) return values
def test_10_ogone_form_render(self): base_url = self.env['ir.config_parameter'].get_param('web.base.url') # be sure not to do stupid thing self.assertEqual(self.ogone.environment, 'test', 'test without test environment') # ---------------------------------------- # Test: button direct rendering + shasign # ---------------------------------------- form_values = { 'PSPID': 'dummy', 'ORDERID': 'test_ref0', 'AMOUNT': '1', 'CURRENCY': 'EUR', 'LANGUAGE': 'en_US', 'CN': 'Norbert Buyer', 'EMAIL': '*****@*****.**', 'OWNERZIP': '1000', 'OWNERADDRESS': 'Huge Street 2/543', 'OWNERCTY': 'Belgium', 'OWNERTOWN': 'Sin City', 'OWNERTELNO': '0032 12 34 56 78', 'SHASIGN': '815f67b8ff70d234ffcf437c13a9fa7f807044cc', 'ACCEPTURL': urls.url_join(base_url, OgoneController._accept_url), 'DECLINEURL': urls.url_join(base_url, OgoneController._decline_url), 'EXCEPTIONURL': urls.url_join(base_url, OgoneController._exception_url), 'CANCELURL': urls.url_join(base_url, OgoneController._cancel_url), } # render the button res = self.ogone.render( 'test_ref0', 0.01, self.currency_euro.id, partner_id=None, partner_values=self.buyer_values) # check form result tree = objectify.fromstring(res) self.assertEqual(tree.get('action'), 'https://secure.ogone.com/ncol/test/orderstandard.asp', 'ogone: wrong form POST url') for form_input in tree.input: if form_input.get('name') in ['submit']: continue self.assertEqual( form_input.get('value'), form_values[form_input.get('name')], 'ogone: wrong value for input %s: received %s instead of %s' % (form_input.get('name'), form_input.get('value'), form_values[form_input.get('name')]) ) # ---------------------------------------- # Test2: button using tx + validation # ---------------------------------------- # create a new draft tx tx = self.env['payment.transaction'].create({ 'amount': 0.01, 'acquirer_id': self.ogone.id, 'currency_id': self.currency_euro.id, 'reference': 'test_ref0', 'partner_id': self.buyer_id}) # render the button res = self.ogone.render( 'should_be_erased', 0.01, self.currency_euro, tx_id=tx.id, partner_id=None, partner_values=self.buyer_values) # check form result tree = objectify.fromstring(res) self.assertEqual(tree.get('action'), 'https://secure.ogone.com/ncol/test/orderstandard.asp', 'ogone: wrong form POST url') for form_input in tree.input: if form_input.get('name') in ['submit']: continue self.assertEqual( form_input.get('value'), form_values[form_input.get('name')], 'ogone: wrong value for form input %s: received %s instead of %s' % (form_input.get('name'), form_input.get('value'), form_values[form_input.get('name')]) )
def create_payment(self, values): self.ensure_one() pm_id = self.payment_token_id if pm_id: values['payment_method'] = pm_id.stripe_checkout_payment_method if not values.get('payment_method'): return {'status': False, 'message': _("Paymant Method not Found.")} base_url = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url') customer_id = self.partner_id.stripe_checkout_create_customer( self.acquirer_id.id) success_url = StripeCheckoutController._checkout_success_url return_url = urls.url_join( base_url, success_url) + '?reference=%s' % self.reference intent_params = { 'amount': int(self.amount if str(self.currency_id.name) in ZERO_DECIMAL_CURRENCIES else float_round(self.amount * 100, 2)), 'currency': self.currency_id.name, 'setup_future_usage': 'off_session', 'confirm': True, 'payment_method': values['payment_method'], 'customer': customer_id, 'return_url': return_url, 'payment_method_options[card][request_three_d_secure]': 'any', 'description': "Payment for %s: %s" % (self.partner_id.email, self.reference), } if self.acquirer_id.capture_manually: intent_params['capture_method'] = 'manual' if not pm_id: res = self.acquirer_id._stripe_call(method='_payment_method', operation='attach', **{ 'sid': values['payment_method'], 'customer': customer_id }) if not res['status']: return res _logger.info( 'create_payment: Sending values to stripe checkout, values:\n%s', pprint.pformat(intent_params)) res = self.acquirer_id._stripe_call(method='_payment_intent', operation='create', **intent_params) if not res['status']: return res self.stripe_checkout_payment_intent = res['response'].get('id') return { 'status': True, 'next_action': res['response'].get('next_action', {}), 'payment_intent': res['response'].get('id'), 'client_secret': res['response'].get('client_secret'), 'payment_method': res['response'].get('payment_method'), 'return_url': return_url, 'stripe_checkout_pub_key': self.acquirer_id.sudo().stripe_checkout_publishable_key }
def moyasar_form_generate_values(self, values): base_url = self.get_base_url() # tmp import datetime from dateutil import relativedelta paymentAmount = self._moyasar_convert_amount(values['amount'], values['currency']) if self.provider == 'moyasar' and len(self.Moyasar_scret_key) == 64: tmp_date = datetime.datetime.today() + relativedelta.relativedelta( days=1) values.update({ 'merchantReference': values['reference'], 'paymentAmount': '%d' % paymentAmount, 'currencyCode': values['currency'] and values['currency'].name or '', 'shipBeforeDate': tmp_date.strftime('%Y-%m-%d'), 'skinCode': self.Moyasar_publishable_api_key, 'merchantAccount': self.moyasar_merchant_account, 'shopperLocale': values.get('partner_lang', ''), 'sessionValidity': tmp_date.isoformat('T')[:19] + "Z", 'resURL': urls.url_join(base_url, MoyasarController._return_url), 'merchantReturnData': json.dumps({'return_url': '%s' % values.pop('return_url')}) if values.get('return_url', '') else False, 'shopperEmail': values.get('partner_email') or values.get('billing_partner_email') or '', }) values['merchantSig'] = self._moyasar_generate_merchant_sig_sha256( 'in', values) else: tmp_date = datetime.date.today() + relativedelta.relativedelta( days=1) values.update({ 'merchantReference': values['reference'], 'paymentAmount': '%d' % paymentAmount, 'currencyCode': values['currency'] and values['currency'].name or '', 'shipBeforeDate': tmp_date, 'skinCode': self.Moyasar_publishable_api_key, 'merchantAccount': self.moyasar_merchant_account, 'shopperLocale': values.get('partner_lang'), 'sessionValidity': tmp_date, 'resURL': urls.url_join(base_url, MoyasarController._return_url), 'merchantReturnData': json.dumps({'return_url': '%s' % values.pop('return_url')}) if values.get('return_url') else False, }) values['merchantSig'] = self._moyasar_generate_merchant_sig( 'in', values) return values
def test_10_alipay_form_render(self): base_url = self.env['ir.config_parameter'].get_param('web.base.url') self.assertEqual(self.alipay.state, 'test', 'test without test environment') # ---------------------------------------- # Test: button direct rendering # ---------------------------------------- # render the button res = self.alipay.render('test_ref0', 0.01, self.currency_euro.id, values=self.buyer_values) form_values = { '_input_charset': 'utf-8', 'notify_url': urls.url_join(base_url, AlipayController._notify_url), 'out_trade_no': 'SO12345-1', 'partner': self.alipay.alipay_merchant_partner_id, 'return_url': urls.url_join(base_url, AlipayController._return_url), 'subject': 'test_ref0', 'total_fee': '0.01', } if self.alipay.alipay_payment_method == 'standard_checkout': form_values.update({ 'service': 'create_forex_trade', 'currency': 'EUR', 'product_code': 'NEW_OVERSEAS_SELLER', }) else: form_values.update({ 'payment_type': '1', 'seller_email': self.alipay.alipay_seller_email, 'service': 'create_direct_pay_by_user' }) sign = self.alipay._build_sign(form_values) form_values.update({'sign': sign, 'sign_type': 'MD5'}) # check form result tree = objectify.fromstring(res) data_set = tree.xpath("//input[@name='data_set']") self.assertEqual( len(data_set), 1, 'Alipay: Found %d "data_set" input instead of 1' % len(data_set)) self.assertEqual(data_set[0].get('data-action-url'), 'https://openapi.alipaydev.com/gateway.do', 'alipay: wrong form POST url') for form_input in tree.input: if form_input.get('name') in [ 'submit', 'data_set', 'sign', 'out_trade_no' ]: continue self.assertEqual( form_input.get('value'), form_values[form_input.get('name')], 'alipay: wrong value for input %s: received %s instead of %s' % (form_input.get('name'), form_input.get('value'), form_values[form_input.get('name')]))
def _get_url(): return url_join(config.COMMUNITY_HUB_URL, 'api/instance/')
def _mollie_webhook_url(self, tx_id): base_url = self.get_base_url() redirect_url = urls.url_join(base_url, MollieController._notify_url) return "%s?tx=%s" % (redirect_url, tx_id)