Beispiel #1
0
def query_mch_pay(pay):
    """
    微信支付查询企业付款
    :param pay:
    :return:
    """
    wx = current_app.config['WEIXIN']
    wx_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo'
    template = 'weixin/pay/mch_pay_query.xml'
    params = {
        'nonce_str': generate_random_key(16),
        'partner_trade_no': pay.partner_trade_no,
        'mch_id': wx['mch_id'],
        'appid': wx['app_id']
    }
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    cert = (wx['cert_path'], wx['key_path'])
    resp = requests.post(wx_url,
                         data=xml.encode('utf-8'),
                         headers=_HEADERS,
                         verify=VERIFY,
                         cert=cert)
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        assert 'result_code' in result, result.get('return_msg')
        pay.update_query_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)
Beispiel #2
0
def cancel_order(order):
    """
    微信支付关闭/撤销订单
    :param order:
    :return:
    """
    wx = current_app.config['WEIXIN']
    if order.trade_type == 'MICROPAY':
        wx_url = 'https://api.mch.weixin.qq.com/secapi/pay/reverse'
        template = 'weixin/pay/micropay_order_reverse.xml'
    else:
        wx_url = 'https://api.mch.weixin.qq.com/pay/closeorder'
        template = 'weixin/pay/unified_order_close.xml'
    params = {
        'appid': wx.get('app_id'),
        'mch_id': wx.get('mch_id'),
        'out_trade_no': order.out_trade_no,
        'nonce_str': generate_random_key(16)
    }
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    resp = requests.post(
        wx_url,
        data=xml.encode('utf-8'),
        headers={'Content-Type': 'application/xml; charset="utf-8"'},
        cert=(wx.get('cert_path'), wx.get('key_path')))
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        sign = result.pop('sign')
        assert sign == generate_pay_sign(wx, result), u'微信支付签名验证失败'
        order.update_cancel_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)
Beispiel #3
0
def query_red_pack(pack):
    """
    微信支付查询红包记录
    :param pack:
    :return:
    """
    wx = current_app.config['WEIXIN']
    wx_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo'
    template = 'weixin/pay/red_pack_query.xml'
    params = {
        'nonce_str': generate_random_key(16),
        'mch_billno': pack.mch_billno,
        'mch_id': wx.get('mch_id'),
        'appid': wx.get('app_id'),
        'bill_type': 'MCHT'
    }
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    resp = requests.post(
        wx_url,
        data=xml.encode('utf-8'),
        headers={'Content-Type': 'application/xml; charset="utf-8"'},
        cert=(wx.get('cert_path'), wx.get('key_path')))
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        assert 'result_code' in result, result.get('return_msg')
        pack.update_query_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)
Beispiel #4
0
def query_order(order):
    """
    微信支付查询订单
    :param order:
    :return:
    """
    wx = current_app.config['WEIXIN']
    wx_url = 'https://api.mch.weixin.qq.com/pay/orderquery'
    template = 'weixin/pay/order_query.xml'
    params = {
        'appid': wx.get('app_id'),
        'mch_id': wx.get('mch_id'),
        'out_trade_no': order.out_trade_no,
        'nonce_str': generate_random_key(16)
    }
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    resp = requests.post(
        wx_url,
        data=xml.encode('utf-8'),
        headers={'Content-Type': 'application/xml; charset="utf-8"'})
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        sign = result.pop('sign')
        assert sign == generate_pay_sign(wx, result), u'微信支付签名验证失败'
        order.update_query_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)
Beispiel #5
0
def apply_for_mch_pay(pay):
    """
    微信支付企业付款
    :param pay:
    :return:
    """
    if pay.status in ['SUCCESS', 'PROCESSING']:
        return

    wx = current_app.config['WEIXIN']
    wx_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'
    template = 'weixin/pay/mch_pay.xml'
    params = pay.to_dict(only=('device_info', 'partner_trade_no', 'openid',
                               'check_name', 're_user_name', 'amount', 'desc',
                               'spbill_create_ip'))
    params['mch_appid'] = wx.get('app_id')
    params['mchid'] = wx.get('mch_id')
    params['nonce_str'] = generate_random_key(16)
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    resp = requests.post(
        wx_url,
        data=xml.encode('utf-8'),
        headers={'Content-Type': 'application/xml; charset="utf-8"'},
        cert=(wx.get('cert_path'), wx.get('key_path')))
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        assert 'result_code' in result, result.get('return_msg')
        pay.update_pay_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)
