示例#1
0
    def response(self, query_string, **kwargs):
        fields = urlparse.parse_qs(query_string, True)
        if not set(fields) >= set([SIGNATURE, VADS_CTX_MODE, VADS_AUTH_RESULT
                                   ]):
            raise ResponseError()
        for key, value in fields.items():
            fields[key] = value[0]
        copy = fields.copy()
        bank_status = []
        if VADS_AUTH_RESULT in fields:
            v = copy[VADS_AUTH_RESULT]
            ctx = (v, AUTH_RESULT_MAP.get(v, 'Code inconnu'))
            copy[VADS_AUTH_RESULT] = '%s: %s' % ctx
            bank_status.append(copy[VADS_AUTH_RESULT])
        if VADS_RESULT in copy:
            v = copy[VADS_RESULT]
            ctx = (v, RESULT_MAP.get(v, 'Code inconnu'))
            copy[VADS_RESULT] = '%s: %s' % ctx
            bank_status.append(copy[VADS_RESULT])
            if v == '30':
                if VADS_EXTRA_RESULT in fields:
                    v = fields[VADS_EXTRA_RESULT]
                    if v.isdigit():
                        for parameter in PARAMETERS:
                            if int(v) == parameter.code:
                                s = 'erreur dans le champ %s' % parameter.name
                                copy[VADS_EXTRA_RESULT] = s
                                bank_status.append(copy[VADS_EXTRA_RESULT])
            elif v in ('05', '00'):
                if VADS_EXTRA_RESULT in fields:
                    v = fields[VADS_EXTRA_RESULT]
                    extra_result_name = EXTRA_RESULT_MAP.get(v, 'Code inconnu')
                    copy[VADS_EXTRA_RESULT] = '%s: %s' % (v, extra_result_name)
                    bank_status.append(copy[VADS_EXTRA_RESULT])
        self.logger.debug('checking systempay response on:')
        for key in sorted(fields.keys()):
            self.logger.debug('  %s: %s' % (key, copy[key]))
        signature = self.signature(fields)
        signature_result = signature == fields[SIGNATURE]
        self.logger.debug('signature check: %s <!> %s', signature,
                          fields[SIGNATURE])
        if not signature_result:
            bank_status.append('invalid signature')

        if fields[VADS_AUTH_RESULT] == '00':
            result = PAID
        else:
            result = ERROR
        test = fields[VADS_CTX_MODE] == 'TEST'
        transaction_id = '%s_%s' % (copy[VADS_TRANS_DATE], copy[VADS_TRANS_ID])
        # the VADS_AUTH_NUMBER is the number to match payment in bank logs
        copy[self.BANK_ID] = copy.get(VADS_AUTH_NUMBER, '')
        response = PaymentResponse(result=result,
                                   signed=signature_result,
                                   bank_data=copy,
                                   order_id=transaction_id,
                                   transaction_id=copy.get(VADS_AUTH_NUMBER),
                                   bank_status=' - '.join(bank_status),
                                   test=test)
        return response
示例#2
0
def sign_url_paiement(ntkey, query):
    if '?' in query:
        query = query[query.index('?') + 1:]
    key = decrypt_ntkey(ntkey)
    data = urlparse.parse_qs(query, True)
    fields = [data.get(field, [''])[0] for field in PAIEMENT_FIELDS]
    data_to_sign = ''.join(fields)
    return hmac.new(key[:20], data_to_sign, hashlib.sha1).hexdigest().upper()
示例#3
0
def parse_query(query):
    q = {'mode': 'main'}
    if query.startswith('?'): query = query[1:]
    queries = urlparse.parse_qs(query)
    for key in queries:
        if len(queries[key]) == 1:
            q[key] = queries[key][0]
        else:
            q[key] = queries[key]
    return q
示例#4
0
    def response(self, query_string, logger=LOGGER, **kwargs):
        form = urlparse.parse_qs(query_string)
        if not set(form) >= set([REFERENCE, ETAT, REFSFP]):
            raise ResponseError()
        for key, value in form.items():
            form[key] = value[0]
        logger.debug('received query_string %s' % query_string)
        logger.debug('parsed as %s' % form)
        reference = form.get(REFERENCE)
        bank_status = []
        signed = False
        form[self.BANK_ID] = form.get(REFSFP)
        etat = form.get('etat')
        status = '%s: %s' % (etat,
                             SPPLUS_RESPONSE_CODES.get(etat, 'Unknown code'))
        logger.debug('status is %s', status)
        bank_status.append(status)
        if 'hmac' in form:
            try:
                signed_data, signature = query_string.rsplit('&', 1)
                _, hmac = signature.split('=', 1)
                logger.debug('got signature %s' % hmac)
                computed_hmac = sign_ntkey_query(self.cle, signed_data)
                logger.debug('computed signature %s' % computed_hmac)
                signed = hmac == computed_hmac
                if not signed:
                    bank_status.append('invalid signature')
            except ValueError:
                bank_status.append('invalid signature')

        test = False
        if etat in PAID_STATE:
            result = PAID
        elif etat in ACCEPTED_STATE:
            result = ACCEPTED
        elif etat in VALID_STATE:
            result = RECEIVED
        elif etat in TEST_STATE:
            result = RECEIVED  # what else ?
            test = True
        else:
            result = ERROR

        response = PaymentResponse(result=result,
                                   signed=signed,
                                   bank_data=form,
                                   order_id=reference,
                                   transaction_id=form[self.BANK_ID],
                                   bank_status=' - '.join(bank_status),
                                   return_content=SPCHECKOK,
                                   test=test)
        return response
