Example #1
0
    def _conn(self):
        try:
            # 读取数据库配置
            conf = ConfigParser.ConfigParser()
            conf.read("%s/config/config.ini" % sys.path[0])
            # print "%s/config/config.ini" % sys.path[0]

            #链接数据库
            conn = MySQLdb.connect(host=conf.get('db', 'dbHost'),
                                   user=conf.get('db', 'dbUser'),
                                   passwd=conf.get('db', 'dbPasswd'),
                                   db=conf.get('db', 'dbName'),
                                   port=int(conf.get('db', 'dbPort')),
                                   charset=conf.get('db', 'dbCharset'))

            conn.autocommit(True)
            cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)

            self.conn = conn
            self.cur = cur
            # print '1t conn mysql'
            return True
        except Exception, e:
            re = str(Exception) + ':' + str(e)
            print 'conn err: %s' % (re)
            helper.getLog('conn err:  -- SQL:%s -- %s' % (self.sql, re),
                          'db.%s.log' % helper.now(0, '%Y-%m-%d'))
            return False
Example #2
0
def ServiceHQ2(config, ticketBoughtList):
    if len(ticketBoughtList) < 1:
        return

    # 循环检查门票
    ts = []  # 同步门票到第三方系统的线程列表 使用Thread类创建线程
    for ticketBought in ticketBoughtList:
        helper.getLog(str(ticketBought['ticket_id']),
                      'responseOutCode.HQ2.log')
        # 同步门票
        for conf in config:
            try:
                if conf == 'productId_' + str(
                        ticketBought['ticket_id']) and config[conf] != '':
                    # 给第三方增加门票
                    t = threading.Thread(target=addTicketToOuterHQ2,
                                         args=(config, ticketBought))
                    t.start()
                    ts.append(t)
                    break
                    # addTicketToOuterHQ2(config, ticketBought)
                    # break
                # print '========='
            except:
                # print '========='
                pass

    for t in ts:
        t.join()

    return True
Example #3
0
def getOrderDetail(config, orderNo):
    helper.getLog('访问getOrderDetail!!!', 'responseOutCode.HQ2.log')
    url = config['url'] + '?op=OrderFinish'
    headers = hawkAuth(url)
    data = {}
    data['otaCode'] = config['account']
    data['otaOrderNO'] = orderNo
    data['platformSend'] = 0
    parameters = {}
    parameters['type'] = '00'
    parameters['parkCode'] = config['parkCode']
    data['parameters'] = json.dumps(parameters).replace(' ', '')
    sign_str = config['account'] + config['privateKey'] + orderNo + '0' + data[
        'parameters']
    data['sign'] = base64.encodestring(helper.md5(
        sign_str.strip()).upper()).strip()
    postData = '''<?xml version="1.0" encoding="utf-8"?>
            <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                <soap:Body>
                   <OrderFinish xmlns="http://tempuri.org/">
                      <otaCode>%s</otaCode>
                      <otaOrderNO>%s</otaOrderNO>
                      <platformSend>%s</platformSend>
                      <parameters>%s</parameters>
                      <signature>%s</signature>
                    </OrderFinish>
                </soap:Body>
            </soap:Envelope>
       ''' % (config['account'], orderNo, 0, data['parameters'], data['sign'])
    res = helper.httpPost(url, postData, headers)
    resBody = json.loads(
        helper.subStr(res, '<OrderFinishResult>', '</OrderFinishResult>'))
    return resBody
Example #4
0
def ServiceYBX(config, ticketBoughtList):
    # print config.keys();exit()
    # print ticketBoughtList;exit()
    if len(ticketBoughtList) < 1:
        return

    # 循环检查门票
    ts = []  # 同步门票到第三方系统的线程列表
    for ticketBought in ticketBoughtList:
        # 同步门票
        for conf in config:
            try:
                if conf == 'ProductID_' + str(ticketBought['ticket_id']) and config[conf] != '':
                    # print ticketBought['id']
                    # print config, config[conf] + ':nTicketType_' + str(ticketBought['ticket_id'])
                    # 给第三方增加门票
                    helper.getLog(str(ticketBought['order_detail_id']) + '------------',
                                  'addTicketToOuterYBX.recordOrderId.log')
                    t = threading.Thread(target=addTicketToOuterYBX, args=(config, ticketBought,))
                    t.start()
                    ts.append(t)
                    break

                # print '========='
            except:
                # print '========='
                pass

    for t in ts:
        t.join()

    return True
def reBuyDo(serviceUrl, order, sql):
    re = helper.httpPost(serviceUrl, order)
    helper.getLog(
        're_buy_do_info -- order_id:' + str(order['orderId']) +
        ' -- order_create_time:' + str(order['create_time']) + ' -- ' + sql +
        ' -- ' + re, 'serviceCheckPay.log')
    # print ' ==== ' + str(order['type']) + ':' + helper.now()
    pass
Example #6
0
def addTicketToOuter_WJT(config, bought):
    #print config;print print bought;exit()
    helper.getLog('thread start - ' + str(bought['id']),
                  'addTicketToService_WJT.log')
    dbObj = db.db()
    try:
        re = '更新out_app_no为receiving_code:' + bought['receiving_code']
    except Exception, e:
        errMsg = "[Service_WJT - 71]" + str(Exception) + ":" + str(e)
        re = 'update out_app_no to receiving_code: ' + bought['receiving_code']
        helper.getLog(errMsg, 'addTicketToService_WJT.Err.log')
Example #7
0
def getOrderDetail(config, orderId):
    url = config['url']
    urlInfo = urlparse.urlparse(url)
    sanitizedHost = str(urlInfo.netloc)
    url = 'http://' + sanitizedHost + "/api/Order/Query/Detail/" + str(orderId)
    headers = hawkAuth(url, config, 'get')
    try:
        response = requests.get(url, headers=headers)
        return response.json()
    except requests.exceptions:
        helper.getLog(requests.exceptions, 'addTicketToOuterYBX.addOrder.log')
Example #8
0
def processOuterKZZN2(config, mallBought, data, processCount):
    dbObj = db.db()
    try:
        # 发起同步
        url = config['url']  #http://123.11.226.80:8118/service.asmx
        url = helper.subStr(url, 'http://', '/service')
        host = helper.subStr(url, '', ':')
        port = int(helper.subStr(url, ':', ''))

        responseBody, re = sendDataToOuterKZZN2(host, port, data)

        reBody = helper.subStr(responseBody, '<nStatus>', '</nStatus>')
        # print responseBody
        # print re
        #成功同步
        if '1' == reBody:
            cQrCode = helper.subStr(responseBody, '<cQrCode>', '</cQrCode>')
            cUrl = 'http://' + host + ':' + str(port) + helper.subStr(
                responseBody, '<cUrl>', '</cUrl>')
            cStatus = helper.subStr(responseBody, '<cStatus>', '</cStatus>')
            sql = "update t_mall_bought set out_app_code = 'KZZN2', out_app_no = '%s', dimen_code_path='%s', remark2='%s' where id = '%d'" % (
                cQrCode, cUrl, cStatus, mallBought['id'])
            # sql = "update t_mall_bought set out_app_code = '_WJT', out_app_no = '%s' where id = '%d'" % (mallBought['receiving_code'], mallBought['id'])
            # sql = "update t_ticket_bought set out_app_code = 'KZZN2', temp_receiving_code = '%s', receiving_code = '%s', dimen_code_path='%s', remark2='%s' where id = %d" %  (mallBought['receiving_code'], cQrCode, cUrl, cStatus, mallBought['id'])
            # print sql
            # print mallBought
            if not True == dbObj.update(sql):
                helper.getLog('update t_mall_bought error:' + sql,
                              'mall.kzzn2.log')

            # 发送消息
            textMessage = '微景通验证码:' + mallBought[
                'receiving_code'] + ' \n票务验证码:' + cQrCode + ' \n购票张数:' + str(
                    mallBought['buy_count']) + ' \n购票时间:' + str(
                        mallBought['create_time'])
            time = int(helper.thisTime())
            re = re + "\nsendMessageToUser:"******"%s \nPostData:%s" % (re, data)
            # print 'processCount:' + str(processCount)
            if processCount < 2:
                processCount += 1
                processOuterKZZN2(config, mallBought, data, processCount)
                return
            else:
                re = "%s \nprocessCount:%s" % (re, str(processCount))
    except Exception, e:
        re = str(Exception) + ":" + str(e)
        re = "%s \nPostData:%s" % (re, data)
