My path to Python development-WeChat web page authorization (SCAN code login), the path to python

Source: Internet
Author: User
Tags openid

My path to Python development-web page authorization (SCAN code login), the path to python

Another account has some problems, so I want to use this.

At the beginning, I was not fully familiar with this aspect. I want to write my own ideas. You can install it. First, we need to have a basic concept for development.

For details, refer to: webpage authorization on the public platform.

With such a basic understanding, we will start to do the following.

Basic Process:

The QR code is a url, and the scan process is an access process. This url is the server address we have set up. the process of a url and background processing module such as py,

We started to officially authorize the webpage.

Step 1: The user agrees to the authorization and obtains the code

That is, access this url = 'https: // open.weixin.qq.com/connect/oauth2/authorize? Appid = {appid} & redirect_uri = {redirect_url} & response_type = code & scope = snsapi_userinfo & state = STATE # wechat_redirect'

We need to determine the following parameters: appid and redirect_url. Appid is the appid of your public account, and redirect_url is the callback connection that we obtain code after accessing the url above to process code.

Here we provide you with a simple writing method:

1 url_tpl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirect_url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'2 url = url_tpl.format(appid=appid, redirect_url=redirect_url)

Note that:

1. After the user agrees to the authorization, the redirected page is the page connected by redirect_url.

2. code Description: the code in exchange for the access_token will be different for each user authorization. The code can only be used once and will automatically expire if it is not used for 5 minutes.

Step 2: Exchange code for webpage authorization access_token

That is to say, access the URL above url_tpl = 'https: // api.weixin.qq.com/sns/oauth2/access_token? Appid = {appid} & secret = {secret} & code = {code} & grant_type = authorization_code'

Url = url_tpl.format (appid = config. WEIXIN ['appid '], secret = config. WEIXIN ['secret'], code = code)

The required parameters include appid, secret, and code. Appid is the appid of the public account, and the appsecret of the secret. The code is the code we obtained in the first step.

This is because I was just getting started with development and was self-taught. I wrote a piece of Process Code according to my understanding.