示例#5
0
def oauth_flow(s, oauth_url, username=None, password=None, sandbox=False):
    """s should be a requests session"""
    r = s.get(oauth_url)
    if r.status_code >= 300:
        raise RuntimeError(r.text)

    params = urlparse.parse_qs(urlparse.urlparse(r.url).query)

    data = {
        "un": username,
        "width": 2560,
        "height": 1440,
        "hasRememberUn": True,
        "startURL": params['startURL'],
        "loginURL": "",
        "loginType": 6,
        "useSecure": True,
        "local": "",
        "lt": "OAUTH",
        "qs": "r=https%3A%2F%2Flocalhost%3A8443%2Fsalesforce%2F21",
        "locale": "",
        "oauth_token": "",
        "oauth_callback": "",
        "login": "",
        "serverid": "",
        "display": "popup",
        "username": username,
        "pw": password,
        "Login": "",
    }

    if sandbox:
        base = "https://test.salesforce.com"
    else:
        base = "https://login.salesforce.com"

    r2 = s.post(base, data)
    m = re.search("window.location.href\s*='(.[^']+)'", r2.text)
    assert m is not None, ("Couldn't find location.href expression in page {} "
                           "(Username or password is wrong)").format(r2.url)

    u3 = "https://" + urlparse.urlparse(r2.url).hostname + m.group(1)
    r3 = s.get(u3)

    m = re.search("window.location.href\s*='(.[^']+)'", r3.text)

    assert m is not None, ("Couldn't find location.href expression in page {}:"
                           "\n{}").format(r3.url, r3.text)

    return m.group(1)
示例#6
0
    def do_POST(self):
        ctype, pdict = parse_header(self.headers['content-type'])
        if ctype == 'multipart/form-data':
            data = parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers['content-length'])
            data = urlparse.parse_qs(self.rfile.read(length),
                                     keep_blank_values=1)
        elif ctype == 'application/json':
            length = int(self.headers['content-length'])
            data = json.loads(self.rfile.read(length))
        else:
            data = {}

        return self._handle_request('POST', data)
示例#7
0
def website_login(username=None, password=None, client_id=None,
                  client_secret=None, redirect_uri=None, sandbox=None,
                  cache_session=None, state=None):
    if sandbox:
        base = "https://test.salesforce.com"
    else:
        base = "https://login.salesforce.com"

    auth_url = base + "/services/oauth2/authorize?"

    client_id = os.environ.get('SALESFORCE_CLIENT_ID', client_id)
    client_secret = os.environ.get('SALESFORCE_CLIENT_SECRET', client_secret)
    redirect_uri = os.environ.get('SALESFORCE_REDIRECT_URI', redirect_uri)

    auth_url += urllib.urlencode([
        ("response_type", "code"),
        ("display", "popup"),
        ("client_id", client_id),
        ("redirect_uri", redirect_uri),
        ("prompt", "login"),
        ("state", state)])

    s = requests.session()
    redirect_return = oauth_flow(
        s,
        auth_url,
        username=username,
        password=password,
        sandbox=sandbox,
    )

    # parse out the session id and endpoint
    params = urlparse.parse_qs(redirect_return)

    data = dict(code=params['code'],
                grant_type="authorization_code",
                client_id=client_id,
                client_secret=client_secret,
                redirect_uri=redirect_uri,
                format="json")

    code_url = base + "/services/oauth2/token"
    return requests.post(code_url, data=data)
示例#8
0
 def response(self, query_string, **kwargs):
     form = urlparse.parse_qs(query_string)
     if not DATA in form:
         raise ResponseError()
     params = {'message': form[DATA][0]}
     result = self.execute('response', params)
     d = dict(zip(RESPONSE_PARAMS, result))
     # The reference identifier for the payment is the authorisation_id
     d[self.BANK_ID] = d.get(AUTHORISATION_ID)
     self.logger.debug('response contains fields %s' % d)
     response_result = d.get(RESPONSE_CODE) == '00'
     response_code_msg = CB_BANK_RESPONSE_CODES.get(d.get(RESPONSE_CODE))
     response = PaymentResponse(result=response_result,
                                signed=response_result,
                                bank_data=d,
                                order_id=d.get(ORDER_ID),
                                transaction_id=d.get(AUTHORISATION_ID),
                                bank_status=response_code_msg)
     return response
