示例#1
0
def GetDoc(docID):
    # Construct full url from parameter and value
    url = config.DOCDB_URL + 'ShowDocument?docid=' + str(
        docID) + '&outformat=xml'

    # Make HTTP request
    response = requests.get(url, auth=('uboone', config.PWD))
    return xmltodict.parse(response.content)
示例#2
0
def CallDocDB(function, parameter, value):
    # Construct full url from parameter and value
    url = config.DOCDB_URL + function + '?' + parameter + '=' + value + '&outformat=xml'

    # Make HTTP request
    response = requests.get(url, auth=('uboone', config.PWD))

    return xmltodict.parse(response.content)
示例#3
0
 def execute_nmap(self, command_arguments = []):
     """Executes nmap command in linux with the server list. The output is in xml format."""
     xml_result = subprocess.Popen(['nmap', '-oX', '-'] + self.server_list + command_arguments, shell=False, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
     # get output
     (self._nmap_last_output, nmap_err) = xml_result.communicate()
     # If there was something on stderr, there was a problem so abort...
     if xml_result.returncode != 0:
         raise  ValueError, "Nmap command failed:", nmap_err
     #parse the xml to ordered dict.
     self.nmap_result = xmltodict.parse(self._nmap_last_output)
     return self.nmap_result
示例#4
0
	def post(self):
		print("[Alipay refund] notify_url!!!!!!!!")
		session = models.DBSession()
		_alipay = WapAlipay(pid=ALIPAY_PID, key=ALIPAY_KEY, seller_email=ALIPAY_SELLER_ACCOUNT)
		sign = self.args.pop('sign')
		signmethod = _alipay.getSignMethod(**self.args)
		if signmethod(self.args) != sign:
			print('sign error')
			return self.write('sign error')
		notify_data = xmltodict.parse(self.args['notify_data'])['notify']
		result_details = notify_data['result_details']
		transaction_id = result_details.split('^')[0]
		balance_history = session.query(models.BalanceHistory).filter_by(transaction_id=transaction_id).first()
		if not balance_history:
			return self.write('old_balance_history not found')
		order = session.query(models.Order).filter_by(transaction_id=transaction_id).first()
		if not order:
			print('order not found')
			return self.write('order not found')
		##########################################################################
		order.del_reason = 'refund'
		order.get_num(session,order.id)  #取消订单,库存增加,在售减少 	
		shop_id = balance_history.shop_id
		balance_value = balance_history.balance_value
		shop = order.shop 
		#该店铺余额减去订单总额
		shop.shop_balance -= balance_value
		balance_history.is_cancel = 1
		#将这条余额记录作废
		balance_history.balance_type = -1
		customer_id = balance_history.customer_id
		name        = balance_history.name
		shop_province = balance_history.shop_province
		shop_name     = balance_history.shop_name
		balance_record = balance_history.balance_record + '--退款'
		create_time   = datetime.datetime.now()
		shop_totalPrice = shop.shop_balance
		customer_totalPrice = balance_history.customer_totalPrice
		transaction_id   = balance_history.transaction_id
		available_balance = balance_history.available_balance
		#同时生成一条退款记录
		refund_history = models.BalanceHistory(customer_id=customer_id,shop_id=shop_id,shop_province=shop_province,shop_name=shop_name,name=name,
			balance_record=balance_record,create_time=create_time,shop_totalPrice=shop_totalPrice,customer_totalPrice=customer_totalPrice,
			transaction_id=transaction_id,balance_type=9,balance_value=balance_value)
		session.add(refund_history)
		# self.session.flush()
		# # 9.15 woody 
		# # 生成一条支付宝退款记录
		# apply_refund = models.ApplyRefund(customer_id=customer_id,order_id=order_id,refund_type=1,refund_fee=totalPrice,
		# 	transaction_id=transaction_id,order_num=num)
		# self.session.add(apply_refund)
		session.commit()
		return self.write('success')
示例#5
0
	def handle_deal_notify(self):
		# 验证签名
		sign = self.args.pop("sign")
		signmethod = self._alipay.getSignMethod(**self.args)
		if signmethod(self.args) != sign:
			Logger.warn("SystemPurchase Notify: sign from alipay error!")
			return self.send_error(403)
		# # 验证notify_id是否存在, 这部分是否需要做?
		# if not self._alipay.verify_notify(**self.args):
		#     Logger.warn("Purchase Notify: notify check illegal!")
		#     return self.send_error(403)
		notify_data = xmltodict.parse(self.args["notify_data"])["notify"]
		# 判断该notify是否已经被处理,已处理直接返回success,未处理填补信息

		o = models.SystemOrder.update_notify_data(
			self.session,
			order_id=int(notify_data["out_trade_no"]),
			notify_data=notify_data)
		if not o:
			Logger.error("SystemPurchase Notify Fatal Error: order not found!")
			return self.write("fail")
		return self.write("success")
示例#6
0
class CoreApi(object):
  def __init__(self):
    self.API_TYPE_REST = 'REST'
    self.API_TYPE_SOAP = 'SOAP'
    self._rest_api_endpoint = ''
    self._soap_api_endpoint = ''
    self._sessions = { self.API_TYPE_REST: None, self.API_TYPE_SOAP: None }
    self.ignore_ssl_validation = False
    self._log_at_level = logging.WARNING
    self.logger = self._set_logging()

  # *******************************************************************
  # properties
  # *******************************************************************
  @property
  def log_at_level(self): return self._log_at_level
  
  @log_at_level.setter
  def log_at_level(self, value):
    """
    Make sure logging is always set at a valid level
    """
    if value in [
      logging.CRITICAL,
      logging.DEBUG,
      logging.ERROR,
      logging.FATAL,
      logging.INFO,
      logging.WARNING,
      ]:
      self._log_at_level = value
      self._set_logging()
    else:
      if not self._log_at_level:
        self._log_at_level = logging.WARNING
        self._set_logging()

  # *******************************************************************
  # methods
  # *******************************************************************
  def _set_logging(self):
    """
    Setup the overall logging environment
    """
    # Based on tips from http://www.blog.pythonlibrary.org/2012/08/02/python-101-an-intro-to-logging/
    logging.basicConfig(level=self.log_at_level)

    # setup module logging
    logger = logging.getLogger("DeepSecurity.API")
    logger.setLevel(self.log_at_level)

    # reset any existing handlers
    logging.root.handlers = [] # @TODO evaluate impact to other modules
    logger.handlers = []

    # add the desired handler
    formatter = logging.Formatter('[%(asctime)s]\t%(message)s', '%Y-%m-%d %H:%M:%S')
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    logger.addHandler(stream_handler)

    return logger

  def _get_request_format(self, api=None, call=None, use_cookie_auth=False):
    if not api: api = self.API_TYPE_SOAP
    return {
      'api': api,
      'call': call,
      'use_cookie_auth': use_cookie_auth,
      'query': None,
      'data': None,
    }

  def _request(self, request, auth_required=True):
    """
    Make an HTTP(S) request to an API endpoint based on what's specified in the 
    request object passed

    ## Input

    Required request keys:
      api
        Either REST or SOAP

      call
        Name of the SOAP method or relative path of the REST URL 

    Optional keys:
      query
        Contents of the query string passed as a dict

      data
        Data to post. For SOAP API calls this will be the SOAP envelope. For
        REST API calls this will be a dict converted to JSON automatically 
        by this method

      use_cookie_auth
        Whether or not to use an HTTP Cookie in lieu of a querystring for authorization

    ## Output

    Returns a dict:
      status
        Number HTTP status code returned by the response, if any

      raw
        The raw contents of the response, if any

      data
        A python dict representing the data contained in the response, if any
    """
    for required_key in [
      'api',
      'call'
      ]:
      if not request.has_key(required_key) and request[required_key]:
        self.log("All requests are required to have a key [{}] with a value".format(required_key), level='critical')
        return None

    url = None
    if request['api'] == self.API_TYPE_REST:
      url = "{}/{}".format(self._rest_api_endpoint, request['call'].lstrip('/'))
    else:
      url = self._soap_api_endpoint

    self.log("Making a request to {}".format(url), level='debug')

    # add the authentication parameters
    if auth_required:
      if request['api'] == self.API_TYPE_REST:
        if not request['use_cookie_auth']: # sID is a query string
          if not request['query']: request['query'] = {}
          request['query']['sID'] = self._sessions[self.API_TYPE_REST]
      elif request['api'] == self.API_TYPE_SOAP:
        # sID is part of the data
        if not request['data']: request['data'] = {}
        request['data']['sID'] = self._sessions[self.API_TYPE_SOAP]

    # remove any blank request keys
    for k, v in request.items():
      if not v: request[k] = None

    # prep the query string
    if request.has_key('query') and request['query']:
      # get with query string
      qs = {}
      for k, v in request['query'].items(): # strip out null entries
        if v: qs[k] = v

      url += '?%s' % urllib.urlencode(qs)
      self.log("Added query string. Full URL is now {}".format(url), level='debug')

    self.log("URL to request is: {}".format(url))

    # Prep the SSL context
    ssl_context = ssl.create_default_context()
    if self.ignore_ssl_validation:
      ssl_context.check_hostname = False
      ssl_context.verify_mode = ssl.CERT_NONE
      self.log("SSL certificate validation has been disabled for this call", level='warning')

    # Prep the URL opener
    url_opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ssl_context))
  
    # Prep the request
    request_type = 'GET'
    headers = {
      'Accept': 'application/json,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*',
      'Content-Type': 'application/json',
      }

    # authentication calls don't accept the Accept header
    if request['call'].startswith('authentication'): del(headers['Accept'])
    
    # some rest calls use a cookie to pass the sID
    if request['api'] == self.API_TYPE_REST and request['use_cookie_auth']:
      headers['Cookie'] = 'sID="{}"'.format(self._sessions[self.API_TYPE_REST])

    if request['api'] == self.API_TYPE_REST and request['call'] in [
      'apiVersion',
      'status/manager/ping'
      ]:
      headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*',
        'Content-Type': 'text/plain',
        }

    if request['api'] == self.API_TYPE_SOAP:
      # always a POST
      headers = {
        'SOAPAction': '',
        'content-type': 'application/soap+xml'
        }
      data = self._prep_data_for_soap(request['call'], request['data'])
      url_request = urllib2.Request(url, data=data, headers=headers)
      request_type = 'POST'
      self.log("Making a SOAP request with headers {}".format(headers), level='debug')
      self.log("   and data {}".format(data), level='debug')
    elif request['call'] == 'authentication/logout':
      url_request = urllib2.Request(url, headers=headers)
      setattr(url_request, 'get_method', lambda: 'DELETE') # make this request use the DELETE HTTP verb
      request_type = 'DELETE'
      self.log("Making a REST DELETE request with headers {}".format(headers), level='debug')
    elif request.has_key('data') and request['data']:
      # POST
      url_request = urllib2.Request(url, data=json.dumps(request['data']), headers=headers)
      request_type = 'POST'
      self.log("Making a REST POST request with headers {}".format(headers), level='debug')
      self.log("    and data {}".format(request['data']), level='debug')
    else:
      # GET
      url_request = urllib2.Request(url, headers=headers)
      self.log("Making a REST GET request with headers {}".format(headers), level='debug')

    # Make the request
    response = None
    try:
      response = url_opener.open(url_request)
    except Exception, url_err:
      self.log("Failed to make {} {} call [{}]".format(request['api'].upper(), request_type, request['call'].lstrip('/')), err=url_err)

    # Convert the request from JSON
    result = {
      'status': response.getcode() if response else None,
      'raw': response.read() if response else None,
      'headers': dict(response.headers) if response else dict(),
      'data': None
    }
    bytes_of_data = len(result['raw']) if result['raw'] else 0
    self.log("Call returned HTTP status {} and {} bytes of data".format(result['status'], bytes_of_data), level='debug')

    if response:
      if request['api'] == self.API_TYPE_SOAP:
        # XML response
        try:
          if result['raw']:
            full_data = xmltodict.parse(result['raw'])
            if full_data.has_key('soapenv:Envelope') and full_data['soapenv:Envelope'].has_key('soapenv:Body'):
              result['data'] = full_data['soapenv:Envelope']['soapenv:Body']
              if result['data'].has_key('{}Response'.format(request['call'])):
                if result['data']['{}Response'.format(request['call'])].has_key('{}Return'.format(request['call'])):
                  result['data'] = result['data']['{}Response'.format(request['call'])]['{}Return'.format(request['call'])]
                else:
                  result['data'] = result['data']['{}Response'.format(request['call'])]
            else:
              result['data'] = full_data
        except Exception, xmltodict_err:
          self.log("Could not convert response from call {}".format(request['call']), err=xmltodict_err)
      else:
        # JSON response
        try:
          if result['raw'] and result['status'] != 204:
            result['type'] = result['headers']['content-type']
            result['data'] = json.loads(result['raw']) if 'json' in result['type'] else None
        except Exception, json_err:
          # report the exception as 'info' because it's not fatal and the data is 
          # still captured in result['raw']
          self.log("Could not convert response from call {} to JSON. Threw exception:\n\t{}".format(request['call'], json_err), level='info')
        else:
            jsonfile = open(jsonfilename, "r")
        jsondata = unicode(file.read(jsonfile))
        instances = json.loads(jsondata)
        jsonfile.close()
    except:
        print "Could not parse JSON."
        sys.exit(1)
