wx_app_pay.py 4.67 KB
Newer Older
1
# -----------------------------------------------------------------------------
2
# File Name: wx_app_pay.py
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
# Author:    X. Peng
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# Constants
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# Functions
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# Classes
# -----------------------------------------------------------------------------
import requests
import hashlib
import time
from xml.etree import cElementTree as etree
import random
from urllib import parse

28 29 30
from app.api.engine import config, env


31 32 33 34 35 36 37 38 39
def genNonce_str():
    """."""
    sss = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    s = ''
    for i in range(32):
        s = s + random.choice(sss)
    return s

class WXPay(object):
pengxiong's avatar
pengxiong committed
40
    """微信APP支付."""
41
    def __init__(self, out_trade_no, body, total_fee, remote_addr, notify_url):
pengxiong's avatar
pengxiong committed
42
        """."""
43 44
        self.timeStamp = int(time.time())
        self.req_url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
45
        self.appid = 'wx3ad4c5856975a2c4'
46 47 48 49 50 51
        self.mch_id = '1515329071'
        self.nonce_str = genNonce_str()
        self.sign = None
        self.sign_type = 'MD5'
        self.body = body
        self.out_trade_no = out_trade_no
pengxiong@wealthgrow.cn's avatar
pengxiong@wealthgrow.cn committed
52
        self.total_fee = int(total_fee)
53
        self.spbill_create_ip = remote_addr
54
        self.notify_url = notify_url
55
        self.trade_type = 'APP'
56 57 58
        self.key = 'eqwor3wquevncz9384ssp438oarefskl'
        self.getStringSign()
        self.getData()
59 60
        self.getPrepayId()
        self.getPaySign()
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111


    def getStringSign(self):
        """."""
        self.string_sign_temp = 'appid={0}&body={1}&mch_id={2}&nonce_str={3}&notify_url={4}&out_trade_no={5}&sign_type={6}&spbill_create_ip={7}&total_fee={8}&trade_type={9}&key={10}'.format(
            self.appid,
            self.body,
            self.mch_id,
            self.nonce_str,
            self.notify_url,
            self.out_trade_no,
            self.sign_type,
            self.spbill_create_ip,
            self.total_fee,
            self.trade_type,
            self.key
        )

    def getData(self):
        """."""
        self.sign = hashlib.md5(self.string_sign_temp.encode("utf-8")).hexdigest().upper()
        self.data = {
            'appid': self.appid,
            'body': self.body,
            'mch_id': self.mch_id,
            'nonce_str': self.nonce_str,
            'notify_url': self.notify_url,
            'out_trade_no': self.out_trade_no,
            'sign_type': self.sign_type,
            'spbill_create_ip': self.spbill_create_ip,
            'total_fee': self.total_fee,
            'trade_type': self.trade_type,
            'sign': self.sign
        }

    def dict2xml(self, dict_):
        """将dict转为要发送到微信服务器的xml格式."""
        s = ""
        for k, v in dict_.items():
            s += "<{0}>{1}</{0}>".format(k, v)
        s = "<xml>{0}</xml>".format(s)
        return s.encode("utf-8")

    def xml2dict(self, content):
        """将从微信服务器接收到的xml转为dict."""
        raw = {}
        root = etree.fromstring(content)
        for child in root:
            raw[child.tag] = child.text
        return raw

112
    def getPrepayId(self):
113 114 115
        """."""
        res = requests.post(self.req_url, data=self.dict2xml(self.data))
        res = self.xml2dict(res.content)
116 117 118 119
        self.prepay_id = res['prepay_id']

    def getPaySign(self):
        """."""
120 121
        sign_string = 'appid={0}&noncestr={1}&package={2}&partnerid={3}&prepayid={4}&timestamp={5}&key={6}'.format(
            self.appid, self.nonce_str, 'Sign=WXPay', self.mch_id, self.prepay_id, self.timeStamp, self.key)
122
        self.paySign = hashlib.md5(sign_string.encode("utf-8")).hexdigest().upper()
123

124 125
    def getReturnParams(self):
        """."""
126 127
        params = {'appid': self.appid, 'noncestr': self.nonce_str, 'package': 'Sign=WXPay', 'partnerid': self.mch_id, 'prepayid': self.prepay_id,
                'timestamp': self.timeStamp, 'sign': self.paySign}
128 129
        return params

130
if __name__ == '__main__':
131
    out_trade_no = '201812102324324134112'
132
    body = 'APP支付测试'
133 134 135
    total_fee = 0.01
    remote_addr = '101.95.188.178'
    wx = WXPay(out_trade_no, body, total_fee, remote_addr)
136
    print(wx.getReturnParams())