def process_clickkey(self, cr, uid, key, jsonStr, context): content = "" # if 'EventKey' in jsonStr: # content = jsonStr['EventKey'] # if content=="": # content=key # else: # content = key content = key print content fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] env = Environment(cr, uid, context) if 'AgentID' in jsonStr: agentID = jsonStr['AgentID'] wxOfficeAccountInfo = env[ 'wx.officialaccount'].getqyhofficialaccount(toUser, agentID) else: wxOfficeAccountInfo = env['wx.officialaccount'].getofficialaccount( toUser) text_template = {} text_template.update({"id": ""}) #self.processmessage(fromUser,cr,uid,context, content, wxOfficeAccountInfo) threaded_run = threading.Thread(target=self.processmessage, args=(fromUser, cr, uid, context, content, wxOfficeAccountInfo)) threaded_run.start() return ""
def create_qy_text_record(self, cr, uid, jsonStr, agentid, context): content = jsonStr['Content'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] MsgId = jsonStr['MsgId'] env = Environment(cr, uid, context) wxOfficeAccountInfo = env['wx.officialaccount'].search([ ('wx_appid', '=', toUser), ('wx_qyh_app_id', '=', agentid) ])[0] text_template = {} text_template.update({"id": ""}) try: env['send_message'].insert_qy_text_record(fromUser, wxOfficeAccountInfo, env, content, text_template, "", False, MsgId, 'use_sucess', 'receive') except Exception as e: _logger.info("插入企业号文本消息记录出错:" + str(e)) cr.commit() threaded_run = threading.Thread(target=self.processmessage, args=(fromUser, cr, uid, context, content, wxOfficeAccountInfo)) threaded_run.start() return ""
def _procure_calculation_all(self, cr, uid, ids, context=None): """ @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary """ with Environment.manage(): proc_obj = self.pool.get('procurement.order') #As this function is in a new thread, i need to open a new cursor, because the old one may be closed new_cr = self.pool.cursor() scheduler_cron_id = self.pool['ir.model.data'].get_object_reference(new_cr, SUPERUSER_ID, 'procurement', 'ir_cron_scheduler_action')[1] # Avoid to run the scheduler multiple times in the same time try: with tools.mute_logger('yuancloud.sql_db'): new_cr.execute("SELECT id FROM ir_cron WHERE id = %s FOR UPDATE NOWAIT", (scheduler_cron_id,)) except Exception: _logger.info('Attempt to run procurement scheduler aborted, as already running') new_cr.rollback() new_cr.close() return {} user = self.pool.get('res.users').browse(new_cr, uid, uid, context=context) comps = [x.id for x in user.company_ids] for comp in comps: proc_obj.run_scheduler(new_cr, uid, use_new_cursor=new_cr.dbname, company_id = comp, context=context) #close the new cursor new_cr.close() return {}
def friendshare(self, **post): page = 'wx_weblink.shareinfo' values = {} cr, uid, context = request.cr, request.uid, request.context env = Environment(cr, SUPERUSER_ID, context) parmsdata = request.params if 'code' not in parmsdata: return request.website.render('website.404') code = parmsdata['code'] link_tracker = env['link.tracker.code'].search([('code', '=', code)]) if link_tracker: sign_info = {} url = request.httprequest.url print url # try: # officalaccount = "" # link_tracker = env['link.tracker.code'].search([('code', '=', code)]) # if link_tracker: # officalaccount = link_tracker[0]['link_id']['officialaccount'] # print officalaccount # except: # officalaccount = "" # print officalaccount officalaccount = link_tracker[0]['link_id']['officialaccount'] if officalaccount: sign_info = self.exec_signature(url, officalaccount) print sign_info else: sign_info = {} base_url = env['ir.config_parameter'].get_param('web.base.url') info_url = "/web/image?model=link.tracker&id=" + str( link_tracker[0]['link_id'].id) + "&field=share_image" # 总点击量: if link_tracker[0]['link_id'].share_mood_1: share_mood_1 = link_tracker[0]['link_id'].share_mood_1 else: share_mood_1 = "" print share_mood_1 if link_tracker[0]['link_id'].share_mood_2: share_mood_2 = link_tracker[0]['link_id'].share_mood_2 else: share_mood_2 = "" print share_mood_2 if link_tracker[0]['link_id'].share_mood_3: share_mood_3 = link_tracker[0]['link_id'].share_mood_3 else: share_mood_3 = "" print share_mood_3 values.update({ 'desc': link_tracker[0]['link_id'].share_desc, 'title': link_tracker[0]['link_id'].title, 'share_mood_1': share_mood_1, 'share_mood_2': share_mood_2, 'share_mood_3': share_mood_3, 'imageurl': urlparse.urljoin(base_url, info_url), "signature": json.dumps(sign_info) }) return request.render(page, values) else: return request.website.render('website.404')
def handler_event(self, jsonStr, cr, uid): #content = jsonStr['Content'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] #AgentID=jsonStr['AgentID'] eventType = jsonStr['Event'] create_time = jsonStr['CreateTime'] key = fromUser + create_time msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() env = Environment(http.request.cr, SUPERUSER_ID, http.request.context) if msgvalue == None: logging.info(u"服务号ID" + toUser) cache.redis.set(key, key, 5000) if eventType == "click": #点击事件; eventkey = jsonStr['EventKey'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] return env['receive_message'].process_clickkey( eventkey, jsonStr) #return messageinfo.text_reply_xml(fromUser,toUser,int(time.time()),"Click") # elif eventType=="submit_membercard_user_info": #激活会员卡信息 # return messageinfo.text_reply_xml(fromUser,toUser,int(time.time()),"submit_membercard_user_info") elif eventType == "subscribe": return env['receive_message'].process_clickkey( "default", jsonStr) else: return "" pass
def handler_text(self, jsonStr, cr, context, component_appid, appid, component_sercret, wXBizMsgCrypt, nonce): dbname = cr.dbname uid = SUPERUSER_ID context = context.copy() #component_sercret="d4624c36b6795d1d99dcf0547af5443d" with api.Environment.manage(): with registry(dbname).cursor() as new_cr: env = Environment(new_cr, uid, context) content = unquote(jsonStr['Content'].decode('utf-8')) print content if content.startswith('QUERY_AUTH_CODE'): query_auth_code = content.replace('QUERY_AUTH_CODE:', '') key = component_appid + "ticket" ticket = cache.redis.get(key) publicsdk = public_sdk.public_sdk(component_appid, component_sercret) token = publicsdk.api_query_auth(query_auth_code, ticket) reply_content = query_auth_code + "_from_api" custom_manager.sendText_custommessage_access_token( jsonStr['FromUserName'], reply_content, "", token['authorization_info']['authorizer_access_token']) return key = component_appid + "ticket" ticket = cache.redis.get(key) publicsdk = public_sdk.public_sdk(component_appid, component_sercret) refresh_token_key = appid + "authorizer_refresh_token" refresh_token = cache.redis.get(refresh_token_key) api_authorizer_token = publicsdk.api_authorizer_token( ticket, appid, refresh_token) print "api_authorizer_token:" + str(api_authorizer_token) #custom_manager.sendText_custommessage_access_token(jsonStr['FromUserName'],"测试","",api_authorizer_token) return env['receive_message'].accept_message( 'wx.message_text', jsonStr)
def shareTimeline(self, **post): print post cr, uid, context = request.cr, request.uid, request.context env = Environment(cr, SUPERUSER_ID, context) id = post['id'] link_new = env['link.tracker'].sudo().search([('id', '=', id)]) if link_new: link_tracker = env['link.tracker.code'].search([('link_id', '=', link_new.id)]) if link_tracker: currenturl = request.httprequest.url base_url = env['ir.config_parameter'].get_param('web.base.url') # utms = {} # utms['redirect']=link_new.short_url # utms['code']=link_tracker.code # info_url = "/weixin/sharetimeline?"+urlencode(utms) # #currenturl=urlparse.urljoin(base_url, info_url) # currenturl='%s?%s' %(base_url,) parsed = urlparse.urlparse(currenturl) utms = {} utms['redirect'] = link_new.short_url utms['code'] = link_tracker.code print parsed.netloc print parsed.path redirected_url = '%s://%s%s?%s&%s#%s' % ( parsed.scheme, parsed.netloc, '/weixin/friendshare', urlencode(utms), parsed.query, parsed.fragment) print redirected_url _logger.info("redirected_url:" + redirected_url) return werkzeug.utils.redirect(redirected_url or '', 301)
def sharetimeline_real(self, **post): cr, uid, context = request.cr, request.uid, request.context env = Environment(cr, SUPERUSER_ID, context) parmsdata = request.params code = parmsdata['code'] link_tracker = env['link.tracker.code'].search([('code', '=', code)]) if link_tracker: sign_info = {} url = request.httprequest.url print url # try: # officalaccount = "" # link_tracker = env['link.tracker.code'].search([('code', '=', code)]) # if link_tracker: # # print officalaccount # except: # officalaccount = "" # print officalaccount officalaccount = link_tracker[0]['link_id']['officialaccount'] if officalaccount: sign_info = self.exec_signature(url, officalaccount) print sign_info else: sign_info = {} base_url = env['ir.config_parameter'].get_param('web.base.url') info_url = "/web/image?model=link.tracker&id=" + str( link_tracker[0]['link_id'].id) + "&field=share_image" if link_tracker[0]['link_id'].share_mood_1: share_mood_1 = link_tracker[0]['link_id'].share_mood_1 else: share_mood_1 = "" print share_mood_1 if link_tracker[0]['link_id'].share_mood_2: share_mood_2 = link_tracker[0]['link_id'].share_mood_2 else: share_mood_2 = "" print share_mood_2 if link_tracker[0]['link_id'].share_mood_3: share_mood_3 = link_tracker[0]['link_id'].share_mood_3 else: share_mood_3 = "" print share_mood_3 return env2.get_template("sharetimeline.html").render({ 'desc': link_tracker[0]['link_id'].share_desc, 'title': link_tracker[0]['link_id'].title, 'share_mood_1': share_mood_1, 'share_mood_2': share_mood_2, 'share_mood_3': share_mood_3, 'imageurl': urlparse.urljoin(base_url, info_url), "signature": json.dumps(sign_info) })
def get_custom_menu(self,cr,uid,context,code,official_account_id): print official_account_id env = Environment(cr,uid,context) root_domain = [('parent_id', '=', False),('officialaccount',"=",official_account_id),('officialaccount_menu_type','=',code)] menus = env['wx.officialaccount_menu'].search(root_domain,limit=3,order='sequence') menudata='''"button": [''' for menu_id in menus: #tmp_menu=env['wx.officialaccount_menu'].browse(menu_id) tmp_menu=menu_id print tmp_menu menudata=menudata+'''{"name":"'''+tmp_menu["wx_menu_name"]+'''",''' sub_domain=[('parent_id', '=', tmp_menu['id']),('officialaccount',"=",official_account_id),('officialaccount_menu_type','=',code)] sub_menu_ids =env['wx.officialaccount_menu'].search(sub_domain,limit=5,order='sequence') if len(sub_menu_ids)>0: menudata=menudata+'''"sub_button":[''' sub_menu_data="" for sub_menu_id in sub_menu_ids: sub_menu=sub_menu_id#env['wx.officialaccount_menu'].browse(sub_menu_id) sub_menu_data=sub_menu_data+'''{"name":"'''+sub_menu['wx_menu_name']+'''",''' if sub_menu["wx_menu_type"]=="click": sub_menu_data=sub_menu_data+'''"type":"click","key":"'''+sub_menu["wx_menu_url"]+'''"},''' elif sub_menu["wx_menu_type"]=="view": sub_menu_data=sub_menu_data+'''"type":"view","url":"'''+sub_menu["wx_menu_url"]+'''"},''' elif sub_menu["wx_menu_type"]=="scancode_push": sub_menu_data=sub_menu_data+'''"type":"scancode_push","key":"'''+sub_menu["wx_menu_url"]+'''","sub_button": [ ]},''' elif sub_menu["wx_menu_type"]=="scancode_waitmsg": sub_menu_data=sub_menu_data+'''"type":"scancode_waitmsg","key":"'''+sub_menu["wx_menu_url"]+'''","sub_button": [ ]},''' elif sub_menu["wx_menu_type"]=="pic_sysphoto": sub_menu_data=sub_menu_data+'''"type":"pic_sysphoto","key":"'''+sub_menu["wx_menu_url"]+'''","sub_button": [ ]},''' elif sub_menu["wx_menu_type"]=="pic_photo_or_album": sub_menu_data=sub_menu_data+'''"type":"pic_photo_or_album","key":"'''+sub_menu["wx_menu_url"]+'''","sub_button": [ ]},''' elif sub_menu["wx_menu_type"]=="pic_weixin": sub_menu_data=sub_menu_data+'''"type":"pic_weixin","key":"'''+sub_menu["wx_menu_url"]+'''","sub_button": [ ]},''' elif sub_menu["wx_menu_type"]=="location_select": sub_menu_data=sub_menu_data+'''"type":"location_select","key":"'''+sub_menu["wx_menu_url"]+'''","sub_button": [ ]},''' menudata=menudata+sub_menu_data[:-1]+"]}," else: if tmp_menu["wx_menu_type"]=="click": menudata=menudata+'''"type":"click","key":"'''+tmp_menu["wx_menu_url"]+'''"},''' elif tmp_menu["wx_menu_type"]=="view": menudata=menudata+'''"type":"view","url":"'''+tmp_menu["wx_menu_url"]+'''"},''' elif tmp_menu["wx_menu_type"]=="scancode_push": menudata=menudata+'''"type":"scancode_push","key":"'''+tmp_menu["wx_menu_url"]+'''",},''' elif tmp_menu["wx_menu_type"]=="scancode_waitmsg": menudata=menudata+'''"type":"scancode_waitmsg","key":"'''+tmp_menu["wx_menu_url"]+'''",},''' elif tmp_menu["wx_menu_type"]=="pic_sysphoto": menudata=menudata+'''"type":"pic_sysphoto","key":"'''+tmp_menu["wx_menu_url"]+'''",},''' elif tmp_menu["wx_menu_type"]=="pic_photo_or_album": menudata=menudata+'''"type":"pic_photo_or_album","key":"'''+tmp_menu["wx_menu_url"]+'''",},''' elif tmp_menu["wx_menu_type"]=="pic_weixin": menudata=menudata+'''"type":"pic_weixin","key":"'''+tmp_menu["wx_menu_url"]+'''",},''' elif tmp_menu["wx_menu_type"]=="location_select": menudata=menudata+'''"type":"location_select","key":"'''+tmp_menu["wx_menu_url"]+'''",},''' if menudata.endswith(","): menudata=menudata[:-1]+"]" else: menudata=menudata+"]" _logger.debug(menudata) return menudata
def create_voice_record(self, cr, uid, vals, context): fromUser = vals['FromUserName'] toUser = vals['ToUserName'] recognitionInfo = "" if 'Recognition' in vals: recognitionInfo = vals["Recognition"] format_value = vals['Format'] mediaId = vals['MediaId'] voicedata = "" env = Environment(cr, uid, context) from yuancloud.addons.wx_platform.models import wx_customer as wx_customer wx_customer_4subscribe = wx_customer.wx_customer_4subscribe( cr, uid, context) values = {} values['openid'] = fromUser values['officialaccount_id'] = toUser wx_customerinfo = wx_customer_4subscribe.create_wx_customer(values) wxOfficeAccountInfo = env['wx.officialaccount'].getofficialaccount( toUser) mediaManager = media_manager.media_manager( wxOfficeAccountInfo['wx_appid'], wxOfficeAccountInfo['wx_appsecret']) # 判断字符串为空 audio_format, media_info = mediaManager.get_media(mediaId) # print audio_format # filename = fromUser + "." + format_value # new_head_url = os.path.join(os.getcwd(), filename) # print new_head_url # f = open(new_head_url, "w+b") # f.write(media_info) # f.close() createtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime((int)(vals['CreateTime']))) print createtime msgid = vals['MsgId'] data = {} data.update({ 'message_msgid': msgid, 'message_event': 'receive', 'official_username': wx_customerinfo.id, 'message_format': format_value, 'message_mediaId': mediaId, 'message_recognition': recognitionInfo, 'message_voicedata': base64.b64encode(media_info), 'createTime': createtime, 'message_status': 'use_sucess', 'officialaccount': wxOfficeAccountInfo['id'] }) try: create_result = env['wx.voice_message_record'].create(data) _logger.info(create_result) except Exception as e: _logger.error('插入语音消息失败:' + str(e)) print e pass
def handler_image(self, jsonStr, cr, uid): messageinfo = reply_information.reply_information() imageId = jsonStr["MediaId"] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] env = Environment(cr, uid, http.request.context) key = jsonStr['MsgId'] msgvalue = cache.redis.get(key) if msgvalue == None: cache.redis.set(key, key, 1000) # env['ycloud.wx.message'].create_message('ycloud.wx.message_image', jsonStr) env['receive_message'].accept_message('wx.image_message_record', jsonStr) return "" return ""
def handler_shortvideo(self, jsonStr, cr, uid): messageinfo = reply_information.reply_information() fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] thumbMediaId = jsonStr["ThumbMediaId"] mediaId = jsonStr["MediaId"] env = Environment(cr, uid, http.request.context) key = jsonStr['MsgId'] msgvalue = cache.redis.get(key) if msgvalue == None: cache.redis.set(key, key, 1000) env['receive_message'].accept_message('wx.video_message_record', jsonStr) return "" return ""
def weixin_notify(self, **post): """ weixin Notify. """ _logger.info('Beginning weixin notify form_feedback with post data %s', pprint.pformat(post)) # debug postdata = request.httprequest.data print postdata if self.weixin_validate_data(postdata): # werkzeug.utils.redirect("/shop/payment/validate") json = {} for el in etree.fromstring(postdata): json[el.tag] = el.text transaction_id = json['transaction_id'] openid = json['openid'] is_subscribe = json['is_subscribe'] appid = json['appid'] print appid out_trade_no = json['out_trade_no'] msgvalue = cache.redis.get(transaction_id) if msgvalue == None: cache.redis.set(transaction_id, transaction_id, 50000) if is_subscribe.lower() == "y": print '准备发送支付成功信息' message_key = "merchant_order" context = http.request.context context.update({"openid": openid}) env = Environment(request.cr, SUPERUSER_ID, context) officialaccount = request.env['payment.acquirer'].search([ ('weixin_officialaccount.wx_appid', '=', appid) ])[0] oe_order = env['sale.order'].search([('name', '=', out_trade_no)])[0] product_model = env['ir.model'].search([('model', '=', 'sale.order')])[0] model_instances = [] model_instance = {} model_instance.update({ "id": product_model['id'], "model_value": oe_order }) model_instances.append(model_instance) env['wx.message.send_event'].sendmessage_TriggeredbyCommand( message_key, model_instances, officialaccount) pass return 'success' else: return "" else: return ''
def test_tour(self): self.phantom_js( "/", "yuancloud.__DEBUG__.services['web.Tour'].run('website_crm_tour', 'test')", "yuancloud.__DEBUG__.services['web.Tour'].tours.website_crm_tour") # need environment using the test cursor as it's not committed cr = self.registry.cursor() assert cr is self.registry.test_cr env = Environment(cr, self.uid, {}) record = env['crm.lead'].search([('description', '=', '### TOUR DATA ###')]) assert len(record) == 1 assert record.contact_name == 'John Smith' assert record.email_from == '*****@*****.**' assert record.partner_name == 'YuanCloud S.A.'
def handler_link(self, jsonStr, cr, uid): messageinfo = reply_information.reply_information() fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] linktitle = jsonStr["Title"] linkdescription = jsonStr["Description"] linkurl = jsonStr["Url"] env = Environment(cr, uid, http.request.context) key = jsonStr['MsgId'] msgvalue = cache.redis.get(key) if msgvalue == None: cache.redis.set(key, key, 1000) env['receive_message'].accept_message('wx.link_message_record', jsonStr) return "" return ""
def handler_voice(self, jsonStr, cr, uid): messageinfo = reply_information.reply_information() fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] recognitionInfo = "" if 'Recognition' in jsonStr: recognitionInfo = jsonStr["Recognition"] env = Environment(cr, uid, http.request.context) key = jsonStr['MsgId'] msgvalue = cache.redis.get(key) if msgvalue == None: cache.redis.set(key, key, 1000) env['receive_message'].accept_message('wx.voice_message_record', jsonStr) return "" return ""
def handler_text(self, jsonStr, wXBizMsgCrypt): content = jsonStr['Content'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] AgentID = jsonStr['AgentID'] msgId = jsonStr['MsgId'] key = msgId msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() if msgvalue == None: cache.redis.set(key, key, 5000) print content env = Environment(http.request.cr, SUPERUSER_ID, http.request.context) return env['receive_message'].accept_qy_message( 'wx.message_text', jsonStr, AgentID) else: return ""
def handler_text(self, jsonStr, cr, uid): fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] create_time = jsonStr['CreateTime'] msgId = jsonStr['MsgId'] key = msgId msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() if msgvalue == None: _logger.debug(u"服务号ID" + toUser) context = http.request.context context.update({"openid": fromUser}) env = Environment(cr, uid, context) cache.redis.set(key, key, 5000) return env['receive_message'].accept_message( 'wx.message_text', jsonStr) else: return ""
def handler_location(self, jsonStr, cr, uid): messageinfo = reply_information.reply_information() fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] locationX = jsonStr["Location_X"] locationY = jsonStr["Location_Y"] scale = jsonStr["Scale"] label = jsonStr["Label"] key = jsonStr['MsgId'] locationInfo = u"你发送的是位置,纬度为:" + locationX + u";经度为:" + locationY + u";缩放级别为:" + scale + u";位置为:" + label env = Environment(cr, uid, http.request.context) msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() if msgvalue == None: cache.redis.set(key, key, 1000) env['receive_message'].accept_message('wx.location_message_record', jsonStr) return "" return ""
def scanbarcode(eventKey, cr, uid, context, fromUser, wxOfficeAccountInfo): dbname = cr.dbname uid = uid context = context.copy() with api.Environment.manage(): with registry(dbname).cursor() as new_cr: context.update({"openid": fromUser}) new_env = Environment(new_cr, uid, context) # scanvalues={} # scanvalues['scene']="subscribe" # scanvalues['scancode_key']=eventKey # qr_management = new_env['ycloud.qr.management'].search(['|', ('scene_str', '=', eventKey), ('scene_id', '=', int(eventKey) if eventKey.isdigit() else -1)]) # if len(qr_management) > 0: # scanvalues['scene']=qr_management[0]['qr_scene'] # print scanvalues['scene'] # scanvalues['openid']=fromUser # scanvalues['officialaccount_appid']=wxOfficeAccountInfo['wx_appid'] # scancode_help=scancode.scancode(new_cr,uid,context) # scancode_help.create_scancode(scanvalues) # qr_key=qr_management[0]['qr_key'] # qr_models = qr_management[0]['qr_models'] qr_key = eventKey qr_models_values = [] # for qr_model in qr_models: # model_info=qr_model['model_id']['model'] # model_id_value=qr_model['model_id_value'] # model_column=qr_model['model_column']['name'] # orderinfo=new_env[model_info].search([(model_column,'=',model_id_value)])[0] # value={} # value.update({ # 'id':qr_model['model_id']['id'], # 'model_value':orderinfo # }) # qr_models_values.append(value) #currentContext={} if len(qr_models_values) == 0: new_env['receive_message'].process_clickkey( qr_key, jsonStr) else: new_env[ 'wx.message.send_event'].sendmessage_TriggeredbyCommand( qr_key, qr_models_values)
def processmessage(self, openid, cr, uid, context, content, wxOfficeAccountInfo): dbname = cr.dbname uid = uid context = context.copy() with api.Environment.manage(): with registry(dbname).cursor() as new_cr: context.update({"openid": openid}) env = Environment(new_cr, uid, context) wxOfficeAccountInfo = env['wx.officialaccount'].search([ ('id', '=', wxOfficeAccountInfo.id) ]) #currentContext={} model_instances = [] model_instance = {} model_instance.update({"id": "", "model_value": ""}) model_instances.append(model_instance) env['wx.message.send_event'].sendmessage_TriggeredbyCommand( content, model_instances, wxOfficeAccountInfo)
def test_tour(self): self.phantom_js( "/", "yuancloud.__DEBUG__.services['web.Tour'].run('website_hr_recruitment_tour', 'test')", "yuancloud.__DEBUG__.services['web.Tour'].tours.website_hr_recruitment_tour" ) # get test cursor to read from same transaction browser is writing to cr = self.registry.cursor() assert cr == self.registry.test_cr env = Environment(cr, self.uid, {}) record = env['hr.applicant'].search([ ('description', '=', '### HR RECRUITMENT TEST DATA ###') ]) assert len(record) == 1 assert record.partner_name == "John Smith" assert record.email_from == "*****@*****.**" assert record.partner_phone == '118.218'
def create_location_record(self, cr, uid, jsonStr, context): fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] locationX = jsonStr["Location_X"] locationY = jsonStr["Location_Y"] scale = jsonStr["Scale"] label = jsonStr["Label"] createTime = (int)(jsonStr['CreateTime']) print createTime value = time.localtime(createTime) createtime = time.strftime("%Y-%m-%d %H:%M:%S", value) print createtime msgid = jsonStr['MsgId'] env = Environment(cr, uid, context) from yuancloud.addons.wx_platform.models import wx_customer as wx_customer wx_customer_4subscribe = wx_customer.wx_customer_4subscribe( cr, uid, context) values = {} values['openid'] = fromUser values['officialaccount_id'] = toUser wx_customerinfo = wx_customer_4subscribe.create_wx_customer(values) wxOfficeAccountInfo = env['wx.officialaccount'].getofficialaccount( toUser) data = {} data.update({ 'message_msgid': msgid, 'message_event': 'receive', 'official_username': wx_customerinfo.id, 'message_locationX': locationX, 'message_locationY': locationY, 'message_scale': scale, 'message_label': label, 'createTime': createtime, 'officialaccount': wxOfficeAccountInfo['id'], 'message_status': 'use_sucess' }) try: create_result = env['wx.location_message_record'].create(data) _logger.info(create_result) except Exception as e: _logger.error('插入位置消息失败:' + str(e)) print e
def create_image_record(self, cr, uid, vals, context): imageId = vals["MediaId"] fromUser = vals['FromUserName'] toUser = vals['ToUserName'] msgid = vals['MsgId'] picurl = vals['PicUrl'] createTime = (int)(vals['CreateTime']) print createTime value = time.localtime(createTime) createtime = time.strftime("%Y-%m-%d %H:%M:%S", value) print createtime imagedata = urllib2.urlopen(picurl).read() imagedata_encode = base64.b64encode(imagedata) env = Environment(cr, uid, context) # from yuancloud.addons.ycloud_wx import ycloud_wx_customer as wx_customer # wx_customer_4subscribe = wx_customer.wx_customer_4subscribe(cr, uid, context) # values = {} # values['openid'] = fromUser # values['officialaccount_id'] = toUser # wx_customerinfo = wx_customer_4subscribe.create_wx_customer(values) wxOfficeAccountInfo = env['wx.officialaccount'].getofficialaccount( toUser) data = {} data.update({ 'message_msgid': msgid, 'message_event': 'receive', 'official_username': "", #wx_customerinfo.id, 'message_picurl': picurl, 'message_mediaId': imageId, 'message_imagedata': imagedata_encode, 'createTime': createtime, 'message_status': 'use_sucess', 'officialaccount': wxOfficeAccountInfo['id'] }) try: create_result = env['wx.image_message_record'].create(data) _logger.info(create_result) except Exception as e: _logger.error('插入图片消息失败:' + str(e)) print e return ""
def create_link_record(self, cr, uid, vals, context): fromUser = vals['FromUserName'] toUser = vals['ToUserName'] linktitle = vals["Title"] linkdescription = vals["Description"] linkurl = vals["Url"] createTime = (int)(vals['CreateTime']) print createTime value = time.localtime(createTime) createtime = time.strftime("%Y-%m-%d %H:%M:%S", value) print createtime msgid = vals['MsgId'] env = Environment(cr, uid, context) from yuancloud.addons.wx_platform.models import wx_customer as wx_customer wx_customer_4subscribe = wx_customer.wx_customer_4subscribe( cr, uid, context) values = {} values['openid'] = fromUser values['officialaccount_id'] = toUser wx_customerinfo = wx_customer_4subscribe.create_wx_customer(values) wxOfficeAccountInfo = env['wx.officialaccount'].getofficialaccount( toUser) data = {} data.update({ 'message_msgid': msgid, 'message_event': 'receive', 'official_username': wx_customerinfo.id, 'message_title': linktitle, 'message_description': linkdescription, 'message_url': linkurl, 'createTime': createtime, 'officialaccount': wxOfficeAccountInfo['id'], 'message_status': 'use_sucess' }) try: create_result = env['wx.link_message_record'].create(data) _logger.info(create_result) except Exception as e: _logger.error('插入链接消息失败:' + str(e)) print e pass
def handler_text(self, jsonStr, cr, uid, wXBizMsgCrypt): content = jsonStr['Content'] fromUser = jsonStr['FromUserName'] toUser = jsonStr['ToUserName'] AgentID = jsonStr['AgentID'] msgId = jsonStr['MsgId'] key = msgId # mc=wx_public_sdk.getClient() msgvalue = cache.redis.get(key) messageinfo = reply_information.reply_information() if msgvalue == None: cache.redis.set(key, key, 5000) print content env = Environment(cr, uid, http.request.context) # content=u"测试中心,测试教师" # result= messageinfo.text_reply_xml(fromUser, toUser, int(time.time()), content) # return result return env['receive_message'].accept_qy_message( 'wx.message_text', jsonStr, AgentID) else: return ""
def getinfo(self, **post): print post cr, uid, context = request.cr, request.uid, request.context env = Environment(cr, SUPERUSER_ID, context) parmsdata = request.params code = parmsdata['code'] link_tracker = env['link.tracker.code'].search([('code', '=', code)]) if link_tracker: result = {} base_url = env['ir.config_parameter'].get_param('web.base.url') info_url = "/web/image?model=link.tracker&id=" + str(link_tracker[0]['link_id'].id) + "&field=share_image" result.update({ 'desc': link_tracker[0]['link_id'].share_desc, 'title': link_tracker[0]['link_id'].title, 'imageurl': urlparse.urljoin(base_url, info_url), 'success': True }) print result _logger.info(json.dumps(result)) return json.dumps(result) else: return {}
def authorize_complete(self, **kw): env = Environment(request.cr, SUPERUSER_ID, request.context) auth_code = kw['auth_code'] component_appid = kw['key'] #component_appid="wx8a79b1dd516ef8d7" #component_sercret="d4624c36b6795d1d99dcf0547af5443d" third_platform = env['wx.third_platform'].search([ ('auth_component_appid', '=', component_appid), ('auth_component_platfromtype', '=', 'openplatform') ]) if len(third_platform) == 0: component_sercret = "d4624c36b6795d1d99dcf0547af5443d" else: component_sercret = third_platform[0]['auth_component_appsecret'] key = component_appid + "ticket" ticket = cache.redis.get(key) publicsdk = public_sdk.public_sdk(component_appid, component_sercret) token = publicsdk.api_query_auth(auth_code, ticket) print token authorizer_appid = token['authorization_info']['authorizer_appid'] authorizer_access_token = token['authorization_info'][ 'authorizer_access_token'] authorizer_refresh_token = token['authorization_info'][ 'authorizer_refresh_token'] cache.redis.set(authorizer_appid + "authorizer_access_token", authorizer_access_token, 7200) print sys.maxint cache.redis.set(authorizer_appid + "authorizer_refresh_token", authorizer_refresh_token, 9000000) officialaccount = env['wx.officialaccount'].search([ ('wx_appid', '=', authorizer_appid), ('is_auth_officialaccount', '=', True), ('auth_component', '=', third_platform[0].id) ]) #更新刷新token if officialaccount: officialaccount[0][ 'authorizer_refresh_token'] = authorizer_refresh_token return 'sucess'
def display_store_info(self,**kw): print kw store_id=kw['key'] env_new = Environment(http.request.cr, SUPERUSER_ID, http.request.context) store_info=env_new['o2o.store'].search([('id','=',store_id)]) name=store_info.name address=store_info.address contact=store_info.contact if not contact: contact='' phone=store_info.phone if not phone: phone='' mobile=store_info.mobile if not mobile: mobile='' simple_info=store_info.simple_info if not simple_info: simple_info='暂无简介' recommend=store_info.recommend if not recommend: recommend='' category=store_info.category.name if not category: category='暂未分类' category_line=store_info.category_line.name if not category_line: category_line='' return env_jinjia.get_template("display_store.html").render({ "name": name, "address": address, "contact": contact, "phone":phone, "mobile": mobile, "simple_info": simple_info, "recommend":recommend , "category": category, "category_line": category_line, })
def gen_sign(self, **post): print post cr, uid, context = request.cr, request.uid, request.context env = Environment(cr, SUPERUSER_ID, context) parmsdata = request.params code = parmsdata['code'] url = parmsdata['url'] try: officalaccount = "" link_tracker = env['link.tracker.code'].search([('code', '=', code)]) if link_tracker: officalaccount = link_tracker[0]['link_id']['officialaccount'] # officalaccount = env['wx.officialaccount'].search(['|',('wx_appid', '=', app_id),('id', '=', int(app_id) if app_id.isdigit() else -1)])[0] print officalaccount except: officalaccount = "" print officalaccount if officalaccount: sign_info = self.exec_signature(url, officalaccount) print sign_info return json.dumps(sign_info) else: return {}