Example #9
0
def processOuterYBX(config, ticketBought, data, processCount):
    dbObj = db.db()
    send_time = time.time()
    # 错误时 记录信息
    sql_error = "update t_ticket_bought set out_app_error='%s' where id = %d" % (1, ticketBought['id'])
    try:
        # 记录请求时间
        # 发起同步
        response = sendDataToOuterYBX(config, data)

        # 防止票务系统死锁
        if -2 == response['resultcode']:
            for i in range(1, 10):
                time.sleep(i)
                response = sendDataToOuterYBX(config, data)
                if response != -2:
                    break
        # 成功同步
        if 0 == response['resultcode']:
            # 获取订单详细信息
            orderId = response['orderid']
            orderDetail = getOrderDetail(config, orderId)
            # 门票唯一ID
            ticketId = orderDetail[0]['ticketinnernumber']
            # 获取filecode
            # cQrCodeFile = getQrcodeFile(config, ticketId, orderId)
            # 获取二维码
            cQrCodeInfo = getQrcode(config, ticketId, orderId)
            # cQrCode = base64.b64decode(cQrCodeInfo['imagebase64'])
            # 获取二维码成功
            if cQrCodeInfo['errcode'] == 0:
                cQrCode = cQrCodeInfo['imagebase64']
                cQrCode = base64.b64encode(cQrCode)
                qrcodeImgUrl = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/getQrCode?data=' + cQrCode
                # 替换二维码 、订单号 、门票编码
                sql = "update t_ticket_bought set out_app_code = 'YBX', temp_receiving_code = '%s', receiving_code = '%s', dimen_code_path='%s', remark2='%s', out_app_error='%s' where id = %d" % (
                    ticketBought['receiving_code'], ticketId, qrcodeImgUrl, orderId, 2, ticketBought['id'])
                try:
                    re = dbObj.update(sql)
                    if not True == re:
                        helper.getLog(sql, 'addTicketToOuterYBX.UpdateTicketboughtlistErr.log')
                    else:
                        re = "%s \npostdata:%s" % (response, data)
                except Exception, e:
                    dbObj.update(sql_error)
                    re = "%s " % e
            # 获取二维码不成功
            else:
                dbObj.update(sql_error)
                re = "%s \n %s \n postdata:%s" % ('获取二维码失败,订单已同步', cQrCodeInfo, data)
        else:
Example #10
0
 def _checkConn(self):
     try:
         re = self.conn.ping()
         helper.getLog('check conn mysql: %s -- sql: %s' % (re, self.sql),
                       'db.%s.log' % helper.now(0, '%Y-%m-%d'))
         print 'check conn mysql: %s -- sql: %s' % (re, self.sql)
     except Exception, e:
         while True:
             print 're connect mysql'
             helper.getLog('re conn mysql -- SQL:%s' % self.sql,
                           'db.%s.log' % helper.now(0, '%Y-%m-%d'))
             if self._conn():
                 break
             time.sleep(2)
Example #11
0
def getQrcode(config, ticketcode, orderid):
    url = config['url']
    urlInfo = urlparse.urlparse(url)
    sanitizedHost = str(urlInfo.netloc)
    # url = 'http://' + sanitizedHost + "/api/Ticket/Resource/" + str(ticketcode)
    # url = 'http://' + sanitizedHost + "/api/Ticket/Resource/String/" + str(ticketcode)
    url = 'http://' + sanitizedHost + "/api/Ticket/Barcode/String/" + str(orderid) + '/' + str(ticketcode)
    headers = hawkAuth(url, config, 'get')
    try:
        response = requests.get(url, headers=headers)
        # helper.getLog(response, 'addTicketToOuterYBX.getQrcode.log')
        return response.json()
    except requests.exceptions:
        helper.getLog(requests.exceptions, 'addTicketToOuterYBX.addOrder.log')
Example #12
0
def processOuterHQ2(config, ticketBought, data, processCount):
    # helper.getLog('访问processOuterHQ2!!!', 'responseOutCode.HQ2.log')
    dbObj = db.db()
    orderInfo = {}
    orderInfo['merchantCode'] = config['account']  #获取环企票务的编码
    orderInfo['postOrder'] = json.dumps(data).replace(' ', '')
    tempOrder = config['account'] + config['privateKey'] + orderInfo[
        'postOrder']
    orderInfo['signature'] = base64.encodestring(
        helper.md5(tempOrder.strip()).upper()).strip()
    try:
        # 发起同步
        response = sendDataToOuterHQ2(config, orderInfo)
        # # 防止同时发起请求造成唯一ID插入错误
        # 成功同步
        if '00' == response['ResultCode']:
            # 获取订单详细信息
            orderNo = ticketBought['order_detail_id']
            orderDetail = getOrderDetail(config, str(orderNo))
            # 获取订单信息成功
            if orderDetail['ResultCode'] == '00':
                result = json.loads(orderDetail['ResultJson'].replace(
                    '[', '').replace(']', ''))
                for item in result:
                    if 'ECode' == item:
                        qrcodeData = result[item]
                        break
                qrcodeImgUrl = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/?data=' + qrcodeData
                # 替换二维码 、订单号 、门票编码
                sql = "update t_ticket_bought set out_app_code = 'HQ2', temp_receiving_code = '%s', receiving_code = '%s', dimen_code_path='%s', remark2='%s' where id = %d" % (
                    ticketBought['receiving_code'], qrcodeData, qrcodeImgUrl,
                    qrcodeData, ticketBought['id'])
                try:
                    re = dbObj.update(sql)
                    if not True == re:
                        helper.getLog(
                            sql,
                            'addTicketToOuterHQ2.UpdateTicketboughtlistErr.log'
                        )
                    else:
                        re = "%s \npostdata:%s" % (response, orderInfo)
                except Exception, e:
                    re = "%s " % e
            # 获取订单信息不成功
            else:
                re = "%s \n %s \n postdata:%s" % ('获取订单详情失败,订单已占用',
                                                  orderDetail, orderInfo)
        else:
