Beispiel #1
0
def create_pay_record(orderid, mchid, appid, pay_type, amount, notify_url, description=''):
    appid_detail = get_appid_detail(appid, pay_type, polling=True)
    fee_rate = appid_detail.fee_rate
    service_rate = appid_detail.service_rate
    accountid = appid_detail.accountid
    account = Account.query.filter(Account.id == accountid).one()
    service_fee = appid_detail.service_rate / 10000.0 * float(amount)
    #if service_rate and account.balance < _SERVICE_FEE_LIMIT:  # service_fee:
    #    raise InsufficientFunds(u"服务费余额不足")

    pay_record = PayRecord()
    pay_record.id = generate_long_id('pay')
    pay_record.orderid = orderid
    pay_record.description = description
    pay_record.mchid = mchid or None
    pay_record.appid = appid
    pay_record.pay_type = pay_type or PAY_TYPE.WECHAT_H5
    pay_record.amount = amount
    pay_record.description = description
    pay_record.fee = get_fee(fee_rate, amount, pay_type)
    pay_record.notify_url = notify_url
    pay_record.real_pay = appid_detail.real_pay
    pay_record.real_custid = appid_detail.custid
    pay_record.pay_status = PAY_STATUS.READY
    pay_record.service_fee = service_fee
    pay_record.save(auto_commit=True)
    return pay_record
Beispiel #2
0
def create_recharge_order(recharge_type, amount, accountid):
    recharge_type = _convert_recharge_type(recharge_type)
    orderid = generate_long_id("pay")
    if recharge_type == 0:
        pay_url = qq_traffic_pay(amount, orderid)
    else:
        pay_url = alipay_traffic_pay(float(amount) / 100, orderid)
    rech = controller.create_recharge(orderid, accountid, pay_url, amount,
                                      recharge_type)
    return {"order_id": str(rech.id), "pay_url": rech.pay_url}
Beispiel #3
0
def create_jinjian_record(appid,
                          real_pay,
                          jinjian_data,
                          resp_data,
                          mch_name=None,
                          custid=None,
                          jinjian_id=None,
                          status=0):
    jinjian = JinjianAppid.query.filter(JinjianAppid.appid == appid).first()
    accountid = jinjian.accountid
    record = JinjianRecord()
    record.id = id_generator.generate_long_id(
        'jinjian') if jinjian_id else jinjian_id
    record.accountid = accountid
    record.real_pay = real_pay
    record.jinjian_data = jinjian_data
    record.resp_data = resp_data
    record.status = status
    record.mch_name = mch_name
    record.custid = custid
    record.save()
Beispiel #4
0
def create_withdraw_record(appid,
                           real_pay,
                           amount,
                           fee=2,
                           order_code=0,
                           mchid=None,
                           extend='',
                           acc_name='',
                           paystatus=1,
                           channel=None,
                           to_account='',
                           bank_name='',
                           trans_time=None,
                           withdraw_type=1):
    appid_detail = Appid.query.filter(Appid.appid == appid).filter(
        Appid.real_pay == real_pay).first()
    appid_detail.withdraw_total += Decimal('%s' % amount)
    appid_detail.save(auto_commit=False)
    withdraw_record = WithdrawRecord()
    withdraw_record.id = generate_long_id('pay')
    withdraw_record.appid = appid
    withdraw_record.mchid = mchid
    withdraw_record.real_pay = real_pay
    withdraw_record.bank_name = bank_name
    withdraw_record.amount = Decimal(amount)
    withdraw_record.extend = extend
    withdraw_record.acc_name = acc_name
    withdraw_record.withdraw_type = withdraw_type
    withdraw_record.fee = Decimal('%s' % fee)
    withdraw_record.status = WITHDRAW_STATUS.READY
    withdraw_record.order_code = order_code
    withdraw_record.channel = channel
    withdraw_record.acc_name = acc_name
    withdraw_record.to_account = to_account
    withdraw_record.trans_time = trans_time
    withdraw_record.save(auto_commit=False)
    orm.session.commit()
    return withdraw_record