else:
    try:
        xmlfilename = args.xml
        if xmlfilename == "-":
            xmlfile = sys.stdin
        else:
            xmlfile = open(xmlfilename, "r")
        instances = xmltodict.parse(xmlfile, attr_prefix = '')
        xmlfile.close()
    except:
        print "Could not parse XML."
        sys.exit(1)

"""
Config files describing a single instance should be in the format output
by 'nuxeoctl showconf --json/--xml' (the root 'instance' element can be renamed)

Config files describing multiples instances should have an 'instances' root
element. Sub-elements should have different names.

JSON example:
{"instances": { "test1": { some stuff },
                "test2": { other stuff }
    def _request(self, request, auth_required=True):
        """
    Make an HTTP(S) request to an API endpoint based on what's specified in the
    request object passed

    ## Input

    Required request keys:
      api
        Either REST or SOAP

      call
        Name of the SOAP method or relative path of the REST URL

    Optional keys:
      query
        Contents of the query string passed as a dict

      data
        Data to post. For SOAP API calls this will be the SOAP envelope. For
        REST API calls this will be a dict converted to JSON automatically
        by this method

      use_cookie_auth
        Whether or not to use an HTTP Cookie in lieu of a querystring for authorization

    ## Output

    Returns a dict:
      status
        Number HTTP status code returned by the response, if any

      raw
        The raw contents of the response, if any

      data
        A python dict representing the data contained in the response, if any
    """
        for required_key in ['api', 'call']:
            if not request.has_key(required_key) and request[required_key]:
                self.log(
                    "All requests are required to have a key [{}] with a value"
                    .format(required_key),
                    level='critical')
                return None

        url = None
        if request['api'] == self.API_TYPE_REST:
            url = "{}/{}".format(self._rest_api_endpoint,
                                 request['call'].lstrip('/'))
        else:
            url = self._soap_api_endpoint

        self.log("Making a request to {}".format(url), level='debug')

        # add the authentication parameters
        if auth_required:
            if request['api'] == self.API_TYPE_REST:
                if not request['use_cookie_auth']:  # sID is a query string
                    if not request['query']: request['query'] = {}
                    request['query']['sID'] = self._sessions[
                        self.API_TYPE_REST]
            elif request['api'] == self.API_TYPE_SOAP:
                # sID is part of the data
                if not request['data']: request['data'] = {}
                request['data']['sID'] = self._sessions[self.API_TYPE_SOAP]

        # remove any blank request keys
        for k, v in request.items():
            if not v: request[k] = None

        # prep the query string
        if request.has_key('query') and request['query']:
            # get with query string
            qs = {}
            for k, v in request['query'].items():  # strip out null entries
                if v: qs[k] = v

            url += '?%s' % urllib.urlencode(qs)
            self.log("Added query string. Full URL is now {}".format(url),
                     level='debug')

        self.log("URL to request is: {}".format(url))

        # Prep the SSL context
        ssl_context = ssl.create_default_context()
        if self.ignore_ssl_validation:
            ssl_context.check_hostname = False
            ssl_context.verify_mode = ssl.CERT_NONE
            self.log(
                "SSL certificate validation has been disabled for this call",
                level='warning')

        # Prep the URL opener
        url_opener = urllib.request.build_opener(
            urllib.request.HTTPSHandler(context=ssl_context))

        # Prep the request
        request_type = 'GET'
        headers = {
            'Accept':
            'application/json,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*',
            'Content-Type': 'application/json',
        }

        # authentication calls don't accept the Accept header
        if request['call'].startswith('authentication'):
            del (headers['Accept'])

        # some rest calls use a cookie to pass the sID
        if request['api'] == self.API_TYPE_REST and request['use_cookie_auth']:
            headers['Cookie'] = 'sID="{}"'.format(
                self._sessions[self.API_TYPE_REST])

        if request['api'] == self.API_TYPE_REST and request['call'] in [
                'apiVersion', 'status/manager/ping'
        ]:
            headers = {
                'Accept':
                'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*',
                'Content-Type': 'text/plain',
            }

        if request['api'] == self.API_TYPE_SOAP:
            # always a POST
            headers = {
                'SOAPAction': '',
                'content-type': 'application/soap+xml'
            }
            data = self._prep_data_for_soap(request['call'], request['data'])
            url_request = urllib.request.Request(url,
                                                 data=data,
                                                 headers=headers)
            request_type = 'POST'
            self.log("Making a SOAP request with headers {}".format(headers),
                     level='debug')
            self.log("   and data {}".format(data), level='debug')
        elif request['call'] == 'authentication/logout':
            url_request = urllib.request.Request(url, headers=headers)
            setattr(
                url_request, 'get_method',
                lambda: 'DELETE')  # make this request use the DELETE HTTP verb
            request_type = 'DELETE'
            self.log(
                "Making a REST DELETE request with headers {}".format(headers),
                level='debug')
        elif request.has_key('data') and request['data']:
            # POST
            url_request = urllib.request.Request(url,
                                                 data=json.dumps(
                                                     request['data']),
                                                 headers=headers)
            request_type = 'POST'
            self.log(
                "Making a REST POST request with headers {}".format(headers),
                level='debug')
            self.log("    and data {}".format(request['data']), level='debug')
        else:
            # GET
            url_request = urllib.request.Request(url, headers=headers)
            self.log(
                "Making a REST GET request with headers {}".format(headers),
                level='debug')

        # Make the request
        response = None
        try:
            response = url_opener.open(url_request)
        except Exception as url_err:
            self.log("Failed to make {} {} call [{}]".format(
                request['api'].upper(), request_type,
                request['call'].lstrip('/')),
                     err=url_err)

        # Convert the request from JSON
        result = {
            'status': response.getcode() if response else None,
            'raw': response.read() if response else None,
            'headers': dict(response.headers) if response else dict(),
            'data': None
        }
        bytes_of_data = len(result['raw']) if result['raw'] else 0
        self.log("Call returned HTTP status {} and {} bytes of data".format(
            result['status'], bytes_of_data),
                 level='debug')

        if response:
            if request['api'] == self.API_TYPE_SOAP:
                # XML response
                try:
                    if result['raw']:
                        full_data = xmltodict.parse(result['raw'])
                        if full_data.has_key('soapenv:Envelope') and full_data[
                                'soapenv:Envelope'].has_key('soapenv:Body'):
                            result['data'] = full_data['soapenv:Envelope'][
                                'soapenv:Body']
                            if result['data'].has_key('{}Response'.format(
                                    request['call'])):
                                if result['data']['{}Response'.format(
                                        request['call'])].has_key(
                                            '{}Return'.format(
                                                request['call'])):
                                    result['data'] = result['data'][
                                        '{}Response'.format(request['call'])][
                                            '{}Return'.format(request['call'])]
                                else:
                                    result['data'] = result['data'][
                                        '{}Response'.format(request['call'])]
                        else:
                            result['data'] = full_data
                except Exception as xmltodict_err:
                    self.log("Could not convert response from call {}".format(
                        request['call']),
                             err=xmltodict_err)
            else:
                # JSON response
                try:
                    if result['raw'] and result['status'] != 204:
                        result['type'] = result['headers']['content-type']
                        result['data'] = json.loads(
                            result['raw']
                        ) if 'json' in result['type'] else None
                except Exception as json_err:
                    # report the exception as 'info' because it's not fatal and the data is
                    # still captured in result['raw']
                    self.log(
                        "Could not convert response from call {} to JSON. Threw exception:\n\t{}"
                        .format(request['call'], json_err),
                        level='info')

        return result
        else:
            jsonfile = open(jsonfilename, "r")
        jsondata = unicode(file.read(jsonfile))
        instances = json.loads(jsondata)
        jsonfile.close()
    except:
        print "Could not parse JSON."
        sys.exit(1)
else:
    try:
        xmlfilename = args.xml
        if xmlfilename == "-":
            xmlfile = sys.stdin
        else:
            xmlfile = open(xmlfilename, "r")
        instances = xmltodict.parse(xmlfile, attr_prefix='')
        xmlfile.close()
    except:
        print "Could not parse XML."
        sys.exit(1)
"""
Config files describing a single instance should be in the format output
by 'nuxeoctl showconf --json/--xml' (the root 'instance' element can be renamed)