Example #13
0
def processOuterYBX(config, mallBought, data, processCount):
    dbObj = db.db()
    # 错误记录
    sql_error = "update t_mall_bought set out_app_error = '%s' where id = %d" % (1, mallBought['id'])
    try:
        # 记录请求时间
        # helper.getLog(helper.now(), 'addTicketToOuterYBX.recordSendTime.log')
        # 发起同步
        response = sendDataToOuterYBX(config, data)

        # 防止票务系统死锁
        if -2 == response['resultcode']:
            for i in range(1, 10):
                time.sleep(i)
                response = sendDataToOuterYBX(config, data)
                if response != -2:
                    break
        # 成功同步
        if 0 == response['resultcode']:
            # 获取订单详细信息
            orderId = response['orderid']
            orderDetail = getOrderDetail(config, orderId)
            # 门票唯一ID
            ticketId = orderDetail[0]['ticketinnernumber']
            # 获取filecode
            cQrCodeInfo = getQrcode(config, ticketId, orderId)
            # 获取二维码
            cQrCode = cQrCodeInfo['imagebase64']

            if (cQrCodeInfo['errcode'] == 0):
                cQrCode = base64.b64encode(cQrCode)
                qrcodeImgUrl = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/getQrCode?data=' + cQrCode
                # 替换二维码
                sql = "update t_mall_bought set out_app_code = 'YBX', out_app_no = '%s',  receiving_code = '%s', dimen_code_path='%s' , dimen_code_path='%s', out_app_error ='%s' where id = %d" % (
                orderId, ticketId, qrcodeImgUrl, 2, mallBought['id'])
                re = dbObj.update(sql)
                if not True == re:
                    helper.getLog(sql, 'addTicketToOuterYBX.UpdateTicketboughtlistErr.log')
            else:
                dbObj.update(sql_error)
                re = "%s \n %s \n PostData:%s" % ('获取二维码失败,订单已同步', cQrCodeInfo, data)
                # helper.getLog('获取二维码失败,同步失败', 'addTicketToOuterYBX.updateQRcode.log')
        else:
            dbObj.update(sql_error)
            re = "%s \npostdata:%s" % (response, data)
    except Exception, e:
        re = str(Exception) + ":" + str(e)
        re = "%s \nPostData:%s" % (re, data)
Example #14
0
def ServiceKZZN2(config, mallBoughtList):
    # print mallBoughtList
    # print config.keys()
    # exit()
    if not 'cid' in config.keys():
        # print '==== no CompanyCode config ====' + config['url']
        helper.getLog(
            'no CompanyCode config:config:' + str(config) +
            ";mallBoughtList:" + str(mallBoughtList), 'mall.kzzn2.log')
        return
    if len(mallBoughtList) < 1:
        helper.getLog(
            'no mallBoughtList:config:' + str(config) + ";mallBoughtList:" +
            str(mallBoughtList), 'mall.kzzn2.log')
        return

    #循环检查门票
    ts = []  #同步门票到第三方系统的线程列表
    for mallBought in mallBoughtList:
        #同步门票
        for conf in config:
            # try:
            # print config[conf] + ':mall_nTicketType_' + str(mallBought['mall_product_id'])
            if conf == 'mall_nTicketType_' + str(
                    mallBought['mall_product_id']) and config[conf] != '':
                # print mallBought['id']
                # 给第三方增加门票
                t = threading.Thread(target=addTicketToOuterKZZN2,
                                     args=(
                                         config,
                                         mallBought,
                                     ))
                t.start()
                ts.append(t)
                break

                # print '========='
            # except:
            # print '========='
            # pass

    for t in ts:
        t.join()

    return True
Example #15
0
    def handle(self):
        global msg
        global clients
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        # print("{} wrote:".format(self.client_address[0]))
        # print(self.data)
        kv = self.data.split(',')

        if kv[0] == 'put':
            """
            put 数据格式如:put,somedata
            somedata会被追加到消息队列
            """
            msg.append(kv[1])
            # print(msg)
            # just send back the same data, but upper-cased
            # self.request.sendall(self.data.upper())
            self.request.sendall(str('200 OK'))
            if not int(random.random() * 1000) % 37:
                helper.getLog(str(msg), 'mq.server.msg.txt')
        elif kv[0] == 'get':
            """
            get 数据格式如:get,clientname
            根据clientname,返回最新的消息
            """
            try:
                msglen = len(msg)
                if not clients[kv[1]] == msglen:
                    self.request.sendall(str(msg[clients[kv[1]]: clients[kv[1]] + 20]))
                    clients[kv[1]] = msglen
                    # print msg[clients[kv[1]]:]
                # print clients[kv[1]]
                if msglen > 10000:
                    del msg[0: 50]
                    for k in clients:
                        clients[k] -= 50
                    print(clients)
            except:
                self.request.sendall(str(msg))
                clients[kv[1]] = len(msg)
                # print clients
        else:
            pass
Example #16
0
def sendDataToOuterHQ2(config, data):
    helper.getLog('访问sendDataToOuterHQ2!!!', 'responseOutCode.HQ2.log')
    url = config['url'] + '?op=OrderOccupies'

    headers = hawkAuth(url)
    data = '''<?xml version="1.0" encoding="utf-8"?>
            <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
            <soap:Body>
               <OrderOccupies xmlns="http://tempuri.org/">
                   <merchantCode>%s</merchantCode>
                   <postOrder>%s</postOrder>
                   <signature>%s</signature>
                </OrderOccupies>
            </soap:Body>
        </soap:Envelope>
       ''' % (data['merchantCode'], data['postOrder'], data['signature'])
    res = helper.httpPost(url, data, headers)
    resBody = json.loads(
        helper.subStr(res, '<OrderOccupiesResult>', '</OrderOccupiesResult>'))
    return resBody
Example #17
0
def processOuterJYZY(config, ticketBought, data, processCount):
    dbObj = db.db()
    # 发起同步
    dataOld = data
    data = buildParam(data, config['pkey'], 'createOrderForBeforePaySync')
    re = sendDataToOuterJYZY(config['url'], data)
    # redata, re = sendDataToOuterJYZY(config['url'], None)

    try:
        code = helper.subStr(re, '<code>', '</code>')
        # print responseBody
        # print re
        #成功同步
        if '1000' == code:
            re1 = re
            partnerorderId = helper.subStr(re, '<partnerorderId>', '</partnerorderId>')
            re, postData = payTicketToOuterJYZY(config, ticketBought, partnerorderId)
            # print partnerorderId;exit()

            code = helper.subStr(re, '<code>', '</code>')
            if '1000' == code:
                qrcodeUrl = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/index/?data=' + str(ticketBought['order_detail_id'])
                sql = "update t_ticket_bought set out_app_code = 'JYZY', temp_receiving_code = '%s', receiving_code = '%s', dimen_code_path='%s' where id = %d" %  (ticketBought['receiving_code'], partnerorderId, qrcodeUrl, ticketBought['id'])
                # print sql
                if not True == dbObj.update(sql):
                    helper.getLog(sql, 'addTicketToOuterJYZY.UpdateTicketboughtlistErr.log')
            else:
                re = "re1:%s \nre2:%s \nPostData1:%s \nPostData2:%s" % (re1, re, data, postData)
        else:
            re = "%s \nPostData:%s" % (re, data)
            print 'processCount:' + str(processCount)
            if processCount < 2:
                processCount += 1
                processOuterJYZY(config, ticketBought, dataOld, processCount)
                return
            else:
                re = "%s \nprocessCount:%s" % (re, str(processCount))
    except Exception, e:
        re = str(Exception) + ":" + str(e)
        re = "%s \nPostData:%s" %(re, data)
Example #18
0
def addMallToOuter_WJT(config, productConfig, mallBought):
    # print config;print productConfig;print mallBought;exit()

    dbObj = db.db()
    re = ''
    try:
        productConfig = dbObj.selectOne(
            'select id, out_code from t_mall_product where id = %d' %
            mallBought['mall_product_id'])
        if productConfig['out_code'] == '_WJT':
            re = '更新out_app_no为receiving_code:' + mallBought['receiving_code']
            sql = "update t_mall_bought set out_app_code = '_WJT', out_app_no = '%s' where id = '%d'" % (
                mallBought['receiving_code'], mallBought['id'])
            if not True == dbObj.update(sql):
                re += '(更新出错)'
                helper.getLog(
                    sql, 'addMallToService_WJT.UpdateMallboughtlistErr.log')
        else:
            re = '产品没有配置第三方系统代码。不处理。'

    except Exception, e:
        re = str(Exception) + ":" + str(e)
