# -*- coding: utf-8 -*- # !/usr/bin/env python import logging from typing import TYPE_CHECKING import simplejson as json from apps.web.core import SaobeiMixin from library.saobei import SaobeiSignatureError, SaobeiValidationError from library.saobei import SaobeiPay from apilib.monetary import RMB from apps.web.constant import AppPlatformType from apps.web.core.payment.base import PaymentGateway if TYPE_CHECKING: from apps.web.core.models import SaobeiPayApp logger = logging.getLogger(__name__) class SaobeiPaymentGateway(PaymentGateway, SaobeiMixin): PayTypeMap = { AppPlatformType.WECHAT: '010', AppPlatformType.ALIPAY: '020', AppPlatformType.JD: '080' } def __init__(self, app, gateway_type): # type: (SaobeiPayApp, AppPlatformType)->None super(SaobeiPaymentGateway, self).__init__(app) self.__gateway_type__ = gateway_type @property def __client__(self): # type: ()->SaobeiPay return SaobeiPay(self.merchant_no, self.terminal_id, self.app.access_token, self.debug) def _to_fen(self, rmb): # type: (RMB)->int return str(int(rmb.amount * 100)) def create_pay_url(self, pay_trace, pay_time, money, attach, body, notify_url, front_url = ''): data = { 'attach': json.dumps(attach, separators = (',', ':')) if attach else '', 'order_body': body, 'auto_pay': '0', 'notify_url': notify_url } if front_url: data.update({'front_url': front_url}) url = self.client.generate_wap_pay_url( pay_trace = pay_trace, pay_time = pay_time, total_fee = str(self._to_fen(money)), **data) return url def api_trade_query(self, pay_trace, pay_time): result = self.client.api_trade_query(pay_type = self.PayTypeMap[self.gateway_type], pay_trace = pay_trace, pay_time = pay_time) return result def check(self, data, order = True, token = True): key_sign = data.pop('key_sign') if self.merchant_no != data['merchant_no']: raise SaobeiValidationError( errmsg = u'商户号不一致', lvalue = self.merchant_no, rvalue = data['merchant_no'], client = self) if self.terminal_id != data['terminal_id']: raise SaobeiValidationError( errmsg = u'终端ID不一致', lvalue = self.terminal_id, rvalue = data['terminal_id'], client = self) re_key_sign = self.client.sign(data, order, token) if key_sign != re_key_sign: raise SaobeiSignatureError(lvalue = re_key_sign, rvalue = key_sign, client = self) def __repr__(self): return \ '' % ( str(self.occupantId), self.merchant_no, self.terminal_id, self.debug)