Beispiel #6
0
def query_red_pack(pack):
    """
    微信支付查询红包记录
    :param pack:
    :return:
    """
    wx = current_app.config['WEIXIN']
    wx_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo'
    template = 'weixin/pay/red_pack_query.xml'
    params = {
        'nonce_str': generate_random_key(16),
        'mch_billno': pack.mch_billno,
        'mch_id': wx['mch_id'],
        'appid': wx['app_id'],
        'bill_type': 'MCHT'
    }
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    cert = (wx['cert_path'], wx['key_path'])
    resp = requests.post(wx_url,
                         data=xml.encode('utf-8'),
                         headers=_HEADERS,
                         verify=VERIFY,
                         cert=cert)
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        sign = result.pop('sign')
        assert sign == generate_pay_sign(wx, result), u'微信支付签名验证失败'
        pack.update_query_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)
Beispiel #7
0
def get_weixin_js_sdk_config():
    """
    获取微信JS-SDK权限验证配置信息
    :return:
    """
    url = request.args.get('url')
    claim_args(1201, url)
    wx = current_app.config['WEIXIN']
    jsapi_ticket = get_jsapi_ticket(wx)
    claim_args(1802, jsapi_ticket)

    noncestr = generate_random_key(16)
    timestamp = int(time.time())
    items = [
        'jsapi_ticket=%s' % jsapi_ticket,
        'noncestr=%s' % noncestr,
        'timestamp=%s' % timestamp,
        'url=%s' % url
    ]
    items.sort()
    signature = hashlib.sha1('&'.join(items)).hexdigest()
    data = {
        'app_id': wx.get('app_id'),
        'noncestr': noncestr,
        'timestamp': timestamp,
        'signature': signature
    }
    return api_success_response(data)
Beispiel #8
0
def query_refund(refund):
    """
    微信支付查询退款
    :param refund:
    :return:
    """
    wx = current_app.config['WEIXIN']
    wx_url = 'https://api.mch.weixin.qq.com/pay/refundquery'
    template = 'weixin/pay/refund_query.xml'
    params = {
        'appid': wx['app_id'],
        'mch_id': wx['mch_id'],
        'nonce_str': generate_random_key(16),
        'out_refund_no': refund.out_refund_no
    }
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    resp = requests.post(wx_url,
                         data=xml.encode('utf-8'),
                         headers=_HEADERS,
                         verify=VERIFY)
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        sign = result.pop('sign')
        assert sign == generate_pay_sign(wx, result), u'微信支付签名验证失败'
        refund.update_query_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)
Beispiel #9
0
    def create_weixin_mch_pay(cls, openid, check_name, amount, desc, spbill_create_ip, device_info=None,
                              re_user_name=None):
        """
        创建微信支付企业付款
        :param openid:
        :param check_name:
        :param amount:
        :param desc:
        :param spbill_create_ip:
        :param device_info:
        :param re_user_name:
        :return:
        """
        try:
            return cls.create(
                partner_trade_no=generate_random_key(28, current_app.config['WEIXIN'].get('mch_id')
                                                     + datetime.date.today().strftime('%Y%m%d'), 'd'),
                openid=openid.strip(),
                check_name=check_name.strip(),
                amount=amount,
                desc=desc.strip(),
                spbill_create_ip=spbill_create_ip.strip(),
                device_info=_nullable_strip(device_info),
                re_user_name=_nullable_strip(re_user_name)
            )

        except Exception, e:
            current_app.logger.error(e)
Beispiel #10
0
    def create_wx_pay_order(cls, body, total_fee, spbill_create_ip, trade_type, device_info=None, detail=None,
                            attach=None, fee_type=None, time_start=None, time_expire=None, goods_tag=None,
                            product_id=None, limit_pay=None, openid=None, scene_info=None, auth_code=None):
        """
        创建微信支付订单
        :param body:
        :param total_fee:
        :param spbill_create_ip:
        :param trade_type:
        :param device_info:
        :param detail:
        :param attach:
        :param fee_type:
        :param time_start:
        :param time_expire:
        :param goods_tag:
        :param product_id:
        :param limit_pay:
        :param openid:
        :param scene_info:
        :param auth_code:
        :return:
        """
        try:
            return cls.create(
                body=body.strip(),
                out_trade_no=generate_random_key(24, datetime.date.today().strftime('%Y%m%d'), 'd'),
                total_fee=total_fee,
                spbill_create_ip=spbill_create_ip.strip(),
                trade_type=trade_type.strip(),
                device_info=_nullable_strip(device_info),
                detail=_nullable_strip(detail),
                attach=_nullable_strip(attach),
                fee_type=_nullable_strip(fee_type),
                time_start=_nullable_strip(time_start),
                time_expire=_nullable_strip(time_expire),
                goods_tag=_nullable_strip(goods_tag),
                product_id=_nullable_strip(product_id),
                limit_pay=_nullable_strip(limit_pay),
                openid=_nullable_strip(openid),
                scene_info=_nullable_strip(scene_info),
                auth_code=_nullable_strip(auth_code)
            )

        except Exception, e:
            current_app.logger.error(e)
