Python实现微信公众平台自定义菜单实例

时间:2021-07-07 16:15:03

首先先获取access_token,并保存与全局之中

?
1
2
3
4
5
6
7
def token(requset):
  url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (
  Config.AppID, Config.AppSecret)
  result = urllib2.urlopen(url).read()
  Config.access_token = json.loads(result).get('access_token')
  print 'access_token===%s' % Config.access_token
  return HttpResponse(result)

利用上面获得的access_token,创建自定义表单

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def createMenu(request):
  url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s" % Config.access_token
  data = {
   "button":[
   {
      "name":"看美图",
      "sub_button":[
      {
        "type":"click",
        "name":"美图",
        "key":"meitu"
      },
      {
        "type":"view",
        "name":"精选",
        "url":"http://m.zzvips.com/youxi/"
      },
  {
        "type":"view",
        "name":"回顾",
        "url":"http://m.zzvips.com/qq/"
      },
  {
        "type":"view",
        "name":"美图app",
        "url":"http://m.zzvips.com/zhanzhang/"
      }]
 },
 {
      "name":"看案例",
      "sub_button":[
      {
        "type":"click",
        "name":"全部风格",
        "key":"style"
      },
      {
        "type":"click",
        "name":"全部户型",
        "key":"houseType"
      },
  {
        "type":"click",
        "name":"全部面积",
        "key":"area"
      },
  {
        "type":"view",
        "name":"更多案例",
        "url":"http://m.zzvips.com/projects"
      }]
 },
 {
      "type":"view",
      "name":"设计申请",
      "url":"http://m.zzvips.com/news/"
 
 }
 
 ]
}
  #data = json.loads(data)
  #data = urllib.urlencode(data)
  req = urllib2.Request(url)
  req.add_header('Content-Type', 'application/json')
  req.add_header('encoding', 'utf-8')
  response = urllib2.urlopen(req, json.dumps(data,ensure_ascii=False))
  result = response.read()
  return HttpResponse(result)