Example #19
0
def Service_WJT(config, ticketBoughtList, orderId):
    # print 'debug:';print config;print ticketBoughtList;print print 'debugEnd.';exit()
    helper.getLog(
        '-----------start: orderId: ' + str(orderId) + ', boughtCount: ' +
        str(len(ticketBoughtList)) + '-------------',
        'addTicketToService_WJT.log')
    if len(ticketBoughtList) < 1:
        return

    # print ticketBoughtList;exit()

    #循环检查门票
    ts = []  #同步门票到第三方系统的线程列表
    for bought in ticketBoughtList:
        # print bought['id']
        #同步门票
        try:
            # if conf == 'viewid_' + str(bought['mall_id']):
            # 给第三方增加门票
            # 配置为空,直接执行
            if len(config) == 0:
                helper.getLog('pos - 39', 'addTicketToService_WJT.log')
                t = threading.Thread(target=addTicketToOuter_WJT,
                                     args=(
                                         config,
                                         bought,
                                     ))
                t.start()
                ts.append(t)
            #配置有 ticket_ids 的情况,要进行判断
            if config.has_key('ticket_ids') and config['ticket_ids'] != '':
                ticketIds = config['ticket_ids'].split(",")
                helper.getLog(
                    'ticket_id: ' + str(bought['ticket_id']) +
                    ' ticketIds - ' + config['ticket_ids'],
                    'addTicketToService_WJT.log')
                # 只有指定了对接门票id 的门票才执行
                if str(bought['ticket_id']) in ticketIds:
                    t = threading.Thread(target=addTicketToOuter_WJT,
                                         args=(
                                             config,
                                             bought,
                                         ))
                    t.start()
                    ts.append(t)
            # break

            # print '========='
        except:
            # print '========='
            pass

    for t in ts:
        t.join()

    return True
Example #20
0
def runService(clientConfig, mallProductConfig, mallBoughts, code, configType):
    # for mallBought in mallBoughts:
    # if mallBought['client_id'] == 1257:
    # print clientConfig , code, mallBoughts,'==============================='

    #python
    if configType == 2:
        eval('Service' + code + '.MallService' + code)(clientConfig,
                                                       mallProductConfig,
                                                       mallBoughts)
    #java
    elif configType == 1:
        for mallBought in mallBoughts:
            requestData = {
                'type': 'mall',
                'key': '3e3bcd9d71d52132a9b413a57be173ca',
                'orderId': str(mallBought['order_id'])
            }
            # print urllib.urlencode(requestData);
            url = helper.confGet('host', 'nwxService') + 'api/order'
            reChar = helper.httpPost(url, requestData)
            res = json.loads(reChar)
            if res['isok']:
                #返回的验证码,如果下单失败,则为空
                if not res['codes']:
                    # print requestData
                    helper.getLog('重新下单失败 -- ' + url + ' -- ' + reChar +
                                  ' -- ' + urllib.urlencode(requestData))
                else:
                    helper.getLog('重新下单成功 -- ' + url + ' -- ' + reChar +
                                  ' -- ' + urllib.urlencode(requestData))
            else:
                helper.getLog('重新下单失败 -- ' + url + ' -- ' + reChar + ' -- ' +
                              urllib.urlencode(requestData))
    elif configType == 3:
        eval('Service' + code + '.MallService' + code)(clientConfig,
                                                       mallProductConfig,
                                                       mallBoughts)

    pass
Example #21
0
import util.helper as helper  #工具集
import util.db as db  #db操作类

HOST, PORT = "192.168.1.119", 9999
# Create a socket (SOCK_STREAM means a TCP socket)

try:
    n = 0
    while True:
        for i in range(1, 5):
            n += 1
            data = ",".join([
                'put', 'a' + str(n) + '_' + str(i) + '_' + str(random.random())
            ])
            print data
            # Connect to server and send data
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((HOST, PORT))
            sock.sendall(bytes(data + "\n"))

            # Receive data from the server and shut down
            received = str(sock.recv(1024))
            # print i
            # print("Sent:     {}".format(data))
            # print("Received: {}".format(received))
            helper.getLog(received + ' -- ' + data, 'mq.client.put1.txt')
        time.sleep(0.1)
finally:
    sock.close()
    pass