Beispiel #5
0
def query_balance(custid):
    url = "https://caspay.sandpay.com.cn/agent-main/openapi/queryBalance"
    key = get_random_str()
    order_code = id_generator.generate_long_id("pay")
    print 'order_code', order_code
    payload = {
        "version": "01",
        "productId": "00000004",
        "tranTime": tz.local_now().strftime("%Y%m%d%H%M%S"),
        "orderCode": str(order_code),
        "channelType": "08",
        "extend": "",
    }
    _data = json.dumps(payload, ensure_ascii=False).replace(' ', '')
    _rsakey = RSA.importKey(_PUBLIC_KEY)
    cipher = Cipher_pkcs1_v1_5.new(_rsakey)
    data = {
        "transCode": "MBQU",
        "accessType": "1",
        "merId": custid,  # 子商户号
        "plId": "P47428",  # 平台商户号
        "encryptKey": b64encode(cipher.encrypt(key)),
        "encryptData": aes_crypto(_data, key),
        "sign": b64encode(sign_string(_data)),
        "extend": "",
    }
    resp = requests.post(url, data=data)
    resp_dct = parse_qs(unquote(resp.text))
    encrypt_data = resp_dct['encryptData'][0]
    encrypt_key = resp_dct['encryptKey'][0]
    aes_key = decrypt_aes_key(encrypt_key)
    cipher = AES.AESCipher(aes_key)
    decrypt_data = cipher.decrypt(b64decode(encrypt_data.replace(' ', '+')))
    _LOGGER.info('sand agent pay decrypt_data: %s' % decrypt_data)
    resp_detail = json.loads(decrypt_data.split('}')[0] + '}')
    return resp_detail
Beispiel #6
0
def keda_jinjian():
    '''
    进件格式:
    {
        "appid": "xxxxx",
        "signature": "yyyyyy",
        "mchName": "bankLinkNumber"
        "address": "xx路yy街道"
    }
    '''
    _OFFICECODE = '0000000035'
    _KEY = 'UyRk88Ec'
    columns = ('bankLinkNumber', 'mchName', 'mchShortName', 'city', 'province',
               'district', 'address', 'mobile', 'bankNo', 'industryNo',
               'balanceType', 'balanceName', 'userIdNumber', 'cardImgA',
               'legalIdNumber', 'cardNumbercontact', 'licenseStartDate',
               'licenseScope', 'licenseImg', 'paymentType', 'zfbpay', 'wxpay',
               'accountLicense', 'licensePeriod', 'licenseEndDate', 'wxValue',
               'aliValue', 'cardNumber', 'contact', 'licenseNum')
    file_columns = ('legalIDCardA', 'legalIDCardB', 'userIDCardA',
                    'userIDCardB', 'cardImgA', 'licenseImg')
    jinjian_id = generate_long_id('jinjian')
    post_files = {}
    for file_column in file_columns:
        f = request.files.get(file_column)
        if f:
            filename = secure_filename(f.filename)
            d = os.path.join('/home/ubuntu/flask-env/data/jinjian',
                             str(jinjian_id))
            os.makedirs(d)
            fp = os.path.join(d, filename)
            f.save(fp)
            post_files[file_column] = (file_column, open(fp, 'rb'))
    post_data = {}
    for column in columns:
        value = request.form.get(column)
        if value:
            post_data[column] = value
    appid = request.form['appid']
    check_jinjian_sign(post_data, appid, request.form['signature'])
    url = 'http://116.62.100.174/Bank/mobile/zhBank/addMerchant'
    post_data['officeCode'] = _OFFICECODE
    post_data['notifyUrl'] = 'http://p.51paypay.net/api/v1/callback'
    auth_str = json.dumps({'officeCode': _OFFICECODE, 'KEY': _KEY})
    k = pyDes.des(_KEY,
                  pyDes.ECB,
                  "\0\0\0\0\0\0\0\0",
                  pad=None,
                  padmode=pyDes.PAD_PKCS5)
    d = base64.b64encode(k.encrypt(auth_str))

    headers = {'Authorization': d}

    resp = requests.post(url=url,
                         data=post_data,
                         headers=headers,
                         files=post_files)
    if resp.status_code == 200:
        content = resp.content
        resp_data = json.loads(content)
        """
        {
            "message": "进件申请成功,等待审核!",
            "error": 0,
            "data":{
                "bankLinkNumber":"308584000013",
                "merchantCode":"T20170921145929293"
            },
            "success":true
        }
        """
        mch_name = post_data.get('mchShortName')
        if resp_data.get('success') and resp_data.get('error') == 0:
            custid = resp_data['data']['merchantCode']
        else:
            custid = None
        create_jinjian_record(appid,
                              REAL_PAY.KEDA,
                              json.dumps(post_data),
                              content.encode('utf-8'),
                              mch_name=mch_name,
                              custid=custid,
                              jinjian_id=jinjian_id,
                              status=0)
        return resp_data
    else:
        _LOGGER.info("keda jinjian response error")
        _LOGGER.info(post_data)
        return '{"message":"system error", "error":-1,"success":false}'