1 #-*-encoding: UTF-8-*-2 3 # vim: set ts = 4 et sw = 4 sts = 4 fileencoding = UTF-8: 4 5 import OS 6 import sys 7 import logging 8 import time 9 from zbase. web import core 10 from zbase. web import template 11 from zbase. base. dbpool import with_database 12 import json 13 import config 14 import urllib2 15 import MySQLdb 16 17 log = logging. getLogger () 18 19 20 #1 Step 1: The user agrees to the authorization and obtains code 21 #2 Step 2: Use code in exchange for webpage authorization access_token 22 #3 Step 3: refresh access_token (if needed) 23 #4 Step 4: Pull user information (the scope must be snsapi_userinfo) 24 #5 attached: Check whether the authorization credential (access_token) is valid 25 26 class Visit_User: 27 def _ init _ (self): 28 self. appid = 'appid '# public ID appid 29 self. secret = 'secret' # public account secret 30 self. redirect_url =' http://api.uyu.com/v1/wx/user_auth '# Callback address 31 32 def Visit_Url (self, url): # Every access link 33 try: 34 result = urllib2.urlopen (url ). read () 35 return result 36 failed t urllib2.HTTPError, e: 37 print e. code 38 failed t urllib2.URLErrror, e: 39 print str (e) 40 41 def Get_Code (self): #1 Step 1: The user agrees to the authorization and obtains code 42 get_code_url =' https://open.weixin.qq.com/sns/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect '% (43 self. appid, self. redirect_url) 44 code = self. visit_Url (get_code_url) 45 if code: 46 return code 47 else: 48 print "Failure to obtain results" 49 50 def Get_Access_token (self): #2 Step 2: use code in exchange for webpage authorization access_token 51 code = self. get_Code () 52 get_access_url =' https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code '% (53 self. appid, self. secret, code) 54 acc_token = self. visit_Url (get_access_url) 55 if acc_token ["errcode"]: 56 pass 57 if acc_token ["access_token"]: 58 # access_token = json. loads (access_token) 59 access_token = acc_token ["access_token"] 60 expires_in = acc_token ["token"] 61 token = acc_token ["token"] 62 openid = acc_token ["openid"] 63 scope = acc_token ["scope"] 64 return access_token, openid, refresh_token 65 66 def Refresh_Access_token (self): #3 Step 3: refresh access_token (if needed) 67 yu_zu = self. get_Access_token () 68 refresh_token = yu_zu [2] 69 new_access_url =' https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s '% (70 self. appid, refresh_token) 71 new_acc_token = self. visit_Url (new_access_url) 72 if new_acc_token ["errcode"]: 73 pass 74 if new_acc_token ["access_token"]: 75 # access_token = json. loads (access_token) 76 access_token = token ["access_token"] 77 expires_in = new_acc_token ["expires_in"] 78 refresh_token = token ["token"] 79 openid = token ["openid"] 80 scope = token ["scope"] 81 return access_token, openid 82 83 def Verify_Access_token (self): # verify whether access_token is valid. 84 yu_zu = self. refresh_Access_token () 85 access_token = yu_zu [0] 86 openid = yu_zu [1] 87 verify_url =' https://api.weixin.qq.com/sns/auth?access_token=%s&openid=%s '% (88 access_token, openid) 89 verify = self. Visit_Url (verify_url) 90 if verify ["error"] = 0: 91 print "Succeed !!! "92 return access_token, openid 93 else: 94 pass 95 96 def Get_Message (self): #4 Step 4: Pull user information (scope must be snsapi_userinfo) 97 yu_zu = self. verify_Access_token () 98 access_token = yu_zu [0] 99 openid = yu_zu [1] 100 user_message_url =' https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN '% (101 access_token, openid) 102 user_message = self. visit_Url (user_message_url) 103 openid = user_message ["openid"] 104 global openid105 nickname = user_message ["nickname"] 106 sex = user_message ["sex"] 107 province = user_message ["province"] 108 city = user_message ["city"] 109 country = user_message ["country"] 110 openheadimgurlid = user_message ["headimgurl"] 111 privilege = user_message ["privilege"] 112 unionid = user_message [" unionid "] 113 return openid, nickname, sex, province, city, country, openheadimgur1_114 115 def Insert_db (self): 116 pass117 118 119 120 class Query_User_Tel: 121 def _ init _ (self, tel ): 122 self. openid = openid123 self. tel = tel124 self. conn = MySQLdb. connect (125 host = 'localhost', 126 user = 'root', 127 passwd = '000000', 123456 db = 'test', 128 port = 129) 131 132 def Judge_user (self): 133 try: 134 # conn = MySQLdb. connect (host = 'localhost', user = 'root', passwd = '000000', db = 'shanghai', port = 123456) 3306 cur = self. conn. cursor () 136 cur.exe cute ('select * from register WHERE Openid = % s' % self. openid) 137 rows = cur. fetchall () 138 if rows: 139 return True140 else: 141 print "Please register with the registration page" 142 cur. close () 143 self. conn. close () 144 TB t MySQLdb. error, e: 145 print "Mysql Error % d: % s" % (e. args [0], e. args [1]) 146 147 def Judge_tel (self): 148 try: 149 # conn = MySQLdb. connect (host = 'localhost', user = 'root', passwd = '000000', db = 'shanghai', port = 123456) 3306 cur = self. conn. cursor () 151 cur.exe cute ('select * from register WHERE Tel = % s' % self. tel) 152 rows = cur. fetchall () 153 if rows: 154 return True155 else: 156 print "Please enter the telephone number again" 157 cur. close () 158 self. conn. close () 159 Tb t MySQLdb. error, e: 160 print "Mysql Error % d: % s" % (e. args [0], e. args [1])
View Code

At first, I thought all the steps had to be taken, and then I found that in my actual operations, I only needed to get the openid, in other words, I only need to use the code-for-zone webpage to authorize access_token, and obtain the openid from it, so that the verification or binding process can be completed.

Of course, if you want to be more reasonable, you need more complex and complete operations.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.