flask 开发微信公众号 自定义菜单的问题

# -*- coding:utf-8 -*-
from flask import Flask, make_response,request
import hashlib
import xmltodict
import time
import json
import requests
from urllib import parse
from urllib import request as re
import urllib
from bs4 import BeautifulSoup

WECHAT_APPID = "wxb4cd05a73650cfb3"
WECHAT_APPSECRET = "360abbb5257bc169b1e13e0dc54dbe1a"
WECHAT_TOKEN = "flaskss"
xml_rep = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"

class AccessToken(object):
    access_token = {
        "access_token":"",
        "update_time":time.time(),
        "expires_in":7200
    }

    @classmethod
    def get_access_token(cls):
        if not cls.access_token.get('access_token') or (time.time() - cls.access_token.get('update_time')>cls.access_token.get('expires_in')):
            url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (WECHAT_APPID, WECHAT_APPSECRET)
            response = re.urlopen(url).read()
            resp_json = json.loads(response)
            if 'errcode' in resp_json:
                raise Exception(resp_json.get('errmsg'))
            else:
                cls.access_token['access_token'] = resp_json.get('access_token')
                cls.access_token['expires_in'] = resp_json.get('expires_in')
                cls.access_token['update_time'] = time.time()
                return cls.access_token.get('access_token')
        else:
            return cls.access_token.get('access_token')


class Menu(object):
    def create(self,postData):
            p = json.dumps(postData,ensure_ascii=False)
            postUrl = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s' % AccessToken.get_access_token()
            req = requests.post(postUrl,p.encode('utf-8'))
            print(req.text)


def  getMenu():
    postJson = {
        "button": [
            {
                "name": "公共查询",
                "sub_button": [
                    {
                        "type": "click",
                        "name": "天气查询",
                        "key": "tianQi"
                    }]
            }]
    }

    return postJson

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def wechat():
    args = request.args
    signature = args.get('signature')
    timestamp = args.get('timestamp')
    nonce = args.get('nonce')
    echostr = args.get('echostr')
    temp = [WECHAT_TOKEN, timestamp, nonce]
    temp.sort()

    temp = "".join(temp)

    sig = hashlib.sha1(temp.encode("utf8")).hexdigest()

    if sig == signature:
        if request.method == "GET":
            return echostr
        else:
            resp_data = request.data
            resp_dict = xmltodict.parse(resp_data).get('xml')
            if 'text' == resp_dict.get('MsgType'):
                if resp_dict.get('Content')  == '天气':
                    u = 'https://www.tianqi.com/yuhang/'
                    resp = requests.get(u)
                    bs = BeautifulSoup(resp.content,'lxml').find_all('dd',class_='weather')
                    b = BeautifulSoup(str(bs),'lxml').find('p',class_='now').find('b').get_text()
                    w = BeautifulSoup(str(bs),'lxml').find('span').find('b').get_text()
                    wstr = b+'℃'+'     '+w
                    response = make_response(xml_rep % (
                    resp_dict.get('FromUserName'), resp_dict.get('ToUserName'), str(int(time.time())),
                    wstr))
                    response.content_type = 'application/xml'
                    return response
                elif  resp_dict.get('Content')  == '笑话':
                    pass
                else:
                    response = make_response(xml_rep % (resp_dict.get('FromUserName'), resp_dict.get('ToUserName'), str(int(time.time())),
                    resp_dict.get('Content')))
                    response.content_type = 'application/xml'
                return response
            else:
                response = make_response(xml_rep % (resp_dict.get('FromUserName'), resp_dict.get('ToUserName'), str(int(time.time())),resp_dict.get('Content') ))
                response.content_type = 'application/xml'
                return response
    else:
            return 'errno', 403
if __name__ == '__main__':
    pData = getMenu()
    m = Menu()
    m.create(pData)
    app.run(port=80,host='0.0.0.0')

 

展开阅读全文

没有更多推荐了,返回首页