Beispiel #11
0
def place_order(order):
    """
    微信支付统一下单/提交刷卡支付
    :param order:
    :return:
    """
    if order.order_result_code == 'SUCCESS':
        return

    wx = current_app.config['WEIXIN']
    if order.trade_type == 'MICROPAY':
        wx_url = 'https://api.mch.weixin.qq.com/pay/micropay'
        template = 'weixin/pay/micropay_order.xml'
        params = order.to_dict(only=('device_info', 'body', 'detail', 'attach',
                                     'out_trade_no', 'total_fee', 'fee_type',
                                     'spbill_create_ip', 'goods_tag',
                                     'limit_pay', 'auth_code', 'scene_info'))
    else:
        wx_url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
        template = 'weixin/pay/unified_order.xml'
        params = order.to_dict(only=('device_info', 'body', 'detail', 'attach',
                                     'out_trade_no', 'fee_type', 'total_fee',
                                     'spbill_create_ip', 'time_start',
                                     'time_expire', 'goods_tag', 'trade_type',
                                     'product_id', 'limit_pay', 'openid',
                                     'scene_info'))
        params['notify_url'] = url_for('bp_www_main.wx_pay_notify',
                                       _external=True)
    params['appid'] = wx['app_id']
    params['mch_id'] = wx['mch_id']
    params['nonce_str'] = generate_random_key(16)
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    resp = requests.post(wx_url,
                         data=xml.encode('utf-8'),
                         headers=_HEADERS,
                         verify=VERIFY)
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        sign = result.pop('sign')
        assert sign == generate_pay_sign(wx, result), u'微信支付签名验证失败'
        order.update_order_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)
Beispiel #12
0
def upload_weixin_temp_image_to_qiniu():
    """
    上传微信临时图片素材到七牛
    :return:
    """
    media_id = g.json.get('media_id')
    claim_args(1401, media_id)
    claim_args_string(1402, media_id)
    image = get_temp_image_media(current_app.config['WEIXIN'], media_id)
    claim_args_true(1803, image)

    key = generate_random_key(20, 'img_')
    upload_token = get_upload_token(current_app.config['QINIU'], key)
    claim_args_true(1850, upload_token)
    resp, info = qiniu.put_data(upload_token, key, image)
    claim_args_true(1851, resp and resp.get('key') == key)
    data = {
        'url': 'http://%s/%s' % (current_app.config['QINIU']['domain'], key)
    }
    return api_success_response(data)
Beispiel #13
0
def send_red_pack(pack):
    """
    微信支付发放红包
    :param pack:
    :return:
    """
    if pack.status in ['SENDING', 'SENT', 'RECEIVED', 'RFUND_ING', 'REFUND']:
        return

    wx = current_app.config['WEIXIN']
    template = 'weixin/pay/red_pack.xml'
    if pack.total_num == 1:
        wx_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack'
        params = pack.to_dict(only=('mch_billno', 'send_name', 're_openid',
                                    'total_amount', 'total_num', 'wishing',
                                    'client_ip', 'act_name', 'remark',
                                    'scene_id', 'risk_info', 'consume_mch_id'))
    else:
        wx_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack'
        params = pack.to_dict(only=('mch_billno', 'send_name', 're_openid',
                                    'total_amount', 'total_num', 'amt_type',
                                    'wishing', 'act_name', 'remark',
                                    'scene_id', 'risk_info', 'consume_mch_id'))
    params['nonce_str'] = generate_random_key(16)
    params['mch_id'] = wx.get('mch_id')
    params['wxappid'] = wx.get('app_id')
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    resp = requests.post(
        wx_url,
        data=xml.encode('utf-8'),
        headers={'Content-Type': 'application/xml; charset="utf-8"'},
        cert=(wx.get('cert_path'), wx.get('key_path')))
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        assert 'result_code' in result, result.get('return_msg')
        pack.update_send_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)
Beispiel #14
0
def send_red_pack(pack):
    """
    微信支付发放红包
    :param pack:
    :return:
    """
    if pack.status in ['SENDING', 'SENT', 'RECEIVED', 'RFUND_ING', 'REFUND']:
        return

    wx = current_app.config['WEIXIN']
    if pack.total_num == 1:
        wx_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack'
    else:
        wx_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack'
    template = 'weixin/pay/red_pack.xml'
    params = pack.to_dict(only=('mch_billno', 'send_name', 're_openid',
                                'total_amount', 'total_num', 'amt_type',
                                'wishing', 'client_ip', 'act_name', 'remark',
                                'scene_id', 'risk_info', 'consume_mch_id'))
    params['nonce_str'] = generate_random_key(16)
    params['mch_id'] = wx['mch_id']
    params['wxappid'] = wx['app_id']
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    cert = (wx['cert_path'], wx['key_path'])
    resp = requests.post(wx_url,
                         data=xml.encode('utf-8'),
                         headers=_HEADERS,
                         verify=VERIFY,
                         cert=cert)
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        sign = result.pop('sign')
        assert sign == generate_pay_sign(wx, result), u'微信支付签名验证失败'
        pack.update_send_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)