Beispiel #7
0
def init_jinjian(user_id, real_pay, form, files, payment_type):
    appid_detail = Appid.query.order_by(
        Appid.appid.desc()).with_for_update(of='account_appid').first()
    appid = (appid_detail.appid if appid_detail else 0) + 1
    appkey = uuid.uuid4().hex
    appmanage = AppManage()
    appmanage.accountid = user_id
    appmanage.appid = appid
    appmanage.paymenttype = payment_type
    extend = {
        'url': form.get('url'),
        'serviceTel': form.get('serviceTel'),
        'legalMobile': form.get('legalMobile'),
        'ic_card': form.get('ic_card', '')
    }
    appmanage.extend = json.dumps(extend)
    print 'form', form
    print 'files', files
    if payment_type == 'D0':  # 浦发d0
        appmanage.appname = form.get('pf_appname')
        appmanage.app_type = form.get('pf_app_type')
        pf_pay_type = []
        for key in ['pf_pay_type_wx', 'pf_pay_type_zfb', 'pf_pay_type_zfbh5']:
            if form.get(key):
                pf_pay_type.append(int(form.get(key)))
        appmanage.pay_type = json.dumps(pf_pay_type)
    if payment_type == 'D1':
        appmanage.appname = form.get('zh_appname')
        appmanage.app_type = form.get('zh_app_type')
        zh_pay_type = []
        for key in ['zh_pay_type_wx', 'zh_pay_type_zfb', 'zh_pay_type_zfbh5']:
            if form.get(key):
                zh_pay_type.append(int(form.get(key)))
        appmanage.pay_type = json.dumps(zh_pay_type)
    appmanage.mch_number = form.get('mchNumber')
    appmanage.mch_name = form.get('mchName')
    appmanage.mch_short_name = form.get('mch_short_name')
    appmanage.balance_type = form.get('balance_type')
    appmanage.balance_name = form.get('balance_name')
    appmanage.valid = APPID_STATUS.UNREADY
    appmanage.userid_card = form.get('userid_card')
    appmanage.bank_city = form.get('bank_city')
    appmanage.card_name = form.get('card_name')
    appmanage.card_number = form.get('card_number')
    appmanage.bank_name = form.get('bank_name')
    appmanage.bank_no = form.get('bank_no')
    appmanage.industry_no = _convert_mch_type(long(form.get('industryNo')))
    appmanage.save(auto_commit=False)
    orm.session.flush()
    record = JinjianRecord()
    record.id = id_generator.generate_long_id("jinjian")
    form_dct = {}
    for key, value in form.items():
        if key in [
                'officeCode', 'bankLinkNumber', 'mchName', 'mchShortName',
                'city', 'province', 'district', 'address', 'mobile', 'bankNo',
                'industryNo', 'balanceType', 'balanceName', 'userIdNumber',
                'legalIdNumber', 'cardNumber', 'contact', 'wxUseParent',
                'licenseNum', 'licenseStartDate', 'licensePeriod',
                'licenseEndDate', 'licenseScope', 'useDine', 'wxValue',
                'aliValue', 'zfbpay', 'wxpay', 'notifyUrl', 'appid',
                'payDirectory'
        ]:
            form_dct[key] = value
    form_dct['paymentType'] = payment_type
    _officeCode = '0000000035'
    form_dct['officeCode'] = _officeCode

    for key in files:
        if files[key] and key in [
                'userIDCardA', 'userIDCardB', 'cardImgA', 'licenseImg',
                'mchFrontImg', 'mchInnerImg', 'mchDeskImg', 'accountLicense',
                'inScene', 'outScene', 'legalIDCardA', 'legalIDCardB'
        ]:
            form_dct[key] = _save_file(files[key])
    pufa_banklinknumber = '310290000013'
    zhaoshang_banklinknumber = '308584000013'
    if payment_type == 'D0':  # 浦发d0
        form_dct["bankLinkNumber"] = pufa_banklinknumber
        record.banklinknumber = pufa_banklinknumber
    if payment_type == 'D1':
        form_dct.pop("wxValue", '')
        form_dct.pop("aliValue", '')
        form_dct["bankLinkNumber"] = zhaoshang_banklinknumber
        record.banklinknumber = zhaoshang_banklinknumber
    if form_dct["licensePeriod"] != "1":
        form_dct.pop("licensePeriod")
    record.accountid = user_id
    mch_name = form.get('mchName', '') or form.get('mchtName', '')
    record.paymenttype = payment_type
    record.appmanageid = appmanage.id
    record.mch_name = mch_name
    record.real_pay = real_pay
    record.jinjian_data = json.dumps(form_dct)
    record.status = VALID_STATUS.AUDIT
    record.save(auto_commit=False)
    pay_type = json.loads(appmanage.pay_type)
    for key in pay_type:
        account_appid = Appid()
        account_appid.appid = appid
        account_appid.appkey = appkey
        account_appid.accountid = user_id
        account_appid.valid = APPID_STATUS.UNVALID
        account_appid.pay_type = key
        account_appid.real_pay = real_pay
        account_appid.save(auto_commit=False)
    orm.session.commit()
