微信公众号中网页授权并获取已关注用户的nickname以及乱码问题的解决

首先查看微信官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
大致分三步走:
1.第一步:用户同意授权,获取code。
访问:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
其中所对应的参数含义可以查看官方文档,其中redirect_uri为授权后重定向的网址, 要用 urlEncode 对链接进行处理,其必须在测试公众号或者公众号的网页授权获取用户基本信息选项中添加进去,只用填写域名即可不需要写https://scope参数有两个snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。就可获取code的值

2.第二步:通过code换取网页授权access_token。
访问:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code。返回的json数据中包含open_id和access_token

3.第三步:拉取用户信息(需scope为 snsapi_userinfo)
访问:http:GET(请使用https协议) https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
返回的json数据中包含nickname,此时你会发现乱码现象,解决办法不写&lang=zh_CN或者改成&lang=zh_CN.UTF8,此时发现nickname还是乱码,原因是由于微信那边采用的是“ISO-8859-1”编码造成的,解决办法先采用encode(“ISO-8859-1”)方法来编码,然后decode(‘utf8’)方法来解码即可解决

import json
import urllib

import chardet
import requests

APP_ID = "wx7b10b0c5448d080b"
APP_SECRET = "4f57dcf9e1f866971f30931420b70955"
CODE = "061C75w11W7GaV1nNmz11KN7w11C75wr"

def wechat():
    # 获取access_token
    # url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" %(APP_ID,APP_SECRET)

    # response = requests.get(url)
    # json_str = response.text
    # resp_dict = json.loads(json_str)
    # if "errcode" in resp_dict:
        # return HttpResponse("获取access_token失败")
        #print("获取access_token失败")
    # access_token1 = resp_dict.get("access_token")
    # print(access_token1)

    # 获取二维码
    # url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=34_cCQoqExSgZAp2Gx6qnPqle9IA2y0qMUfUMVUFi1aGpfuc5aTJ3CN-X_fJqjJqUDex4phuh3q_pz9zISXRhw2-jFpZI7o3jUITbGGn253utdiGsMfnnGR_VfaM2etA-BYHeuaTT7kLwPwVoXMWXHfACALMW"
    #  # POST参数
    # data = {
    #     "action_name": "QR_LIMIT_SCENE",
    #     "action_info": {
    #         "scene": {
    #             "scene_id": 1 #二维码的场景值
    #
    #         }
    #     }
    # }
    # # request = requests.post(url, json=data)
    # request = requests.post(url, data=json.dumps(data))
    #
    # QR_json_str = request.text
    # QR_dict_data = json.loads(QR_json_str)
    # ticket = QR_dict_data.get("ticket")
    # print(ticket)

    # 1.用户同意授权,获取code
    url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7b10b0c5448d080b&redirect_uri=https%3A//www.baidu.com&response_type=code&scope=snsapi_userinfo#wechat_redirect"
    # REDIRECT_URI = "https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60"
    # REDIRECT_URI = urllib.parse.unquote(REDIRECT_URI,encoding='utf-8', errors='replace')
    # urllib.parse.quote(REDIRECT_URI, safe='/', encoding=None, errors=None)
    REDIRECT_URI = "https://baidu.com"
    REDIRECT_URI = urllib.parse.quote(REDIRECT_URI, safe='/', encoding=None, errors=None)
    print(REDIRECT_URI)
    # https://www.baidu.com/?code=0212tnUa0zp0mA17xgUa0pzqUa02tnUp&state=

    # 2.通过code换取网页授权access_token
    url = " https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code" %(APP_ID,APP_SECRET,CODE)
    response1 = requests.get(url)
    json_str1 = response1.text
    resp_dict1 = json.loads(json_str1)
    opeen_id = resp_dict1.get('openid')
    access_token2 = resp_dict1.get('access_token')
    print(opeen_id)
    print(access_token2)
    # open_id:oXazLs9rYeUCCMQt2fyOWBtPn2P0
    # access_token2:35_NVgDVuxbVslMznvQaI2Htcb2CV9BOnVc_q152yBRg47a7tX6yg1VshSxpITQYfzepOU6H-S6FFB9QN80_a5MVB1upLkIJwe4AjrYLBjExco

    # 3.拉取用户信息(需scope为 snsapi_userinfo)
    url = "https://api.weixin.qq.com/sns/userinfo?access_token=35_CLQNvLJDFS7ynkUCKUg3d0rToqysq999BZAgG7l4chbQupoC3cp9fsMx3TY6hiiT6tRXjrMhelqbreuf3F7EvAoxP_sAbhwbSZRQ2QKGuOM&openid=oXazLs9rYeUCCMQt2fyOWBtPn2P0&lang=zh_CN.UTF8"
    response2 = requests.get(url)
    json_str2 = response2.text
    resp_dict2 = json.loads(json_str2)
    print(resp_dict2)
    nickname = resp_dict2.get('nickname').encode('ISO-8859-1')
    print(type(nickname))
    print(nickname.decode())

if __name__ == '__main__':
    wechat()






你可能感兴趣的:(python,微信开发,公众号开发,OAuth2.0,微信二次开发,微信)