Example #22
0
def addTicketToOuterSZZWY(config, ticketBought):
    # global dbObj
    # dbObj = globalVar.getDbObj()
    dbObj = db.db()

    #查询游客信息
    # userInfo = ''
    userInfo = dbObj.select(
        "select user_id, name, mobile from t_user_identity_info where id = %d"
        % ticketBought['identity_info_id'])
    if userInfo == False or len(userInfo) < 1:
        visitorName = 'wjtVisitor'
        visitorMobile = '18523876001'
    else:
        userInfo = userInfo[0]
        visitorName = userInfo['user_id']
        visitorMobile = userInfo['mobile']

    products = [{
        'viewid': config['viewid_' + str(ticketBought['ticket_id'])]
    }, {
        'Viewname': ticketBought['ticket_id']
    }, {
        'Type': config['Type_' + str(ticketBought['ticket_id'])]
    }, {
        'number': ticketBought['count']
    }]

    orderInfo = [
        {
            'TimeStamp': helper.now()
        },
        {
            'CompanyCode': config['CompanyCode']
        },
        {
            'CompanyName': 'weijingtong'
        },
        {
            'CompanyOrderID': ticketBought['order_id']
        },
        {
            'OrderTime': ticketBought['create_time']
        },
        {
            'ArrivalDate': ticketBought['plan_time']
        },
        {
            'PayType': 1
        },
        {
            'VisitorName': visitorName
        },
        {
            'VisitorMobile': visitorMobile
        },
        {
            'IdCardNeed': 0
        },
        {
            'IdCard': '1X'
        },
        {
            'Note': 'weijingtong'
        },
        {
            'Products':
            helper.dict2xml('product',
                            products).replace('<',
                                              '&lt;').replace('>', '&gt;')
        },
    ]
    data = helper.dict2xml('OrderInfo', orderInfo)
    data = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><OrderReq xmlns="http://tempuri.org/">%s</OrderReq></soap:Body></soap:Envelope>' % data
    # data = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><OrderReq xmlns="http://tempuri.org/"><OrderInfo><TimeStamp>2017-02-21 19:41:29</TimeStamp><CompanyCode>weijingtong96325812zfr</CompanyCode><CompanyName>weijingtong</CompanyName><CompanyOrderID>225534</CompanyOrderID><OrderTime>2017-02-21 19:34:33</OrderTime><ArrivalDate>2017-02-21 00:00:00</ArrivalDate><PayType>1</PayType><VisitorName>oZ9oauAoKfN1C4OptkqQbSeXhW-k</VisitorName><VisitorMobile>18723012341</VisitorMobile><IdCardNeed>0</IdCardNeed><IdCard>1X</IdCard><Note>weijingtong</Note><Products>&lt;product&gt;&lt;viewid&gt;E03&lt;/viewid&gt;&lt;Viewname&gt;2649&lt;/Viewname&gt;&lt;Type&gt;Adult&lt;/Type&gt;&lt;number&gt;1&lt;/number&gt;&lt;/product&gt;</Products></OrderInfo></OrderReq></soap:Body></soap:Envelope>'
    # data = '''<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/"><SOAP-ENV:Body><ns1:OrderReq><ns1:OrderInfo><ns1:TimeStamp>2017-02-21 15:34:49</ns1:TimeStamp><ns1:CompanyCode>weijingtong96325812zfr</ns1:CompanyCode><ns1:CompanyName>weijingtong</ns1:CompanyName><ns1:CompanyOrderID>186738</ns1:CompanyOrderID><ns1:OrderTime>2017-02-21 15:34:49</ns1:OrderTime><ns1:ArrivalDate>2017-02-21</ns1:ArrivalDate><ns1:PayType>1</ns1:PayType><ns1:VisitorName>WeijingtongVisitor</ns1:VisitorName><ns1:VisitorMobile>18523876001</ns1:VisitorMobile><ns1:IdCardNeed>0</ns1:IdCardNeed><ns1:IdCard>1X</ns1:IdCard><ns1:Products>&lt;product&gt;&lt;viewid&gt;E03&lt;/viewid&gt;&lt;Type&gt;Adult&lt;/Type&gt;&lt;number&gt;1&lt;/number&gt;&lt;viewname&gt;21&lt;/viewname&gt;&lt;/product&gt;</ns1:Products></ns1:OrderInfo></ns1:OrderReq></SOAP-ENV:Body></SOAP-ENV:Envelope>'''
    # data = '''<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/"><SOAP-ENV:Body><ns1:OrderCancel><ns1:orderInfo><ns1:TimeStamp>2017-02-21 19:39:50</ns1:TimeStamp><ns1:CompanyCode>weijingtong96325812zfr</ns1:CompanyCode><ns1:CompanyOrderID>186749</ns1:CompanyOrderID><ns1:IdCardNeed>0</ns1:IdCardNeed></ns1:orderInfo></ns1:OrderCancel></SOAP-ENV:Body></SOAP-ENV:Envelope>'''
    # print data;exit()

    try:
        # 发起同步
        url = config[
            'url']  #http://ydpt.hdyuanmingxinyuan.com/interface/AgentInterface.asmx
        host = helper.subStr(url, 'http://', '/interface')

        webservice = httplib.HTTPConnection(host, 80, timeout=50)
        # webservice.set_debuglevel(1)

        # print response.getheaders() #获取头信息
        #连接到服务器后的第一个调用。它发送由request字符串到到服务器
        webservice.putrequest("POST", "/interface/AgentInterface.asmx")
        # webservice.putheader("Accept-Encoding", "text")
        # webservice.putheader("Host", "ydpt.hdyuanmingxinyuan.com")
        webservice.putheader("User-Agent", "WeijingtongService-python")
        webservice.putheader("Content-Type", "text/xml; charset=utf-8")
        # webservice.putheader("Connection", "Keep-Alive")
        webservice.putheader("Content-Length", "%d" % len(data))
        webservice.putheader("SOAPAction", "\"http://tempuri.org/OrderReq\"")
        # webservice.putheader("SOAPAction", "\"http://tempuri.org/OrderCancel\"")
        #发送空行到服务器,指示header的结束
        webservice.endheaders()
        #发送报文数据到服务器
        webservice.send(data)
        #获取返回HTTP 响应信息
        response = webservice.getresponse()
        responseBody = response.read()
        # print 'response:'
        # print response.read()
        # exit()
        res = []
        res.append('HttpStatus:' + str(response.status))
        res.append('HttpReason:' + response.reason)
        res.append('HttpBody:' + responseBody)
        head = []
        for header in response.getheaders():
            head.append('%s: %s' % (header[0], header[1]))

        head = "\n".join(head)
        res.append('HttpHeader:' + head)  #获取头信息
        # print res
        # exit()
        re = "\n".join(res)
        # re = re.decode('gb2312').encode('utf-8')

        webservice.close()  #关闭链接

        #成功同步
        if 'true' == helper.subStr(responseBody, '<Result>', '</Result>'):
            sql = "update t_ticket_bought set out_app_code = 'YMXY', temp_receiving_code = 'None' where id = %d" % ticketBought[
                'id']
            if not True == dbObj.update(sql):
                helper.getLog(
                    sql, 'addTicketToOuterYMXY.UpdateTicketboughtlistErr.log')
        pass
    except Exception, e:
        re = str(Exception) + ":" + str(e)
        re = "%s \npostdata:%s" % (re, data)
Example #23
0
        res.append('HttpHeader:' + head)  #获取头信息
        # print res
        # exit()
        re = "\n".join(res)
        # re = re.decode('gb2312').encode('utf-8')

        webservice.close()  #关闭链接

        #成功同步
        if 'true' == helper.subStr(responseBody, '<Result>', '</Result>'):
            sql = "update t_ticket_bought set out_app_code = 'YMXY', temp_receiving_code = 'None' where id = %d" % ticketBought[
                'id']
            if not True == dbObj.update(sql):
                helper.getLog(
                    sql, 'addTicketToOuterYMXY.UpdateTicketboughtlistErr.log')
        pass
    except Exception, e:
        re = str(Exception) + ":" + str(e)
        re = "%s \npostdata:%s" % (re, data)
    #保存日志到数据库
    sql = "insert into t_order_outapp_msg (client_id, order_id, order_detail_id, type, outapp_code, content, create_time) \
        values ('%d', '%d', '%d', '%d', '%s', '%s', '%s') "

    values = (ticketBought['client_id'], ticketBought['order_id'],
              ticketBought['order_detail_id'], 1, 'YMXY', re, helper.now())
    # print sql
    re = dbObj.insert(sql, values)
    # print re
    if not re == True:
        helper.getLog(re, 'addTicketToOuterYMXY.SqlErr.log')
Example #24
0
def addTicketToOuterDK(config, ticketBought):
    # global dbObj
    # dbObj = globalVar.getDbObj()
    dbObj = db.db()

    #查询游客信息
    # userInfo = ''
    userInfo = dbObj.select(
        "select user_id, name, mobile, id_number from t_user_identity_info where id = %d"
        % ticketBought['identity_info_id'])
    # userInfo = []
    # userInfo.append({
    # 'name': '微景通',
    # 'mobile' : '18523876001'
    # })
    if userInfo == False or len(userInfo) < 1:
        visitorName = 'weijingtongVisitor'
        visitorMobile = '18523876001'
    else:
        userInfo = userInfo[0]
        visitorMobile = userInfo['mobile']
        ##        visitorName = userInfo['user_id']
        visitorName = userInfo['name']
        visitorName = repr(visitorName.decode('UTF-8'))[2:-1]
##        visitorName = '\u5f20\u8001\u5927'
##        visitorName = urllib.urlencode({1:visitorName})[2:]

