django 위챗 인터페이스 호출(위챗 결제, 위챗 사용자 정보)

19107 단어 django
class WeChatPay(object):
    def __init__(self, order_id, body, total_fee, nonce_str, spbill_create_ip='8.8.8.8'):
        """
        :param order_id:   ID
        :param body:     
        :param total_fee:     
        :param nonce_str: 32       
        :param spbill_create_ip:      IP  
        appid = '  appid'
    AppSecret = '  AppSecret'
    mch_id = '    id'
    api_key = '      '
        """
        self.params = {
            'appid': YOUR_WX_APPID,
            'mch_id': YOUR_MCH_ID,
            'nonce_str': nonce_str,
            'body': str(body),
            'out_trade_no': str(order_id),
            'total_fee': str(int(total_fee)),#    
            'spbill_create_ip': spbill_create_ip,#      
            'trade_type': 'APP',  # 'APP',
            'notify_url': YOUR_NOTIFY_URL,#        
        }

        self.WxPay_request_url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'  #     url
        self.error = None

    def key_value_url(self, value):
        """        key1=value1&key2=value2
        """
        pair_array = []
        string_sign = ''
        for k in sorted(value.keys()):
            string_sign += "{0}={1}&".format(k, value[k])
        print(string_sign)
        return string_sign

    def get_sign(self, params):
        """  sign
        """
        stringA = self.key_value_url(params)
        stringSignTemp = stringA + 'key=' + current_app.config['APIKEY']   # APIKEY, API  ,         
        print(stringSignTemp)
        sign = hashlib.md5(stringSignTemp.encode('utf-8')).hexdigest().upper()
        params['sign'] = sign

    def get_req_xml(self):
        """  XML
        """
        self.get_sign(self.params)
        xml = ""
        for k in sorted(self.params.keys()):
            xml += '{1}{0}>'.format(k, self.params[k])
        xml += ""
        print(xml)
        return xml.encode('utf-8')

    def get_prepay_id(self):
        """
            prepay_id
        """
        import requests
        xml = self.get_req_xml()
        unifiedorderXML = requests.post('https://api.mch.weixin.qq.com/pay/unifiedorder', data=xml)
        unifiedorderXML.encoding ='utf-8'
        unifiedorderXML = unifiedorderXML.text
        print(unifiedorderXML)
        tree = et.parse(unifiedorderXML)
        root = tree.getroot()
        if root.find("result_code").text != 'SUCCESS':
            self.error = u"       !"
            print(self.error)
        prepay_id = root.find("prepay_id").text

        self.params['prepay_id'] = prepay_id
        self.params['package'] = 'Sign=WXPay'
        self.params['timestamp'] = str(int(time.time()))

    def re_finall(self):
        """  prepay_id     ,       
        """
        self.get_prepay_id()
        if self.error:
            return

        sign_again_params = {
            'appid': self.params['appid'],
            'noncestr': self.params['nonce_str'],
            'package': self.params['package'],
            'partnerid': self.params['mch_id'],
            'timestamp': self.params['timestamp'],
            'prepayid': self.params['prepay_id']
        }
        self.get_sign(sign_again_params)
        self.params['sign'] = sign_again_params['sign']

        #            
        print('    :', self.params)
        parms_keys = []
        for i in self.params.keys():
            parms_keys.append(i)
        for i in parms_keys:
            if i not in ['appid', 'mch_id', 'nonce_str', 'timestamp', 'sign', 'package', 'prepay_id']:
                self.params.pop(i)
        print('     parms:', self.params)
        return self.params

좋은 웹페이지 즐겨찾기