#橙券支付

import hashlib
import datetime
import time
import json 
import urllib.request
import urllib.parse

domain='https://api.chengquan.cn'

# appid='15020190001'
# k='0BE0C9FEE504983B285B9407CB9C85D9'
# domain='http://test.api.chengquan.cn'

class CQPay:

    def __init__(self, appid, k):
        self.appid = appid
        self.k =k

    def generate_sign(self,data):
        jsonstr = json.dumps(data, sort_keys=True)
        params_json = json.loads(jsonstr)
        items = params_json.items()
        ostr=''
        for key, value in items:
            if value:
                ostr = ostr + str(key) + '=' + str(value) + '&'
        ostr = ostr + 'key='+self.k
        #print(ostr)
        m2 = hashlib.md5(ostr.encode(encoding='UTF-8'))
        return m2.hexdigest()

    def http_post(self,data, type, url):
        timestamp = int(round(time.time() * 1000))
        data['timestamp'] = timestamp
        data['app_id'] = self.appid
        data['type'] = type
        sign = self.generate_sign(data)
        data['sign'] = sign 
        #print(data)
        data = json.dumps(data)
        data = bytes(data,"utf8")
        headers={'Content-Type':'application/json'}   
        request = urllib.request.Request(domain+url, data, headers)   
        res = urllib.request.urlopen(request).read().decode('utf-8')
        return json.loads(res)

    # 微信转账发放下单接口
    def unite_submit(self,project_no, open_id, out_request_no, wechat_app_id, wishing, amount):
        data = {
            'project_no': project_no,
            'open_id': open_id,
            'out_request_no': out_request_no,
            'wechat_app_id': wechat_app_id,
            'wishing': wishing,
            'amount': amount,
            'ip': '116.62.122.204'
        }
        return self.http_post(data,'WECHAT_TRANSFER', '/voucher_platform/unite/submit')

    def unite_query(self,out_request_no):
        data = {
            'out_request_no': out_request_no
        }
        return self.http_post(data,'WECHAT_TRANSFER', '/voucher_platform/unite/query')

#unite_query('test')
#res = unite_submit('100869',"oqqkG6de7so5uKmzIbJfWq9Ys8uo","1690789512497","wxf2d346fbfaf83e1d","测试",1)
#print(res)