# visitorName = 'wjtVisitor'
    ticketName = dbObj.getValue(
        "select name from t_ticket where id = %d" % ticketBought['ticket_id'],
        'name')
    # ticketName = '成人票'
    ticketName = repr(ticketName.decode('UTF-8'))[2:-1][0:48]
    # ticketName = 'test'
    Order = {}
    Order['OrderNO'] = str(ticketBought['order_detail_id'])
    Order['LinkName'] = visitorName
    Order['LinkPhone'] = visitorMobile
    Order['LinkICNO'] = userInfo['id_number']
    Order['TotalAmount'] = str(
        round(ticketBought['price'] * ticketBought['count'], 2))
    Order['CreateTime'] = str(ticketBought['create_time'])

    Visitor = {}
    Visitor['VisitorName'] = visitorName
    Visitor['VisitorPhone'] = visitorMobile
    Visitor['VisitorICNO'] = userInfo['id_number']

    Details = {}
    Details['OrderNO'] = ticketBought['order_detail_id']
    Details['ItemID'] = ticketBought['order_detail_id']
    Details['ProductCode'] = config['ProductCode_' +
                                    str(ticketBought['ticket_id'])]
    Details['ProductID'] = config['ProductID_' +
                                  str(ticketBought['ticket_id'])]
    Details['ProductPackID'] = config['ProductPackID_' +
                                      str(ticketBought['ticket_id'])]
    Details['ProductMarketPrice'] = str(round(ticketBought['list_price'], 2))
    Details['ProductPrice'] = str(round(ticketBought['price'], 2))
    Details['ProductSellPrice'] = str(round(ticketBought['price'], 2))
    Details['ProductCount'] = ticketBought['count']
    Details['ProductSDate'] = str(ticketBought['plan_time'])[0:10]
    Details['ProductEDate'] = str(ticketBought['plan_time'])[0:10]
    Details['Visitor'] = json.dumps(Visitor)

    postOrder = {}
    postOrder['Ptime'] = helper.now()
    postOrder['parkCode'] = config['parkCode']
    postOrder['timestamp'] = helper.now()
    postOrder['Order'] = json.dumps(Order)
    postOrder['Details'] = json.dumps([Details])

    # print postOrder
    # print json.dumps(postOrder)
    postOrder = json.dumps(postOrder)
    # exit()
    sign = base64.encodestring(
        helper.md5(config['merchantCode'] + config['privateKey'] + postOrder +
                   str(int(helper.thisTime()))).upper()).strip()
    # sign = '1'
    # print sign;exit()

    data = '''<?xml version="1.0" encoding="utf-8"?>
            <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                <soap:Body>
                    <OrderOccupies xmlns="http://tempuri.org/">
                          <merchantCode>%s</merchantCode>
                          <postOrder>%s</postOrder>
                          <signature>%s</signature>
                    </OrderOccupies>
                </soap:Body>
            </soap:Envelope>''' % (config['merchantCode'], postOrder, sign)
    # print data;
    # exit();
    try:
        # 发起同步
        '''
        responseBody = helper.httpPost(config['url'] + '/OrderOccupies', data, {'Content-Type' : 'application/x-www-form-urlencoded'})
        '''
        url = config['url']  #http://123.11.226.80:8118/service.asmx
        # url  = 'http://112.74.131.57:10006/service.asmx'
        host = helper.subStr(url, 'http:/', 'service')
        host = helper.subStr(host, '/', ':')
        port = helper.subStr(url, '://', 'service')
        port = helper.subStr(port, ':', '/')
        # print host;exit()

        #占用定单
        res = helper.webservice(host, int(port), "/service.asmx", data,
                                "http://tempuri.org/OrderOccupies", 0)
        responseBody = res[0]
        re = res[1]
        reBody = json.loads(
            helper.subStr(responseBody, '<OrderOccupiesResult>',
                          '</OrderOccupiesResult>'))
        # print reBody
        #成功同步
        if '00' == reBody['ResultCode']:
            #支付定单
            parameters = {}
            parameters['otaOrderNO'] = str(ticketBought['order_detail_id'])
            parameters['parkCode'] = config['parkCode']
            parameters['timestamp'] = helper.now()
            parameters = json.dumps(parameters)

            sign = base64.encodestring(
                helper.md5(config['merchantCode'] + config['privateKey'] +
                           parameters +
                           str(int(helper.thisTime()))).upper()).strip()

            data2 = '''<?xml version="1.0" encoding="utf-8"?>
                    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                        <soap:Body>
                            <OrderFinish xmlns="http://tempuri.org/">
                              <otaCode>%s</otaCode>
                              <parameters>%s</parameters>
                              <signature>%s</signature>
                            </OrderFinish>
                        </soap:Body>
                    </soap:Envelope>''' % (config['merchantCode'], parameters,
                                           sign)

            res = helper.webservice(host, int(port), "/service.asmx", data2,
                                    "http://tempuri.org/OrderFinish", True)
            responseBody2 = res[0]
            re2 = res[1]
            reBody = json.loads(
                helper.subStr(responseBody2, '<OrderFinishResult>',
                              '</OrderFinishResult>'))
            # print reBody
            if '00' == reBody['ResultCode']:
                re = re + "\n\n" + re2
                #生成二维码
                resultJson = json.loads(reBody['ResultJson'])[0]
                qrcodeImg = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/?data=' + resultJson[
                    'ECode']
                sql = "update t_ticket_bought set out_app_code = 'DK', temp_receiving_code = '%s', receiving_code='%s', dimen_code_path = '%s' where id = %d" % (
                    ticketBought['receiving_code'], resultJson['ECode'],
                    qrcodeImg, ticketBought['id'])
                # print sql
                if not True == dbObj.update(sql):
                    helper.getLog(
                        sql,
                        'addTicketToOuterDK.UpdateTicketboughtlistErr.log')
            else:
                re = "%s\nPostData1:%s\n\n%s\nPostData2:%s" % (re, data, re2,
                                                               data2)
                pass

        else:
            re = "%s \nPostData:%s" % (re, data)
            pass
    except Exception, e:
        re = str(Exception) + ":" + str(e)
        re = "%s \nPostData:%s" % (re, data)
Example #25
0
def addTicketToOuterZXK(config, ticketBought):
    # global dbObj
    # dbObj = globalVar.getDbObj()
    dbObj = db.db()

    #查询游客信息
    # userInfo = ''
    userInfo = dbObj.select(
        "select user_id, name, mobile, id_number from t_user_identity_info where id = %d"
        % ticketBought['identity_info_id'])
    # userInfo = []
    # userInfo.append({
    # 'name': '微景通',
    # 'mobile' : '18523876001'
    # })
    if userInfo == False or len(userInfo) < 1:
        visitorName = 'weijingtongVisitor'
        visitorMobile = '18523876001'
        visitorIdNumber = '110102198601018573'
    else:
        userInfo = userInfo[0]
        visitorMobile = userInfo['mobile']
        visitorIdNumber = userInfo['id_number']
        ##        visitorName = userInfo['user_id']
        visitorName = userInfo['name']
        visitorName = repr(visitorName.decode('UTF-8'))[2:-1]
##        visitorName = '\u5f20\u8001\u5927'
##        visitorName = urllib.urlencode({1:visitorName})[2:]