Beispiel #8
0
def test_agent_pay():
    # url = "http://61.129.71.103:7970/agent-main/openapi/agentpay"
    url = "https://caspay.sandpay.com.cn/agent-main/openapi/agentpay"
    key = get_random_str()
    # iv = Random.new().read(AES.block_size)
    order_code = id_generator.generate_long_id("pay")
    print 'order_code', order_code

    payload = {
        "version": "01",
        "productId": "00000004",
        "tranTime":
        (datetime.now() + timedelta(hours=8)).strftime("%Y%m%d%H%M%S"),
        "orderCode": order_code,
        "timeOut": '20171024120000',
        "tranAmt": "000000000050",
        "currencyCode": "156",
        "accAttr": "0",
        "accType": "4",
        "accNo": "6230582000023229449",
        "accName": u"陈喻君".encode('utf-8'),
        "provNo": "100016",
        "cityNo": "100017",
        "bankName": "",
        "bankType": "",
        "remark": "",
        "payMode": "2",  # 1 ? 2 ?
        "channelType": "07",
        # "extendParams": "",
        "reqReserved": "",
        "noticeUrl": "",
        "extend": "",
    }
    _data = json.dumps(payload, ensure_ascii=False).replace(' ', '')
    _rsakey = RSA.importKey(_PUBLIC_KEY)
    cipher = Cipher_pkcs1_v1_5.new(_rsakey)
    data = {
        "transCode": "RTPM",
        "accessType": "1",
        "merId": "Z1033992",
        "plId": "P47428",
        # "merId": "P47428",
        # "plId": "P47428",
        "encryptKey": b64encode(cipher.encrypt(key)),
        "encryptData": aes_crypto(_data, key),
        "sign": b64encode(sign_string(_data)),
        "extend": "",
    }
    print 'req_data', data
    resp = requests.post(url, data=data)
    print resp.content
    resp_dct = parse_qs(unquote(resp.text))
    print resp_dct
    print 'status', resp.status_code
    print 'text', resp.text
    encrypt_data = resp_dct['encryptData'][0]
    print 'encrypt_data: ', encrypt_data
    encrypt_key = resp_dct['encryptKey'][0]
    print encrypt_key
    # 解密AES key
    aes_key = decrypt_aes_key(encrypt_key)
    print 'aes_key: ', aes_key
    cipher = AES.AESCipher(aes_key)
    resp_detail = json.loads(cipher.decrypt(b64decode(encrypt_data)))
    return resp_detail