Config files describing multiples instances should have an 'instances' root
element. Sub-elements should have different names.

JSON example:
{"instances": { "test1": { some stuff },
                "test2": { other stuff }
}
示例#10
0
    def handle_onAlipay_notify(self):
        print(
            "[AliPay]handle_onAlipay_notify!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        )
        sign = self.args.pop('sign')
        signmethod = self._alipay.getSignMethod(**self.args)
        # print("[AliPay]Callback success")
        if signmethod(self.args) != sign:
            return self.send_error(403)
        # print("[AliPay]Callback data:",self.args['notify_data'])
        notify_data = xmltodict.parse(self.args['notify_data'])['notify']
        order_num = notify_data["out_trade_no"]
        print("[AliPay]Callback order_num:", order_num)
        ali_trade_no = notify_data["trade_no"]
        total_fee = float(notify_data["total_fee"])
        # print("[AliPay]ali_trade_no:",ali_trade_no)
        old_balance_history = self.session.query(
            models.BalanceHistory).filter_by(
                transaction_id=ali_trade_no).first()
        if old_balance_history:
            return self.send_success()
        order = self.session.query(
            models.Order).filter_by(num=str(order_num)).first()
        # order = models.Order.get_by_id(self.session,orderId)
        if not order:
            # return self.send_fail(error_text = '抱歉,此订单不存在!')
            balance_history = models.BalanceHistory(
                customer_id=0,
                shop_id=0,
                balance_value=total_fee,
                balance_record='在线支付(支付宝)异常:空订单' + order_num,
                balance_type=3,
                transaction_id=ali_trade_no)
            self.session.add(balance_history)
            self.session.commit()
            print(
                "[AliPay]No This Order!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
            )
            return self.write('success')
        ##############################################################
        # 在线支付成功回调业务处理
        # 修改订单状态 :支付订单刚生成时 状态为-1.完成支付后状态变为1
        # 增加相应店铺 相应的余额
        # 生成一条余额记录
        # 给店铺管理员 和 顾客 发送微信消息
        ##############################################################
        customer_id = order.customer_id
        shop_id = order.shop_id
        totalPrice = order.new_totalprice

        create_date = order.create_date.timestamp()
        now = datetime.datetime.now().timestamp()
        time_difference = now - create_date
        if time_difference > 60 * 60 * 24 * 7:
            balance_history = models.BalanceHistory(
                customer_id=customer_id,
                shop_id=shop_id,
                balance_value=totalPrice,
                balance_record='在线支付(支付宝)异常:一星期以前的订单,很可能是线下测试回调到线上的',
                balance_type=3,
                transaction_id=transaction_id)
            self.session.add(balance_history)
            self.session.commit()
            print(
                "[AliPay]Order Time Wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
            )
            return self.write('success')

        order.status = 1  #修改订单状态
        order.transaction_id = ali_trade_no
        print("[AliPay]Callback order.num:", order.num,
              "change order.status to:", order.status)

        # 修改店铺总余额
        # shop = self.session.query(models.Shop).filter_by(id = shop_id).first()
        # if not shop:
        # 	return self.send_fail('shop not found')
        shop = order.shop
        shop.shop_balance += totalPrice
        self.session.flush()
        # print("[AliPay]shop_balance:",shop.shop_balance)
        customer = self.session.query(
            models.Customer).filter_by(id=customer_id).first()
        if customer:
            name = customer.accountinfo.nickname
        else:
            # return self.send_fail('customer not found')
            name = None

        shop_follow = self.session.query(models.CustomerShopFollow).filter_by(customer_id = customer_id,\
         shop_id = shop_id).first()
        if not shop_follow:
            balance_history = models.BalanceHistory(
                customer_id=customer_id,
                shop_id=shop_id,
                balance_value=totalPrice,
                balance_record='在线支付(支付宝)异常:用户未关注,订单' + order.num,
                name=name,
                balance_type=3,
                shop_totalPrice=shop.shop_balance,
                customer_totalPrice=0,
                transaction_id=ali_trade_no,
                shop_province=shop.shop_province,
                shop_name=shop.shop_name)
            self.session.add(balance_history)
            # print("[AliPay]balance_history:",balance_history)
            self.session.commit()
            print(
                "[AliPay]No CustomerShopFollow!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
            )
        else:
            # 支付成功后  生成一条余额支付记录
            balance_history = models.BalanceHistory(
                customer_id=customer_id,
                shop_id=shop_id,
                balance_value=totalPrice,
                balance_record='在线支付(支付宝):订单' + order.num,
                name=name,
                balance_type=3,
                shop_totalPrice=shop.shop_balance,
                customer_totalPrice=shop_follow.shop_balance,
                transaction_id=ali_trade_no,
                shop_province=shop.shop_province,
                shop_name=shop.shop_name)
            self.session.add(balance_history)
            # print("[AliPay]balance_history:",balance_history)
            self.session.commit()
            print(
                "[AliPay]handle_onAlipay_notify SUCCESS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
            )

        # 发送订单模版消息给管理员/自动打印订单
        if shop.admin.mp_name and shop.admin.mp_appid and shop.admin.mp_appsecret and shop.admin.has_mp:
            # print("[CustomerCart]cart_callback: shop.admin.mp_appsecret:",shop.admin.mp_appsecret,shop.admin.mp_appid)
            access_token = self.get_other_accessToken(self.session,
                                                      shop.admin.id)
            # print(shop.admin.mp_name,shop.admin.mp_appid,shop.admin.mp_appsecret,access_token)
        else:
            access_token = None
        self.send_admin_message(self.session, order, access_token)
        return self.write('success')
示例#11
0
 def post(self):
     print("[Alipay refund] notify_url!!!!!!!!")
     session = models.DBSession()
     _alipay = WapAlipay(pid=ALIPAY_PID,
                         key=ALIPAY_KEY,
                         seller_email=ALIPAY_SELLER_ACCOUNT)
     sign = self.args.pop('sign')
     signmethod = _alipay.getSignMethod(**self.args)
     if signmethod(self.args) != sign:
         print('sign error')
         return self.write('sign error')
     notify_data = xmltodict.parse(self.args['notify_data'])['notify']
     result_details = notify_data['result_details']
     transaction_id = result_details.split('^')[0]
     balance_history = session.query(models.BalanceHistory).filter_by(
         transaction_id=transaction_id).first()
     if not balance_history:
         return self.write('old_balance_history not found')
     order = session.query(
         models.Order).filter_by(transaction_id=transaction_id).first()
     if not order:
         print('order not found')
         return self.write('order not found')
     ##########################################################################
     order.del_reason = 'refund'
     order.get_num(session, order.id)  #取消订单,库存增加,在售减少
     shop_id = balance_history.shop_id
     balance_value = balance_history.balance_value
     shop = order.shop
     #该店铺余额减去订单总额
     shop.shop_balance -= balance_value
     balance_history.is_cancel = 1
     #将这条余额记录作废
     balance_history.balance_type = -1
     customer_id = balance_history.customer_id
     name = balance_history.name
     shop_province = balance_history.shop_province
     shop_name = balance_history.shop_name
     balance_record = balance_history.balance_record + '--退款'
     create_time = datetime.datetime.now()
     shop_totalPrice = shop.shop_balance
     customer_totalPrice = balance_history.customer_totalPrice
     transaction_id = balance_history.transaction_id
     available_balance = balance_history.available_balance
     #同时生成一条退款记录
     refund_history = models.BalanceHistory(
         customer_id=customer_id,
         shop_id=shop_id,
         shop_province=shop_province,
         shop_name=shop_name,
         name=name,
         balance_record=balance_record,
         create_time=create_time,
         shop_totalPrice=shop_totalPrice,
         customer_totalPrice=customer_totalPrice,
         transaction_id=transaction_id,
         balance_type=9,
         balance_value=balance_value)
     session.add(refund_history)
     # self.session.flush()
     # # 9.15 woody
     # # 生成一条支付宝退款记录
     # apply_refund = models.ApplyRefund(customer_id=customer_id,order_id=order_id,refund_type=1,refund_fee=totalPrice,
     # 	transaction_id=transaction_id,order_num=num)
     # self.session.add(apply_refund)
     session.commit()
     return self.write('success')
示例#12
0
	def handle_onAlipay_notify(self):
		print("[AliPay]handle_onAlipay_notify!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
		sign = self.args.pop('sign')
		signmethod = self._alipay.getSignMethod(**self.args)
		# print("[AliPay]Callback success")
		if signmethod(self.args) != sign:
			return self.send_error(403)
		# print("[AliPay]Callback data:",self.args['notify_data'])
		notify_data = xmltodict.parse(self.args['notify_data'])['notify']
		order_num = notify_data["out_trade_no"]
		print("[AliPay]Callback order_num:",order_num)
		ali_trade_no=notify_data["trade_no"]
		total_fee  = float(notify_data["total_fee"])
		# print("[AliPay]ali_trade_no:",ali_trade_no)
		old_balance_history = self.session.query(models.BalanceHistory).filter_by(transaction_id = ali_trade_no).first()
		if old_balance_history:
			return self.send_success()
		order = self.session.query(models.Order).filter_by(num = str(order_num)).first()
		# order = models.Order.get_by_id(self.session,orderId)
		if not order:
			# return self.send_fail(error_text = '抱歉,此订单不存在!')
			balance_history = models.BalanceHistory(customer_id=0,shop_id=0,balance_value=total_fee,balance_record='在线支付(支付宝)异常:空订单'+order_num,
				balance_type=3,transaction_id = ali_trade_no)
			self.session.add(balance_history)
			self.session.commit()
			print("[AliPay]No This Order!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
			return self.write('success')
		##############################################################
		# 在线支付成功回调业务处理
		# 修改订单状态 :支付订单刚生成时 状态为-1.完成支付后状态变为1
		# 增加相应店铺 相应的余额
		# 生成一条余额记录
		# 给店铺管理员 和 顾客 发送微信消息
		##############################################################
		customer_id = order.customer_id
		shop_id     = order.shop_id
		totalPrice  = order.new_totalprice

		create_date = order.create_date.timestamp()
		now         = datetime.datetime.now().timestamp()
		time_difference = now - create_date
		if time_difference > 60 * 60 * 24 * 7:
			balance_history = models.BalanceHistory(customer_id = customer_id,shop_id = shop_id,balance_value=totalPrice,
				balance_record='在线支付(支付宝)异常:一星期以前的订单,很可能是线下测试回调到线上的',balance_type=3,transaction_id=transaction_id)
			self.session.add(balance_history)
			self.session.commit()
			print("[AliPay]Order Time Wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
			return self.write('success')

		order.status = 1  #修改订单状态
		order.transaction_id = ali_trade_no
		print("[AliPay]Callback order.num:",order.num,"change order.status to:",order.status)

		# 修改店铺总余额
		# shop = self.session.query(models.Shop).filter_by(id = shop_id).first()
		# if not shop:
		# 	return self.send_fail('shop not found')
		shop = order.shop
		shop.shop_balance += totalPrice
		self.session.flush()
		# print("[AliPay]shop_balance:",shop.shop_balance)
		customer = self.session.query(models.Customer).filter_by(id = customer_id).first()
		if customer:
			name = customer.accountinfo.nickname
		else:
			# return self.send_fail('customer not found')
			name = None

		shop_follow = self.session.query(models.CustomerShopFollow).filter_by(customer_id = customer_id,\
			shop_id = shop_id).first()
		if not shop_follow:
			balance_history = models.BalanceHistory(customer_id =customer_id ,shop_id = shop_id,
				balance_value = totalPrice,balance_record = '在线支付(支付宝)异常:用户未关注,订单'+ order.num, name = name , balance_type = 3,
				shop_totalPrice = shop.shop_balance,customer_totalPrice = 0,transaction_id=ali_trade_no,
				shop_province = shop.shop_province,shop_name=shop.shop_name)
			self.session.add(balance_history)
			# print("[AliPay]balance_history:",balance_history)
			self.session.commit()
			print("[AliPay]No CustomerShopFollow!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
		else:
			# 支付成功后  生成一条余额支付记录
			balance_history = models.BalanceHistory(customer_id =customer_id ,shop_id = shop_id,
				balance_value = totalPrice,balance_record = '在线支付(支付宝):订单'+ order.num, name = name , balance_type = 3,
				shop_totalPrice = shop.shop_balance,customer_totalPrice = shop_follow.shop_balance,transaction_id= ali_trade_no,
				shop_province = shop.shop_province,shop_name=shop.shop_name)
			self.session.add(balance_history)
			# print("[AliPay]balance_history:",balance_history)
			self.session.commit()
			print("[AliPay]handle_onAlipay_notify SUCCESS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")

		# 发送订单模版消息给管理员/自动打印订单
		if shop.admin.mp_name and shop.admin.mp_appid and shop.admin.mp_appsecret and shop.admin.has_mp:
			# print("[CustomerCart]cart_callback: shop.admin.mp_appsecret:",shop.admin.mp_appsecret,shop.admin.mp_appid)
			access_token = self.get_other_accessToken(self.session,shop.admin.id)
			# print(shop.admin.mp_name,shop.admin.mp_appid,shop.admin.mp_appsecret,access_token)
		else:
			access_token = None
		self.send_admin_message(self.session,order,access_token)
		return self.write('success')
示例#13
0
	def handle_alipay_notify(self):
		# print("[AliCharge]login handler_alipay_notify")
		sign = self.args.pop("sign")
		signmethod = self._alipay.getSignMethod(**self.args)
		if signmethod(self.args) != sign:
			return self.send_error(403)
		# print("[AliCharge]notify_data:",self.args['notify_data'])
		notify_data = xmltodict.parse(self.args["notify_data"])["notify"]
		orderId = notify_data["out_trade_no"]
		ali_trade_no=notify_data["trade_no"]
		# print("[AliCharge]ali_trade_no:",ali_trade_no)
		old_balance_history = self.session.query(models.BalanceHistory).filter_by(transaction_id = ali_trade_no).first()
		if old_balance_history:
			return self.write('success')
		data = orderId.split('a')
		totalPrice = float(data[0])/100
		# shop_id = self.get_cookie('market_shop_id')
		shop_id = int(data[1])
		customer_id = int(data[2])
		# print("[AliCharge]totalPrice:",totalPrice,", shop_id:",shop_id,", customer_id:",customer_id)
		# code = self.args['code']
		# path_url = self.request.full_url()
		# totalPrice =float( self.get_cookie('money'))
		#########################################################
		# 用户余额增加
		# 同时店铺余额相应增加
		# 应放在 支付成功的回调里
		#########################################################
		customer = self.session.query(models.Accountinfo).filter_by(id = customer_id).first()
		if not customer:
			# return self.send_fail("customer not found")
			name = None
		else:
			name = customer.nickname

		shop = self.session.query(models.Shop).filter_by(id = shop_id).first()
		if not shop:
			# return self.send_fail('shop not found')
			shop_province = None
			shop_name     = None
			shop_totalPrice=0
		else:
			shop.shop_balance += totalPrice
			self.session.flush()

			shop_province = shop.shop_province
			shop_name     = shop.shop_name
			shop_totalPrice=shop.shop_balance
		# print("[AliCharge]shop_balance after charge:",shop.shop_balance)

		# 支付成功后,用户对应店铺 余额 增1加
		shop_follow = self.session.query(models.CustomerShopFollow).filter_by(customer_id = customer_id,\
			shop_id = shop_id).first()
		# print("[AliCharge]customer_id:",customer_id,", shop_id:",shop_id)
		if not shop_follow:
			# return self.send_fail('shop_follow not found')
			# 支付成功后  生成一条余额支付记录
			balance_history = models.BalanceHistory(customer_id =customer_id ,shop_id = shop_id,
				balance_value = totalPrice,balance_record = '余额充值(支付宝)失败:用户未关注店铺' , name = name , balance_type = 0,
				shop_totalPrice = shop_totalPrice,customer_totalPrice = 0,transaction_id =ali_trade_no,shop_province=shop_province,shop_name=shop_name)
			self.session.add(balance_history)
			# print("[AliCharge]balance_history:",balance_history)
			self.session.commit()
		else:
			shop_follow.shop_balance += totalPrice     #充值成功,余额增加,单位为元
			self.session.flush()
			# 支付成功后  生成一条余额支付记录
			balance_history = models.BalanceHistory(customer_id =customer_id ,shop_id = shop_id,\
				balance_value = totalPrice,balance_record = '余额充值(支付宝):用户 '+ name  , name = name , balance_type = 0,\
				shop_totalPrice = shop_totalPrice,customer_totalPrice = shop_follow.shop_balance,transaction_id =ali_trade_no,shop_province=shop_province,shop_name=shop_name)
			self.session.add(balance_history)
			# print("[AliCharge]balance_history:",balance_history)
			## add by sunmh 2015-09-14 
			## 充值完成后,如果是首次充值,则更新customershopfollow的首次充值时间
			if shop_follow.first_charge_time==None:
				shop_follow.first_charge_time=datetime.datetime.now()
			self.session.commit()

		self.updatecoupon(customer_id)
		CouponsShops=self.session.query(models.CouponsShop).filter_by(shop_id=shop_id,coupon_type=1,closed=0).order_by(models.CouponsShop.get_rule.desc()).with_lockmode('update').all()
		for x in CouponsShops:
			if  totalPrice>=x.get_rule:
				qhave=self.session.query(models.CouponsCustomer).filter_by(shop_id=shop_id,coupon_id=x.coupon_id,customer_id=customer_id).count()
				if  x.get_limit!=-1:
					if  qhave>=x.get_limit:
						pass
					else:
						CouponsCustomers=self.session.query(models.CouponsCustomer).filter_by(shop_id=shop_id,coupon_id=x.coupon_id,coupon_status=0).with_lockmode('update').first()
						if CouponsCustomers==None:
							pass
						else:
							now_date=int(time.time())
							if x.valid_way==0:
								uneffective_time=x.to_valid_date
								effective_time=x.from_valid_date
							elif x.valid_way==1:
								all_days=x.start_day+x.last_day
								uneffective_time=now_date+all_days*60*60*24
								effective_time=now_date+x.start_day*24*60*60
							else:
								pass
							CouponsCustomers.update(self.session,customer_id=customer_id,coupon_status=1,get_date=now_date,effective_time=effective_time,uneffective_time=uneffective_time)
							get_number=x.get_number+1
							x.update(self.session,get_number=get_number)
							self.session.commit()
							success_message="恭喜你获得一张"+x.coupon_money+"元的优惠券,请到“我的优惠券”查看"
							return self.send_success(success_message)
						self.session.commit()
				else:
					CouponsCustomers=self.session.query(models.CouponsCustomer).filter_by(shop_id=shop_id,coupon_id=x.coupon_id,coupon_status=0).with_lockmode('update').first()
					if CouponsCustomers==None:
						pass
					else:
						now_date=int(time.time())
						if x.valid_way==0:
							uneffective_time=x.to_valid_date
							effective_time=x.from_valid_date
						elif x.valid_way==1:
							all_days=x.start_day+x.last_day
							uneffective_time=now_date+all_days*60*60*24
							effective_time=now_date+x.start_day*24*60*60
						else:
							pass
						CouponsCustomers.update(self.session,customer_id=customer_id,coupon_status=1,get_date=now_date,effective_time=effective_time,uneffective_time=uneffective_time)
						get_number=x.get_number+1
						x.update(self.session,get_number=get_number)
						self.session.commit()
						success_message="恭喜你获得一张"+x.coupon_money+"元的优惠券,请到“我的优惠券”查看"
						return self.send_success(success_message)
					self.session.commit()
		self.session.commit()
		return self.write('success')