示例#9
0
 def response(self, query_string, callback=False, **kwargs):
     d = urlparse.parse_qs(query_string, True, False)
     if not set(d) >= set(['erreur', 'reference']):
         raise ResponseError()
     signed = False
     if 'signature' in d:
         sig = d['signature'][0]
         sig = base64.b64decode(sig)
         data = []
         if callback:
             for key in ('montant', 'reference', 'code_autorisation',
                         'erreur'):
                 data.append('%s=%s' % (key, urllib.quote(d[key][0])))
         else:
             for key, value in urlparse.parse_qsl(query_string, True, True):
                 if key == 'heure':
                     break
                 data.append('%s=%s' % (key, urllib.quote(value)))
         data = '&'.join(data)
         signed = verify(data, sig)
     if d['erreur'][0] == '00000':
         result = PAID
     else:
         result = ERROR
     for l in (5, 3):
         prefix = d['erreur'][0][:l]
         suffix = 'x' * (5-l)
         bank_status = PAYBOX_ERROR_CODES.get(prefix + suffix)
         if bank_status is not None:
             break
     orderid = d['reference'][0]
     # decode order id from returned reference
     if ORDERID_TRANSACTION_SEPARATOR in orderid:
         orderid, transaction_id = orderid.split(ORDERID_TRANSACTION_SEPARATOR, 1)
     return PaymentResponse(
         order_id=orderid,
         signed=signed,
         bank_data=d,
         result=result,
         bank_status=bank_status)
示例#10
0
 def response(self, query_string, **kwargs):
     form = urlparse.parse_qs(query_string)
     if not set(form) >= set(['Data', 'Seal', 'InterfaceVersion']):
         raise ResponseError()
     self.logger.debug('received query string %r', form)
     data = self.decode_data(form['Data'][0])
     seal = form['Seal'][0]
     self.logger.debug('parsed response %r seal %r', data, seal)
     signed = self.check_seal(data, seal)
     response_code = data['responseCode']
     transaction_id = data.get('transactionReference')
     result = self.response_code_to_result.get(response_code, ERROR)
     merchant_id = data.get('merchantId')
     test = merchant_id == self.TEST_MERCHANT_ID
     return PaymentResponse(result=result,
                            signed=signed,
                            bank_data=data,
                            order_id=transaction_id,
                            transaction_id=data.get('authorisationId'),
                            bank_status=self.RESPONSE_CODES.get(
                                response_code,
                                u'unknown code - ' + response_code),
                            test=test)
示例#11
0
def filter_result(link):
    try:

        # Valid results are absolute URLs not pointing to a Google domain
        # like images.google.com or googleusercontent.com
        o = urlparse.urlparse(link, 'http')
        if o.netloc and 'google' not in o.netloc:
            return link

        # Decode hidden URLs.
        if link.startswith('/url?'):
            link = urlparse.parse_qs(o.query)['q'][0]

            # Valid results are absolute URLs not pointing to a Google domain
            # like images.google.com or googleusercontent.com
            o = urlparse.urlparse(link, 'http')
            if o.netloc and 'google' not in o.netloc:
                return link

    # Otherwise, or on error, return None.
    except Exception:
        pass
    return None
示例#12
0
 def response(self, query_string, **kwargs):
     params = urlparse.parse_qs(query_string, True)
     params = dict((key.upper(), params[key][0]) for key in params)
     if not set(params) >= set(['ORDERID', 'PAYID', 'STATUS', 'NCERROR']):
         raise ResponseError()
     reference = params['ORDERID']
     transaction_id = params['PAYID']
     status = params['STATUS']
     error = params['NCERROR']
     signed = False
     if self.sha_in:
         signature = params.get('SHASIGN')
         expected_signature = self.sha_sign_out(params)
         signed = signature == expected_signature
         print ('signed', signature)
         print ('expected', expected_signature)
     if status == '1':
         result = CANCELLED
     elif status == '2':
         result = DENIED
     elif status == '5':
         result = ACCEPTED
     elif status == '9':
         result = PAID
     else:
         self.logger.error('response STATUS=%s NCERROR=%s NCERRORPLUS=%s',
                 status, error, params.get('NCERRORPLUS', ''))
         result = ERROR
     # extract reference from received order id
     if ORDERID_TRANSACTION_SEPARATOR in reference:
         reference, transaction_id = reference.split(ORDERID_TRANSACTION_SEPARATOR, 1)
     return PaymentResponse(
             result=result,
             signed=signed,
             bank_data=params,
             order_id=reference,
             transaction_id=transaction_id)