Beispiel #15
0
    def create_wx_pay_refund(cls, wx_pay_order, refund_fee, refund_fee_type=None, refund_desc=None, refund_account=None):
        """
        创建微信支付退款
        :param wx_pay_order:
        :param refund_fee:
        :param refund_fee_type:
        :param refund_desc:
        :param refund_account:
        :return:
        """
        try:
            return cls.create(
                wx_pay_order=wx_pay_order,
                out_refund_no=generate_random_key(32, wx_pay_order.out_trade_no, 'd'),
                refund_fee=refund_fee,
                refund_fee_type=_nullable_strip(refund_fee_type),
                refund_desc=_nullable_strip(refund_desc),
                refund_account=_nullable_strip(refund_account)
            )

        except Exception, e:
            current_app.logger.error(e)
Beispiel #16
0
    def create_weixin_red_pack(cls, send_name, re_openid, total_amount, total_num, wishing, act_name, remark,
                               amt_type=None, client_ip=None, scene_id=None, risk_info=None, consume_mch_id=None):
        """
        创建微信支付现金红包
        :param send_name:
        :param re_openid:
        :param total_amount:
        :param total_num:
        :param wishing:
        :param act_name:
        :param remark:
        :param amt_type:
        :param client_ip:
        :param scene_id:
        :param risk_info:
        :param consume_mch_id:
        :return:
        """
        try:
            return cls.create(
                mch_billno=generate_random_key(28, current_app.config['WEIXIN'].get('mch_id')
                                               + datetime.date.today().strftime('%Y%m%d'), 'd'),
                send_name=send_name.strip(),
                re_openid=re_openid.strip(),
                total_amount=total_amount,
                total_num=total_num,
                wishing=wishing.strip(),
                act_name=act_name.strip(),
                remark=remark.strip(),
                amt_type=_nullable_strip(amt_type),
                client_ip=_nullable_strip(client_ip),
                scene_id=_nullable_strip(scene_id),
                risk_info=_nullable_strip(risk_info),
                consume_mch_id=_nullable_strip(consume_mch_id)
            )

        except Exception, e:
            current_app.logger.error(e)
Beispiel #17
0
    def create_weixin_pay_refund(cls, weixin_pay_order, refund_fee, op_user_id, refund_fee_type=None,
                                 refund_account=None):
        """
        创建微信支付退款
        :param weixin_pay_order:
        :param refund_fee:
        :param op_user_id:
        :param refund_fee_type:
        :param refund_account:
        :return:
        """
        try:
            return cls.create(
                weixin_pay_order=weixin_pay_order,
                out_refund_no=generate_random_key(28, weixin_pay_order.out_trade_no, 'd'),
                refund_fee=refund_fee,
                op_user_id=op_user_id.strip(),
                refund_fee_type=_nullable_strip(refund_fee_type),
                refund_account=_nullable_strip(refund_account)
            )

        except Exception, e:
            current_app.logger.error(e)
Beispiel #18
0
def apply_for_refund(refund):
    """
    微信支付申请退款
    :param refund:
    :return:
    """
    if refund.refund_status in ['SUCCESS', 'PROCESSING', 'CHANGE']:
        return

    wx = current_app.config['WEIXIN']
    wx_url = 'https://api.mch.weixin.qq.com/secapi/pay/refund'
    template = 'weixin/pay/refund.xml'
    params = refund.to_dict(only=('out_refund_no', 'refund_fee',
                                  'refund_fee_type', 'op_user_id',
                                  'refund_account'))
    params['appid'] = wx.get('app_id')
    params['mch_id'] = wx.get('mch_id')
    params['device_info'] = refund.weixin_pay_order.device_info
    params['nonce_str'] = generate_random_key(16)
    params['out_trade_no'] = refund.weixin_pay_order.out_trade_no
    params['total_fee'] = refund.weixin_pay_order.total_fee
    params['sign'] = generate_pay_sign(wx, params)
    xml = current_app.jinja_env.get_template(template).render(**params)
    resp = requests.post(
        wx_url,
        data=xml.encode('utf-8'),
        headers={'Content-Type': 'application/xml; charset="utf-8"'},
        cert=(wx.get('cert_path'), wx.get('key_path')))
    resp.encoding = 'utf-8'
    try:
        result = xmltodict.parse(resp.text)['xml']
        sign = result.pop('sign')
        assert sign == generate_pay_sign(wx, result), u'微信支付签名验证失败'
        refund.update_refund_result(result)
    except Exception, e:
        current_app.logger.error(e)
        current_app.logger.info(resp.text)