微信公共平台第三方接口python实现,无法返回数据给客户端

def weixin(request):
	try: # 微信接口认证 使用GET方式
		if request.method == 'GET':
			token = 'air2you'
			tmpArr =[token, request.GET['timestamp'], request.GET['nonce']]
			tmpArr.sort()
			tmpArr.sort()
			tmpStr = ''.join(tmpArr)
			code = hashlib.sha1(tmpStr).hexdigest()
			if code  == request.GET['signature']:
				return render_to_response('air/weixin.html',{'echostr':request.GET['echostr']})		
			else: 
				return render_to_response('air/weixin.html',{'echostr':''})
		# 微信接口通讯 返回用户需要数据
		elif request.method == 'POST':
			xml = et.fromstring(request.raw_post_data)
			_to = xml.find('FromUserName').text
			_from = xml.find('ToUserName').text
			_content = 'welcome!'
			_type = 'text'
			return render_to_response('air/weixin.xml',{'_to':_to, '_from': _from, '_time' : int(time.time()), '_type': _type, '_content' : _content}, mimetype='application/xml')
	except Exception, e:
		return render_to_response('air/weixin.html',{'echostr':''})
#weixin.xml
<xml>
<ToUserName><![CDATA[{{ _to }}]]></ToUserName>
<FromUserName><![CDATA[{{ _from }}]]></FromUserName>
<CreateTime>{{ _time }}</CreateTime>
<MsgType><![CDATA[{{ _type }}]]></MsgType>
<Content><![CDATA[{{ _content }}]]></Content>
<FuncFlag>0</FuncFlag>
</xml>
阅读 15.3k
5 个回答

先给你一个我自己实现的示例,你先看看,微信公众平台只能在生产环境调试,这点很不好。如果还不行,可以联系我,微博:唐僧之妈

#! /usr/bin/env python
# coding=utf-8
__author__ = 'jszhou'
from bottle import *
import hashlib
import xml.etree.ElementTree as ET
import urllib2
# import requests
import json
 
 
@get("/")
def checkSignature():
    token = "****"
    signature = request.GET.get('signature', None)  # 拼写不对害死人那,把signature写成singnature,直接导致怎么也认证不成功
    timestamp = request.GET.get('timestamp', None)
    nonce = request.GET.get('nonce', None)
    echostr = request.GET.get('echostr', None)
    tmpList = [token, timestamp, nonce]
    tmpList.sort()
    tmpstr = "%s%s%s" % tuple(tmpList)
    hashstr = hashlib.sha1(tmpstr).hexdigest()
    # return "echostr: %s" % echostr
    if hashstr == signature:
        return echostr
    else:
        return None
 
 
def parse_msg():
    recvmsg = request.body.read()
    root = ET.fromstring(recvmsg)
    msg = {}
    for child in root:
        msg[child.tag] = child.text
    return msg
 
 
def query_movie_info():
    movieurlbase = "http://api.douban.com/v2/movie/subject/"
    DOUBAN_APIKEY = "******"
    id = parse_msg()
    url = '%s%s?apikey=%s' % (movieurlbase, id["Content"], DOUBAN_APIKEY)
    # header = {'Referer': url, 'Content-Type': 'application/json'}
    # resp = requests.get(url=url, headers=header)
    resp = urllib2.urlopen(url)
    movie = json.loads(resp.read())
    info = movie['title'] + ': ' + ''.join(movie['summary'])
    return info
 
 
@post("/")
def response_msg():
    # 拿到Post过来的数据
    # 分析数据(拿到FromUserName、ToUserName、CreateTime、MsgType和content)
    # 构造回复信息(将其中content变为返回给用户的信息)
    msg = parse_msg()
    textTpl = """<xml>
             <ToUserName><![CDATA[%s]]></ToUserName>
             <FromUserName><![CDATA[%s]]></FromUserName>
             <CreateTime>%s</CreateTime>
             <MsgType><![CDATA[%s]]></MsgType>
             <Content><![CDATA[%s]]></Content>
             <FuncFlag>0</FuncFlag>
             </xml>"""
    Content = query_movie_info()
 
    # if Content is not False:
    echostr = textTpl % (msg['FromUserName'], msg['ToUserName'], str(int(time.time())), msg['MsgType'], Content)
    return echostr
    # else:
    #     echostr = textTpl % (msg['FromUserName'], msg['ToUserName'], str(int(time.time())), msg['MsgType'], "Content")
    #     return echostr
 
if __name__ == "__main__":
    # Interactive mode
    debug(True)
    run(host='127.0.0.1', port=8888, reloader=True)
else:
    # Mod WSGI launch
    import sae
    debug(True)
    os.chdir(os.path.dirname(__file__))
    app = default_app()
    application = sae.create_wsgi_app(app)

我现在自己的微信平台没有通过认证,暂时看不了API是否发生了改变,但是我记得公众平台返回XML内容就可以了,是否是模板的原因影响了结果?

你可以直接把xml返回出来就可以了

添加一个response header试试: content_type = 'application/xml'

我用了一个开源的公众平台的框架 werobot,在github搜索就OK了,可以自己拿来改改用。看看他的代码,你大概就明白了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题