# visitorName = 'wjtVisitor'
    ticketName = dbObj.getValue(
        "select name from t_ticket where id = %d" % ticketBought['ticket_id'],
        'name')
    # ticketName = '成人票'
    # ticketName = repr(ticketName.decode('UTF-8'))[2:-1][0:48]
    # ticketName = 'test'
    visitPerson = '''[
        {    "name": "%s",
            "mobile": "%s",
            "idCard": "%s"
        }
    ]''' % (visitorName[0:24], visitorMobile, visitorIdNumber)
    requestBody = '''{
        "orderSerialId": "%s",
        "productNo": "%s",
        "payType": 1,
        "tickets": %s,
        "price": %s,
        "contractPrice": %s,
        "bookName": "%s",
        "bookMobile": "%s",
        "idCard": "%s",
        "travelDate": "%s",
        "visitPerson": %s
    }''' % (ticketBought["order_detail_id"],
            config["productNo_" + str(ticketBought["ticket_id"])],
            ticketBought["count"], int(ticketBought["price"] * 100),
            int(ticketBought["price"] * 100), visitorName[0:24], visitorMobile,
            visitorIdNumber, str(ticketBought["plan_time"])[0:10], visitPerson)

    # print requestBody;exit();
    # data = '{"pageIndex":1,"pageSize":100}' # 1/F4jrg9alyN0uDgJNlEaCLroiTtH9LhlljImdztF8Y=
    KEY = str(config['user_key'])  #密钥
    IV = str(config['user_key'])  #偏转向量
    desObj = des(KEY, ECB, IV, pad=None,
                 padmode=PAD_PKCS5)  # 使用DES对称加密算法的CBC模式加密
    # requestBody = 'adfasfaf'
    requestBody = str(requestBody)
    requestBodyFormat = requestBody
    # print helper.httpPost('http://123.56.105.30:5677/Tongcheng/Encrypt/', requestBody);exit(); #获取des密文
    # print (requestBody);
    # print (str(config['user_key']) );
    requestBody = desObj.encrypt(requestBody)
    # print base64.encodestring(b2a_hex(requestBody))
    requestBody = base64.encodestring(requestBody)
    # print requestBody;
    # print "Decrypted: %r" % desObj.decrypt(base64.decodestring(requestBody));exit()

    timestamp = str(time.time())[0:10]

    sign = config['user_id'] + 'CreateOrder' + str(
        timestamp) + 'v1.0' + requestBody + config['user_key']
    # print (sign);
    md5Obj = md5.new()
    md5Obj.update(sign)
    sign = md5Obj.hexdigest()

    requestHead = '''{
        "user_id": "%s",
        "method": "CreateOrder",
        "timestamp": %s,
        "version": "v1.0",
        "sign": "%s"
    }''' % (config["user_id"], timestamp, sign)
    data = '''{
        "requestHead": %s,
        "requestBody": "%s"
    }''' % (requestHead, requestBody)

    # print (data);
    # exit();

    try:
        re = helper.httpPost(config['url'], data)

        #成功同步
        res = json.loads(re)
        # print res;
        # print res['responseHead']['res_code'];
        # print json.loads(desObj.decrypt(base64.decodestring(res['responseBody'])))
        responseBody = desObj.decrypt(base64.decodestring(res['responseBody']))
        re = re + "\nResponseBodyFormat:" + responseBody
        responseBody = json.loads(responseBody)
        # exit();
        #成功同步
        if '1000' == res['responseHead']['res_code'] or '2001' == res[
                'responseHead']['res_code']:
            sql = "update t_ticket_bought set out_app_code='ZXK', temp_receiving_code='%s', dimen_code_path='%s', remark2='%s' where id = %d" % (
                responseBody['partnerCode'],
                responseBody['partnerQRCodeAddress'],
                responseBody['partnerOrderId'], ticketBought['id'])
            # print sql
            if not True == dbObj.update(sql):
                helper.getLog(
                    sql, 'addTicketToOuterZXK.UpdateTicketboughtlistErr.log')
        else:
            re = "%s \nPostData:%s\nRequestBodyFormat:%s" % (re, data,
                                                             requestBodyFormat)
            pass
    except Exception, e:
        re = str(Exception) + ":" + str(e)
        re = "%s \nPostData:%s\nRequestBodyFormat:%s" % (re, data,
                                                         requestBodyFormat)
Example #26
0

#同步门票到第三方系统的线程列表
def addTicketToOuter_WJT(config, bought):
    #print config;print print bought;exit()
    helper.getLog('thread start - ' + str(bought['id']),
                  'addTicketToService_WJT.log')
    dbObj = db.db()
    try:
        re = '更新out_app_no为receiving_code:' + bought['receiving_code']
    except Exception, e:
        errMsg = "[Service_WJT - 71]" + str(Exception) + ":" + str(e)
        re = 'update out_app_no to receiving_code: ' + bought['receiving_code']
        helper.getLog(errMsg, 'addTicketToService_WJT.Err.log')

    helper.getLog('pos - 77', 'addTicketToService_WJT.log')

    try:
        qrcodeUrl = 'http://pwx.weijingtong.net/index.php/Api/Qrcode/index/?data=' + str(
            bought['receiving_code'])
        sql = "update t_ticket_bought set out_app_code = '_WJT', temp_receiving_code = '%s', dimen_code_path='%s' where id = '%d'" % (
            bought['receiving_code'], qrcodeUrl, bought['id'])

        if not True == dbObj.update(sql):
            helper.getLog(
                sql, 'addTicketToService_WJT.UpdateTicketboughtlistErr.log')
    except Exception, e:
        re = str(Exception) + ":" + str(e)

    helper.getLog('pos - 88', 'addTicketToService_WJT.log')
    re = re.replace("'", '"')
Example #27
0
def addTicketToOuterJKB(config, ticketBought):
    # global dbObj
    # dbObj = globalVar.getDbObj()
    dbObj = db.db()

    #查询游客信息
    # userInfo = ''
    userInfo = dbObj.select(
        "select user_id, name, mobile, id_number from t_user_identity_info where id = %d"
        % ticketBought['identity_info_id'])
    # userInfo = []
    # userInfo.append({
    # 'name': '微景通',
    # 'mobile' : '18523876001'
    # })
    if userInfo == False or len(userInfo) < 1:
        visitorName = 'weijingtongVisitor'
        visitorMobile = '18523876001'
    else:
        userInfo = userInfo[0]
        visitorMobile = userInfo['mobile']
        ##        visitorName = userInfo['user_id']
        visitorName = userInfo['name']
        visitorName = urllib.quote(visitorName.encode('utf-8'))
        # visitorName = repr(visitorName.decode('UTF-8'))[2:-1]
##        visitorName = '\u5f20\u8001\u5927'
##        visitorName = urllib.urlencode({1:visitorName})[2:]

# visitorName = 'wjtVisitor'
    ticketName = dbObj.getValue(
        "select name from t_ticket where id = %d" % ticketBought['ticket_id'],
        'name')
    ticketName = urllib.quote(ticketName.encode('utf-8'))
    # ticketName = '成人票'
    # ticketName = repr(ticketName.decode('UTF-8'))[2:-1][0:48]
    # ticketName = 'test'

    visitPerson = {}
    visitPerson['visitName'] = visitorName
    visitPerson['visitMobile'] = visitorMobile
    visitPerson['credentials'] = userInfo['id_number']
    visitPerson['credentialsType'] = 'Idcard'

    body = {}
    body['productName'] = ticketName
    body['contactMobile'] = visitorMobile
    body['contactName'] = visitorName
    body['orderPrice'] = str(round(ticketBought['price'], 2))
    body['orderQuantity'] = ticketBought['count']
    body['orderRemark'] = 'weijingtong'
    body['outOrderId'] = ticketBought['order_detail_id']
    body['resourceId'] = config['resourceId_' + str(ticketBought['ticket_id'])]
    body['sellPrice'] = str(round(ticketBought['list_price'], 2))
    body['useDate'] = str(ticketBought['plan_time'])[0:10]
    body['visitPerson'] = [visitPerson]

    data = {}
    data['body'] = body
    data['appKey'] = config['AppKey']

    data = json.dumps(data, ensure_ascii=False)
    # data = json.dumps(data)
    # print data
    # exit()
    # time = str(helper.thisTime())[0:10] + str(int(str(helper.thisTime())[12:])*100)
    time = str(int(round(helper.thisTime() * 1000)))
    # time = '1'
    print config['AppKey'] + data + time + config['SecretKey']
    sign = helper.md5(config['AppKey'] + data + time +
                      config['SecretKey']).upper().strip()
    # sign = '1'

    httpHeader = {
        'Content-Type': 'application/json;charset=utf-8',
        'APPKEY': config['AppKey'],
        'TIMESTAMP': time,
        'SIGN': sign,
    }
    # print httpHeader;
    print sign
    # exit()
    try:
        # 发起同步
        re = helper.httpPost(config['url'] + '?method=createOrder', data,
                             httpHeader)
        reBody = json.loads(re)
        # print reBody ;exit()
        #成功同步
        if 200 == reBody['rspCode']:
            #支付定单
            body = {}
            body['orderId'] = outOrderId = reBody['body']['orderId']
            body['paymentSerialno'] = ticketBought['id']

            data2 = {}
            data2['body'] = body
            data2['appKey'] = config['AppKey']
            data2 = json.dumps(data2)

            # print data2;exit()
            sign = helper.md5(config['AppKey'] + data2 + time +
                              config['SecretKey']).upper().strip()
            httpHeader = {
                'Content-Type': 'application/json;charset=utf-8',
                'APPKEY': config['AppKey'],
                'TIMESTAMP': time,
                'SIGN': sign,
            }

            re2 = helper.httpPost(config['url'] + '?method=payOrder', data2,
                                  httpHeader)
            reBody = json.loads(re2)
            print reBody
            if 200 == reBody['rspCode']:
                re = re + "\n\n" + re2
                print re
                #生成二维码
                qrcodeImg = reBody['body']['qrcodeUrl']
                sql = "update t_ticket_bought set out_app_code = 'JKB', temp_receiving_code = '%s', receiving_code='%s', dimen_code_path = '%s', remark2 = '%s' where id = %d" % (
                    ticketBought['receiving_code'], reBody['body']['eticket'],
                    qrcodeImg, '{"outOrderId":"' + outOrderId + '"}',
                    ticketBought['id'])
                print sql
                if not True == dbObj.update(sql):
                    helper.getLog(
                        sql,
                        'addTicketToOuterJKB.UpdateTicketboughtlistErr.log')
            else:
                re = "%s\nPostData1:%s\n\n%s\nPostData2:%s" % (re, data, re2,
                                                               data2)
                print re
                pass

        else:
            re = "%s \nPostData:%s\nPostHead:%s" % (re, data,
                                                    json.dumps(httpHeader))
            pass
    except Exception, e:
        re = str(Exception) + ":" + str(e)
        re = "%s \nPostData:%s" % (re, data)
