微信公众号开发

微信公众号开发——获取用户的openid

阅读微信开放文档可知,如果只要获取用户openid,建立数据库存储用户信息,实现下图流程即可,流程
前端引导用户点击链接:https://open.weixin.qq.com/connect/oauth2/authorize?appid=填写你的appid&redirect_uri=填写你的回调地址,即获取code之后要到哪里&response_type=code&scope=snsapi_base&state=1#wechat_redirect
后端代码如下:下面的代码填写公众号appid和secret即可使用

# -*- encoding:utf-8-*-
import os
import sys
import json
import web
import requests
# 1 第一步:用户同意授权,获取code
# 2 第二步:通过code换取网页授权access_token
# 3 第三步:刷新access_token(如果需要)
# 4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
# 5 附:检验授权凭证(access_token)是否有效
render=web.template.render("templates") #这是前端页面,即最终用户看到的页面,templates是html所在文件夹,如不需要可删去此行

class Getopenid(object):                               
    def GET(self):
        
        data=web.input()
        if len(data)==0:
            return "请重新点击链接"                            
               
        self.appid = ''  # 填写你的公众号appid
        self.secret = ''  # 填写你的公众号secret    
        code=data.code #获取微信服务器返回的code
        #https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code,这是微信开放文档中说明的以此获取用户信息
        get_access_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code' % (
            self.appid, self.secret, code)
        result = requests.get(get_access_url)
        result = result.json()      
        openid = result["openid"] #到这里就得到了openid
        return render.reg(openid) #将openid返回到前端,reg是html文件名称,openid是返回参数,如不需要可删去此行

接着上一篇微信开发公众号博客到目前为止,实现的功能是:测试号和后端服务器绑定,获取用户openid返回前端
整个逻辑框架如下图:
框架
info文件下:
info
其中_init_.py是空白文件,具体了解python语法
templates文件下:
reg
其中reg.html就是上面的代码所指的html文件,具体可以了解web.py文档中的render。 https://webpy.org/docs/0.3/templetor

main.py代码:

# -*- coding: utf-8 -*-
# filename: main.py
import web
import json
import time
import requests
from handle import Handle   #这些是根据我的文件放置import,具体改成你的
from handle import test_send
import access_token
from handle import Handle
from test.test import test
from info.getOpenid import Getopenid
from mysql.insertMysql import Mysql
from altermysql.mysql import AlterMysql
from alterinfo.getopenid import getopenid
from InfoAlterGetOpenid.getOpenid import Getopenid2

urls = (
    '/wx', 'Handle',
    '/test', 'test_send',
    '/myweb/info','Getopenid',  #主要是这里,引导用户点击完链接获取code之后,我的回调地址是回到这里,所以我填写的是http://e441d4bf.ngrok.io/myweb/info
    '/myweb/test','test',
    '/myweb/mysql','Mysql',
    '/myweb/altermysql','AlterMysql',
    '/myweb/alteropenid','getopenid',
    '/myweb/InfoAlterGetOpenid','Getopenid'
)

if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()

到这里就完成了图示的①②③④⑤个步骤了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值