#橙券支付

import hashlib
import datetime
import time
import json 
import random
import base64
import urllib.request
import urllib.parse
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

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

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

class CQPay:

    def __init__(self, appid, k, aes_key='', aes_iv=''):
        self.appid = appid
        self.k =k
        self.aes_key = aes_key
        self.aes_iv = aes_iv

    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 http_post_form(self, data, type, url):
        timestamp = int(round(time.time() * 1000))
        data['timestamp'] = timestamp
        data['app_id'] = self.appid
        if type:
            data['type'] = type
        sign = self.generate_sign(data)
        data['sign'] = sign 
        data = urllib.parse.urlencode(data).encode('utf-8')
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}   
        request = urllib.request.Request(domain + url, data, headers)   
        res = urllib.request.urlopen(request).read().decode('utf-8')
        return json.loads(res)
        
    # 解密
    def decrypt_p(self, text):
        cipher = AES.new(self.aes_key.encode('utf-8'), AES.MODE_CBC, self.aes_iv.encode('utf-8'))
        # 将密文进行 base64解码
        ciphertext = base64.b64decode(text)
        # 解密并去除填充
        decrypted_text = unpad(cipher.decrypt(ciphertext), AES.block_size)
        return decrypted_text.decode('utf-8')
        
    # 微信转账发放下单接口
    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')
    
    # 优惠券、打车券等下单接口
    def coupon_order_pay(self, user_order_no, goods_no, count, mobile):
        data = {
            'user_order_no': user_order_no,
            'goods_no': goods_no,
            'count': count,
        }
        if mobile:
            data['mobile'] = mobile
        return self.http_post_form(data, '', '/coupon/order/pay')
    
    # 生成订单号
    def generate_order_number():
        timestamp = int(time.time())
        random_number = random.randint(1000, 9999)
        order_number = str(timestamp) + str(random_number)
        return order_number
        
#unite_query('test')
#res = unite_submit('100869',"oqqkG6de7so5uKmzIbJfWq9Ys8uo","1690789512497","wxf2d346fbfaf83e1d","测试",1)
#print(res)