Example #28
0
import json
from urlparse import urlparse
import socket
import socket
import sys
import util.helper as helper  #工具集
import util.db as db  #db操作类

HOST, PORT = "192.168.1.119", 9999
# Create a socket (SOCK_STREAM means a TCP socket)

try:
    while True:
        data = ",".join(['get', 'client2'])
        # print data
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # Connect to server and send data
        sock.connect((HOST, PORT))
        sock.sendall(bytes(data + "\n"))

        # Receive data from the server and shut down
        received = str(sock.recv(1024))
        if len(received) > 1:
            print("Sent:     {}".format(data))
            print("Received: {}".format(received))
            for v in eval(received):
                helper.getLog(str(v), 'mq.client.get2.txt')
        time.sleep(0.1)
finally:
    sock.close()
Example #29
0
def serviceInit(codes):

    #连接数据库
    dbObj = db.db()
    # try:
    # dbObj = globalVar.getDbObj() #数据库链接
    # except:
    # dbObj = db.db()
    # globalVar.setDbObj(dbObj)

    ts = []  #线程列表

    #初始化所有code的maxBoughtId为0
    # maxBoughtId = dbObj.getValue("select id from t_ticket_bought order by id desc ", 'id')
    # globalVar.setMaxBoughtId(maxBoughtId)
    globalVar.setMaxBoughtId(320672)
    # print maxBoughtId

    #为了减少数据库查询,初始化时查询出查询商家列表。新添加商家后,需要重启本服务,否则无法监听添加新的。
    # clientList = dbObj.select("select client_id, content, code from t_out_app_config where code in('%s')" % "','".join(codes))

    #启动服务
    i = -1
    while True:
        maxBoughtId = globalVar.getMaxBoughtId()
        print i, maxBoughtId
        helper.getLog("%i -- maxBoughtId:%s" % (i, maxBoughtId),
                      'serviceTicket.log')
        # 不用每次循环都查询配置
        i += 1
        if i > 100:
            i = 0
        if i % 4 == 0:
            #为了商家修改了门票配置信息时立即生效,改为每次查询
            clientList = dbObj.select(
                "select client_id, content, code from t_out_app_config where code in('%s')"
                % "','".join(codes))

        #按code给商家列表分组
        clientIds = []  #client id
        clientCodes = {}  #
        clientConfigs = {}  #client config
        for client in clientList:
            clientCodes[str(client['client_id'])] = client['code']
            clientIds.append(str(client['client_id']))
            clientConfigs[str(client['client_id'])] = json.loads(
                client['content'])
        # print clientCodes;exit()

        #查询已购门票列表
        now = helper.now(-3600 * 24 * 1)
        # now = helper.now(-60)
        sql = ' '.join([
            "select id, client_id,  ticket_id, count, order_id, order_detail_id, price, list_price, identity_info_id, create_time, plan_time, receiving_code ",
            # "select id, client_id",
            "from t_ticket_bought ",
            "where id > '%d' and status = 1 and out_app_code is null and create_time < '%s' and create_time > '%s' and client_id in (%s) "
            % (globalVar.getMaxBoughtId(), helper.now(-20), now,
               ','.join(clientIds)),
            # "where order_detail_id = 697201",
            "order by id asc limit 0, 20",  # limit 0, 50
        ])
        ticketBoughtList = dbObj.select(sql)
        #print  sql;  print ticketBoughtList;
        # exit()

        #把最大的id记录下来
        try:
            maxBoughtId = ticketBoughtList[-1]['id']
            globalVar.setMaxBoughtId(maxBoughtId)
            # print  maxBoughtIds['YMXY']
        except:
            pass

        #按client_id给ticketBoughtList分组
        ticketBoughts = {}
        if len(ticketBoughtList) > 0:
            for ticketBought in ticketBoughtList:
                try:
                    ticketBoughts[ticketBought['client_id']].append(
                        ticketBought)
                except:
                    ticketBoughts[ticketBought['client_id']] = []
                    ticketBoughts[ticketBought['client_id']].append(
                        ticketBought)
            # print ticketBoughts;exit()
            # print clientIds;exit()
            #循环检查每个商家
            for clientId in clientIds:
                # print clientId
                try:
                    code = clientCodes[clientId]
                    t = threading.Thread(target=runService,
                                         args=(
                                             clientConfigs[clientId],
                                             ticketBoughts[int(clientId)],
                                             code,
                                         ))
                    t.start()
                    ts.append(t)
                except:
                    pass

            for t in ts:
                t.join()

        # print globalVar.getMaxBoughtId()
        #每x秒执行一次
        time.sleep(60)
Example #30
0
    except Exception, e:
        re = str(Exception) + ":" + str(e)
        re = "%s \nPostData:%s" % (re, data)
    re = re.replace("'", '"')
    # print re;exit()
    #保存日志到数据库
    sql = "insert into t_order_outapp_msg (client_id, order_id, order_detail_id, type, outapp_code, content, create_time) \
           values ('%d', '%d', '%s', '%d', '%s', '%s', '%s') "

    values = (mallBought['client_id'], mallBought['order_id'],
              mallBought['order_number'], 1, 'KZZN2', re, helper.now())
    # print sql
    re = dbObj.insert(sql, values)
    # print re
    if not re == True:
        helper.getLog('insert into t_order_outapp_msg error: ' + re,
                      'mall.kzzn2')


def sendDataToOuterKZZN2(host, port, data):
    # return ['<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><OnWebOrderResponse xmlns="http://127.0.0.1/WebSellWx/"><OnWebOrderResult><nStatus>1</nStatus><cStatus>OK</cStatus><cUrl>/images/722399640.jpg</cUrl><cQrCode>722399640</cQrCode></OnWebOrderResult></OnWebOrderResponse></soap:Body></soap:Envelope>', '']
    webservice = httplib.HTTPConnection(host, port, timeout=50)
    # webservice.set_debuglevel(1)

    #连接到服务器后的第一个调用。它发送由request字符串到到服务器
    webservice.putrequest("POST", "/service.asmx")
    # webservice.putheader("Accept-Encoding", "text")
    # webservice.putheader("Host", "123.11.226.80")
    webservice.putheader("User-Agent", "WeijingtongService-python")
    webservice.putheader("Content-Type", "text/xml; charset=utf-8")
    # webservice.putheader("Connection", "Keep-Alive")
    webservice.putheader("Content-Length", "%d" % len(data))