5、短信驗證碼
1、注冊容聯云賬號,登錄并查看開發文檔(以下分析來自接口文檔)
2、開發文檔【準備1】:請求URL地址1.示例:https://app.cloopen.com:8883/2013-12-26/Accounts/{}/SMS/TemplateSMS?sig={}ACCOUNT SID# sig:使用MD5加密(賬戶Id + 賬戶授權令牌 + 時間戳)【準備2】:請求頭headersAccept:application/xml;Content-Type:application/xml;charset=utf-8;Content-Length:256; Authorization: # 使用Base64編碼(賬戶Id + 冒號 + 時間戳【準備3】:請求體datato :短信接收端手機號碼集合appId :應用Id,官網控制臺應用列表獲取templateId :模板Id,測試模板id是1。datas :補充模板短信中的內容[驗證碼 | 幾分鐘輸入]經過對接口文檔分析,最終需要準備:1.POST請求的地址:url2.POST請求的請求頭:headers3.POST請求的請求體:datahttps://app.cloopen.com:8883/2013-12-26/Accounts/{}/SMS/TemplateSMS?sig={}
容聯云
ACCOUNT SID:2c94812dgad3018872722dec086d
(主賬戶ID)
AUTH TOKEN:
222*******e929查看
(賬戶授權令牌)
Rest URL(生產):https://app.cloopen.com:8883
AppID(默認):2c948zdfe334gg8872722f1b0874未上線
(APP TOKEN 請到應用管理中獲取)
鑒權IP: #關閉,未認證情況下開啟,無法發短信
設計添加接口路由
#user/urls.py# 短信驗證:v1/users/sms/codepath('sms/code', views.sms_view),
設計短信發送工具
#utils/sms.py
"""對接容聯云短信平臺,實現發送短信驗證碼
"""
import random
import time
import base64
import requests
from hashlib import md5class YunTongXunAPI:def __init__(self, accountSid, authToken, appId, templateId):"""差異化的內容做成應用:param accountSid: 賬號id,控制臺:param authToken: 授權令牌,控制臺:param appId: 控制臺:param templateId: 短信模板,測試為1"""self.accountSid = accountSidself.authToken = authTokenself.appId = appIdself.templateId = templateIddef get_url(self):"""生成url地址"""post_url = "https://app.cloopen.com:8883/2013-12-26/Accounts/{}/SMS/TemplateSMS?sig={}".format(self.accountSid, self.get_sig())return post_urldef get_headers(self):"""獲取請求頭"""# 使用Base64編碼(賬戶Id+冒號+時間戳)s = self.accountSid + ':' + time.strftime("%Y%m%d%H%M%S")auth = base64.b64encode(s.encode()).decode()headers = {"Accept": "application/json;","Content-Type": "application/json;charset=utf-8;",# "Content-Length": "256;", #request模塊會自動添加"Authorization": auth}return headersdef get_body(self, phone, code):"""請求體"""data = {"to": phone,"appId": self.appId,"templateId": self.templateId,"datas": [code, '3']}return datadef run(self, phone, code):"""程序入口函數"""url = self.get_url()headers = self.get_headers()body = self.get_body(phone, code)# html: {"statusCode":"000000"}html = requests.post(url=url, headers=headers, json=body).json()#print(html)#未添加測試賬號 {'statusCode': '111188', 'statusMsg': '【賬號】主賬戶綁定的測試號碼個數為零'}#添加測試賬號{'statusCode': '000000', 'templateSMS': {'smsMessageSid': 'fa9de45f66ca4f5ca76833b9005b10e4', 'dateCreated': '20230602224219'}}return htmldef get_sig(self):"""功能函數:生成sig使用MD5加密(賬戶Id+賬戶授權令牌+時間戳)"""s = self.accountSid + self.authToken + time.strftime("%Y%m%d%H%M%S")m = md5()m.update(s.encode())return m.hexdigest().upper()if __name__ == '__main__':config = {"accountSid": "2c94812dgad3018872722dec086d","authToken": "22205d59b81465abbd26cf16e929","appId": "2c948zdfe334gg8872722f1b0874","templateId": "1"}ytx = YunTongXunAPI(**config)code = random.randint(1000, 9999)ytx.run("17723452345", code)#運行查看是否有短信收到
設計功能路由調用
#瀏覽器點擊獲取驗證碼,查看xhrheaders里:請求地址 http://127.0.0.1:8000/v1/users/sms/codepayload里:{"phone":""}:
#user/urls.py# 短信驗證:v1/users/sms/codepath('sms/code', views.sms_view),
#dashopt/settings.py
...
#############短信驗證配置開始############
MSG_CONFIG = {"accountSid": "2c94811c88518872722dec086d","authToken": "2220db32a697754048bb97e929","appId": "2c94811c8853872722f1b0874","templateId": "1"}
設計發送功能
#user/views.py
...
from utils.sms import YunTongXunAPIdef sms_view(request):"""對接容聯云實現短信驗證碼發送1.獲取請求體數據2.生成短信驗證碼3.調用容聯云接口發送短信"""data = json.loads(request.body)phone = data.get("phone")code = random.randint(1000, 9999)smsapi = YunTongXunAPI(**settings.MSG_CONFIG)smsapi.run(phone,code)return JsonResponse({"code": 200, "data": "發送成功"})#http://localhost:7000/dadashop/templates/register_sms.html 發送驗證是否成功
調整下
#user/views.py
...
from utils.sms import YunTongXunAPIdef sms_view(request):"""對接容聯云實現短信驗證碼發送1.獲取請求體數據2.生成短信驗證碼3.調用容聯云接口發送短信"""data = json.loads(request.body)phone = data.get("phone")code = random.randint(1000, 9999)sms_html = send_msg(phone,code)if sms_html.get("statusCode") == "000000":return JsonResponse({"code": 200, "data": "發送成功"})return JsonResponse({"code": 10110, "error": {"message": "發送失敗"}})def send_msg(phone,code):smsapi = YunTongXunAPI(**settings.MSG_CONFIG)sms_html = smsapi.run(phone,code)return sms_html
發送并帶有驗證的功能
設計redis緩存
#dashopt/settings.py
...
CACHES = {# 緩存郵件激活隨機數"default": {
...},"msg_code": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": "redis://192.168.1.11:6379/2",# "TIMEOUT": None, 默認300s"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient","PASSWORD": "123456"}},
}
放入redis
#user/views.py
...
MSG_CACHE = caches["msg_code"]
...
def sms_view(request):"""對接容聯云實現短信驗證碼發送1.獲取請求體數據2.生成短信驗證碼3.調用容聯云接口發送短信"""data = json.loads(request.body)phone = data.get("phone")code = random.randint(1000, 9999)# 1.redis中確認: sms_13603263409key = "sms_%s" % phoneredis_code = MSG_CACHE.get(key)if redis_code:# 3分鐘之內已經發過return JsonResponse({"code": 10111, "error": {"message":"code already existed"}})# 3分鐘之內沒有發過:sms_html = send_msg(phone,code)# 2.存入redisif sms_html.get("statusCode") == "000000":MSG_CACHE.set(key, code, 180)return JsonResponse({"code": 200, "data": "發送成功"})return JsonResponse({"code": 10110, "error": {"message": "發送失敗"}})
短時間發送兩次短信,注意第二次發送是否成功,以及redis里的數據
$.ajax({type: "post",url: baseUrl+"/v1/users",datatype: "json",contentType:"application/json",data: JSON.stringify({"uname": $('#uname').val(),"password": $('#upwd').val(),"phone": $('#phone').val(),"email": $('#email').val(),"verify": $('#verify').val(),"carts":localStorage.getItem('cart'),}),success: function (data) { //成功的回調函數if (data.code === 200){//window.localStorage.setItem('dashop_token', data.data.token);//window.localStorage.setItem('dashop_user', data.username);//window.localStorage.setItem('dashop_count', data.data.length);window.localStorage.setItem('dashop_token', data.data.token);window.localStorage.setItem('dashop_user', data.username);window.localStorage.setItem('dashop_count', data.carts_count);alert('注冊成功!');window.location.href = '/dadashop/templates/index.html';}else {alert(data.error.message); //返回后端message,彈窗code already existed}},
celery異步發送
...
from django.conf import settings
from utils.sms import YunTongXunAPI@app.task
def async_send_msg(phone, code): #user/views.py send_msg不用了"""功能函數:發送短信驗證碼"""smsapi = YunTongXunAPI(**settings.MSG_CONFIG)sms_html = smsapi.run(phone, code)return sms_html
#user/views.py
from .tasks import async_send_active_email, async_send_msg
...# 3分鐘之內沒有發過:celery異步# sms_html = send_msg(phone,code)async_send_msg.delay(phone, code)# 2.存入redisMSG_CACHE.set(key, code, 180)return JsonResponse({"code": 200, "data": "發送成功"})
重啟celery
#發送短信,查看celery日志,查看redis存儲結果...: INFO/MainProcess] Task user.tasks.async_send_msg[36ca7635-b751-4948-b257-c5d422624d82] succeeded in 0.5160000000032596s:
設計驗證
抓包請求
#注冊 查看xhr請求
Request URL: http://127.0.0.1:8000/v1/usersPayload: {uname: "", password: "", phone: "17723452345", email: "", verify: "11111", carts: null}
#user/views.py
...
def users(request):"""注冊模塊視圖邏輯"""# 1.獲取請求體數據data = json.loads(request.body)uname = data.get('uname')password = data.get('password')phone = data.get('phone')email = data.get('email')# 獲取前端提交過來的短信驗證碼# 校驗短信驗證碼verify = data.get('verify')key = "sms_%s" % phoneredis_code = MSG_CACHE.get(key)if verify != str(redis_code): # str 注意數據類型return JsonResponse({"code": 10112, "error": {"message": "code wrong"}})
...
#注冊驗證
http://localhost:7000/dadashop/templates/register_sms.html
OAuth 2.0
授權碼模式(authorization code) 廣泛使用,其他了解
#微博 微連接創建網頁應用
https://open.weibo.com/apps/911505717/info/advanced
應用信息,高級信息,OAuth 2.0,授權回調頁: 編輯回調頁urlhttp://localhost:7000/dadashop/templates/callback.html#查看OAuth 2.0接口文檔
https://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI
"""
%E5%BE%AE%E5%8D%9A --》微博API
涉及到url編碼問題,瀏覽器里帶中文的部分,通過urllib編碼使用如下
from urllib import parse
date = parse.urlencode(%E5%BE%AE%E5%8D%9A)
print(data)
""" #授權頁示例,換成自己的client_id,和上面設置的回調url看是否進入授權頁面
https://api.weibo.com/oauth2/authorize?client_id=123456&redirect_uri=http://www.example.com/response&response_type=code#回調成功后查看url里是否多了code信息
http://www.example.com/response?code=CODE
請求授權
接口功能準備
#utils/weiboapi.py"""第三方微博登錄接口API
"""
import requests
from urllib import parse
from django.conf import settingsclass OAuthWeiboAPI:def __init__(self, client_id, client_secret, redirect_uri):self.client_id = client_idself.client_secret = client_secretself.redirect_uri = redirect_uridef get_grant_url(self):"""獲取微博授權登錄頁的地址"""# https://api.weibo.com/oauth2/authorize?client_id=123456&redirect_uri=http://www.example.com/response&response_type=codebase_url = "https://api.weibo.com/oauth2/authorize?"params = {"client_id": self.client_id,"redirect_uri": self.redirect_uri,"response_type": "code"}return base_url + parse.urlencode(params)if __name__ == '__main__':config = {"client_id": "22342872","client_secret": "e2a52dfasdg5d4b9185db1430735","redirect_uri": "http://localhost:7000/dadashop/templates/callback.html"}weibo_api = OAuthWeiboAPI(**config)grant_url = weibo_api.get_grant_url()print(grant_url)# 將打印的url放到瀏覽器里看是否跳到微博授權頁
抓包路由配置
#抓包路由 http://localhost:7000/dadashop/templates/login.html
http://127.0.0.1:8000/v1/users/weibo/authorization
#user/urls.py
...# 微博授權登錄頁: v1/users/weibo/authorizationpath('weibo/authorization', views.OAuthWeiboUrlView.as_view()),
功能函數設計
#user/views.py
...
from utils.weiboapi import OAuthWeiboAPIclass OAuthWeiboUrlView(View):def get(self, request):"""生成授權登錄頁的地址,返給前端由前端跳轉到授權登錄頁[window.location.href=]"""weibo_api = OAuthWeiboAPI(**settings.WEIBO_CONFIG)oauth_url = weibo_api.get_grant_url()# 返回響應result = {"code": 200, "oauth_url": oauth_url}return JsonResponse(result)
配置試圖函數使用的WEIBO_CONFIG
#dashopt/settings.py
...
#############微博登錄配置開始############
WEIBO_CONFIG = {"client_id": "9134235717","client_secret": "a6dbdca9b1b185bd762f6b8091","redirect_uri": "http://localhost:7000/dadashop/templates/callback.html"}
前端跳轉實現了解
//login.html
...//異步獲取微博登陸地址$.ajax({type:'GET',url:baseUrl+'/v1/users/weibo/authorization',success:function(response){if(response.code==200){window.location.href=response.oauth_url//跳轉后端返回的oauth_url}else{alert('服務器異常')}
跳轉獲取授權碼
#注冊授權,查看是否跳轉
http://localhost:7000/dadashop/templates/callback.html #url跳轉授權回調頁,
http://localhost:7000/dadashop/templates/callback.html?code=1b710d828a02c3e506bedce5#xhr里自動請求到下一個路由(前端已經設計好了),需要進行下一步功能
Request URL: http://127.0.0.1:8000/v1/users/weibo/users?code=1b710d828a02c3e506bedce5
前端跳轉實現了解
//callback.html
...
<script>var uid = ""var querystring = location.search //獲取查詢部分 code=1b710d...window.onload=function(){$.ajax({url: baseUrl+'/v1/users/weibo/users'+querystring,type: 'get',dataType: "json",success: function (res) {if (res.code == 200) {//先清理本地存儲,再跳轉到主頁window.localStorage.clear();window.localStorage.setItem('dashop_token', res.token);window.localStorage.setItem('dashop_user', res.username);$('.query').css({display:"block"})$(".success").css({display:"none"})//none 隱藏了success form_box注冊操作$('.form_box').css({display:"none"})setTimeout(()=>{window.location.href="index.html"//轉到主頁},3000) // 3秒等待}else if(res.code == 201){$('.query').css({display:"none"})$(".success").css({display:"none"})$('.form_box').css({display:"block"})// access_token = res.access_tokenuid = res.uid}else{alert(res.error)}}})
獲取授權token
https://open.weibo.com/wiki/Oauth2/access_token
HTTP請求方式:POST,請求參數
參數 | 必選 | 類型 | 說明 |
---|---|---|---|
client_id | true | string | 第三方應用在微博開放平臺注冊的APPKEY。 |
client_secret | true | string | 在微博開放平臺注冊的應用所對應的AppSecret。 |
grant_type | true | string | 請求的類型,需填寫 authorization_code。 |
code | true | string | 調用第一步 authorize 接口所獲得的授權 code。 |
redirect_uri | true | string | 授權回調地址,傳的值需與在開放平臺網站填寫的回調地址一致,設置填寫位置:“我的應用>應用信息>高級信息”。 |
配置獲取的路由
#user/urls.py #自動跳轉需要的路由
...# 微博登錄[獲取授權令牌access_token]:v1/users/weibo/userspath('weibo/users', views.OAuthWeiboView.as_view()),
獲取toekn功能
#user/views.py
...
import requestsclass OAuthWeiboView(View):def get(self, request):"""生成授權登錄頁的地址,返給前端由前端跳轉到授權登錄頁[window.location.href=]"""# 1.獲取code[查詢字符串]code = request.GET.get("code")if not code:return JsonResponse({"code": 10112, "error": "Not code"})# 2.post請求post_url = "https://api.weibo.com/oauth2/access_token"post_data = {"client_id": settings.WEIBO_CONFIG["client_id"],"client_secret": "ab504366dbb185bd762f6b8091","code":code,"grant_type":"authorization_code","redirect_uri":"http://localhost:7000/dadashop/templates/callback.html",}access_html = requests.post(url=post_url,data=post_data).json()print('---------------get access token---------')print(access_html)return JsonResponse({'code': 200})
#瀏覽器里重新微博登錄下,授權3秒等待再跳轉到主頁 見上面的前端跳轉實現了解
xhr請求 Request URL: http://127.0.0.1:8000/v1/goods/index #需設計#終端查看獲得的token
...."GET /v1/users/weibo/authorization HTTP/1.1" 200 189
---------------get access token---------
{'access_token': '2.00mytczH0HRagz1699aJeq4NC', 'remind_in': '157679999', 'expires_in': 157679999, 'uid': '73207972', 'isRealName': 'true'}
優化到工具類里
#utils/weiboapi.py
import requests
from django.conf import settings
#...
class OAuthWeiboAPI:
#...def get_access_token(self, code):"""獲取access_token接口"""post_url = "https://api.weibo.com/oauth2/access_token"post_data = {"client_id": settings.WEIBO_CONFIG["client_id"],"client_secret": settings.WEIBO_CONFIG["client_secret"],"grant_type": "authorization_code","code": code,"redirect_uri":settings.WEIBO_CONFIG["redirect_uri"]}access_html = requests.post(url=post_url, data=post_data).json()# 獲取access_token成功if access_html.get("access_token"):return access_htmlraise Exception("get access token failed")
#user/views.py
#....# 2.post請求try:weibo_api = OAuthWeiboAPI(**settings.WEIBO_CONFIG)access_html = weibo_api.get_access_token(code)except Exception as e:print(e)return JsonResponse({"code": 10113, "error": "weibo server is busy"})# 成功獲取到access_tokenprint('---- get access token success ----')print(access_html)return JsonResponse({'code': 200})
驗證
#重新注冊,查看跳轉,token打印,準備設計表,入庫token
{'access_token': '2.00mytczH0HRagz1699aJeq4NC', 'remind_in': '157679999', 'expires_in': 157679999, 'uid': '73207972', 'isRealName': 'true'
}
token入庫表設計
#user/models.py
...
class WeiboProfile(BaseModel):"""微博用戶表"""# 外鍵 和用戶表一對一# 因為微博數據存入時,可能還沒有正式用戶,設置外鍵允許為nulluser_profile = models.OneToOneField(UserProfile, on_delete=models.CASCADE, null=True)# db_index:因為后期大量查詢wuid = models.CharField(verbose_name="微博uid", max_length=10, db_index=True, unique=True)access_token = models.CharField(verbose_name="微博授權令牌", max_length=32)class Meta:db_table = "user_weibo_profile"> python manage.py makemigrations
> python manage.py migrate
前端根據返回狀態碼返回頁面
//callback.html
...
<script>var uid = ""var querystring = location.search //獲取查詢部分 code=1b710d...window.onload=function(){$.ajax({url: baseUrl+'/v1/users/weibo/users'+querystring,type: 'get',dataType: "json",success: function (res) {if (res.code == 200) {//先清理本地存儲,再跳轉到主頁window.localStorage.clear();window.localStorage.setItem('dashop_token', res.token);window.localStorage.setItem('dashop_user', res.username);//block顯示,none隱藏 根據返回的201 200 跳轉頁面 $('.query').css({display:"block"})// 請稍后$(".success").css({display:"none"})//登錄成功//none 隱藏了success $('.form_box').css({display:"none"})// 輸入登錄名、手機號信息綁定setTimeout(()=>{window.location.href="index.html"//轉到主頁},3000) // 3秒等待}else if(res.code == 201){$('.query').css({display:"none"})$(".success").css({display:"none"})$('.form_box').css({display:"block"})// access_token = res.access_tokenuid = res.uid}else{alert(res.error)}}})
#user/views.py
from .models import Address, WeiboProfile
#.... # 2.post請求try:weibo_api = OAuthWeiboAPI(**settings.WEIBO_CONFIG)access_html = weibo_api.get_access_token(code)except Exception as e:print(e)return JsonResponse({"code": 10113, "error": "weibo server is busy"})# 成功獲取到access_tokenprint('---- get access token success ----')print(access_html)# 獲取wuid和access_tokenwuid = access_html.get('uid')access_token = access_html.get('access_token')"""微博表中查看該wuid是否存在情況1:用戶第一次微博登錄[201]情況2:用戶之前掃碼登錄過2.1 已經和正式用戶綁定過[200]2.2 在綁定注冊頁不填寫用戶名手機號信息,關閉頁面[201]200響應:{"code":200, "username":xxx, "token": token}201響應:{"code"201,"uid": wuid}"""try:weibo_user = WeiboProfile.objects.get(wuid=wuid)except Exception as e:# 用戶第一次掃碼登錄WeiboProfile.objects.create(wuid=wuid, access_token=access_token)# 返回201,到綁定注冊頁return JsonResponse({"code": 201, "uid": wuid})else:# 情況1:已和正式用戶綁定# 情況2:掃過碼,但是并未綁定user = weibo_user.user_profileif user:token = make_token(user.username)result = {"code": 200,"username": user.username,"token": token}return JsonResponse(result)else:result = {"code": 201,"uid": wuid}return JsonResponse(result)
驗證
#登錄頁注冊再次提交,授權登錄驗證 因第一次,返回201 進入綁定手機號郵箱頁面
http://localhost:7000/dadashop/templates/callback.html?code=3743ffa4c057f33c26d1e85fc36c23e3#補充信息提交,
Request URL: http://127.0.0.1:8000/v1/users/weibo/users 405 Method Not AllowedPayload: {"uid": "736547972","username": "user03","password": "123456","phone": "17723452345","email": "65733058@qq.com"}設計提交試圖,獲取數據,完成綁定
設計提交功能
#user/views.py
class OAuthWeiboView(View):
#...def post(self, request):"""綁定注冊視圖邏輯1.獲取請求體數據2.存入用戶表[UserProfile]3.兩個用戶綁定[更新外鍵-user_profile]4.組織數據返回"""data = json.loads(request.body)username = data.get("username")password = data.get("password")email = data.get("email")phone = data.get("phone")uid = data.get("uid")# 處理密碼m = md5()m.update(password.encode())pwd_md5 = m.hexdigest()# 創建正式用戶[create]并和微博用戶綁定[update]# 事務with transaction.atomic():sid = transaction.savepoint()try:# 創建正式用戶[UserProfile]user = UserProfile.objects.create(username=username, password=pwd_md5, email=email, phone=phone)# 更新外鍵[WeiboProfile]weibo_user = WeiboProfile.objects.get(wuid=uid)weibo_user.user_profile = userweibo_user.save()except Exception as e:print("bind user error", e)# 回滾transaction.savepoint_rollback(sid)return JsonResponse({"code": 10114, "error": "database error"})# 提交事務transaction.savepoint_commit(sid)# 1.發送激活郵件verify_url = get_verify_url(username) #下面重構功能函數async_send_active_email.delay(email, verify_url)# 2.簽發tokentoken = make_token(username)# 3.組織數據返回result = {"code": 200,"username": username,"token": token}return JsonResponse(result)
功能函數:生成郵件激活鏈接
#user/views.pydef get_verify_url(uname):"""功能函數:生成郵件激活鏈接"""# http://127.0.0.1:7000/dadashop/templates/active.html?code=xxx# code: base64(1016_username)code_num = "%d" % random.randint(1000, 9999)code_str = "%s_%s" % (code_num, uname)code = base64.urlsafe_b64encode(code_str.encode()).decode()# 存入redis[key-value] email_active_usernamekey = "email_active_%s" % unameCODE_MSG.set(key, code_num, 3600 * 24 * 3)# 生成激活鏈接verify_url = "http://127.0.0.1:7000/dadashop/templates/active.html?code=%s" % codereturn verify_url
再次注冊驗證
#登錄,注冊,授權,綁定郵箱信息 ,收件箱
二、微博登錄流程梳理
-
微博開放平臺
-
注冊微博開放平臺用戶,并進行實名認證
-
創建應用
- 控制臺-應用基本信息:App Key 、App Secret
- 控制臺-應用高級信息:設置回調地址
-
關于回調地址
回調地址不能出現127.0.0.1,必須為域名[localhost]
-
-
第三方微博登錄功能梳理
-
用戶:登錄頁點擊微博登錄,xhr請求到后端索要微博授權登錄頁地址
-
后端:視圖函數中生成微博授權登錄頁地址【微博接口文檔】,返給前端
-
前端:重定向到微博授權登錄頁地址【login.html】
window.location.href=response.oauth_url
-
用戶:輸入微博賬號和密碼 或者 掃碼,確認授權并登錄
-
微博:校驗微博賬號和密碼信息,如果正確則跳轉到回調地址【微博開放平臺設置】,在回調地址中添加授權碼的查詢參數
-
前端:移花接木,把授權碼code從回調地址【7000端口】取出來,放到后端路由【8000端口】發送xhr請求
var querystring = location.search $.ajax({url:baseUrl+'v1/users/weibo/users' + querystring })
-
后端:獲取授權碼[request.GET.get()],向微博發請求【微博開發文檔】獲取授權令牌【access_token】
{“uid”:“xxx”,“access_token”:“xxx”,…}
-
后端:獲取到授權令牌后,創建微博表并存儲數據,并執行綁定注冊流程
后端和前端協商狀態碼:
200: 說明用戶之前已經使用微博登錄過并和正式用戶做了綁定,直接簽發token并跳轉到主頁【index.html】
201:說明用戶之前并沒有和正式用戶綁定過,跳轉到綁定注冊頁面
-
前端:根據狀態碼決定頁面跳轉
200:跳轉到index.html
201:跳轉到綁定注冊頁面【讓用戶填寫注冊相關信息】
-
用戶:填寫注冊信息,點擊提交,發送xhr請求到后端
-
后端:把該用戶存入正式用戶表并和當前微博用戶做好關聯
-
access_token使用:服務器端獲取到該用戶的access_token后,可以在微博開放平臺-我的應用-接口管理,獲取該用戶的相關資源【微博開放出來的資源】
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-qV8dt0GN-1688875149467)(project-pictures/09_第三方微博登錄流程圖.png)]
pip切換源
sudo pip3 install 模塊名 -i https://pypi.tuna.tsinghua.edu.cn/simple/1.阿里云 http://mirrors.aliyun.com/pypi/simple/
2.豆瓣http://pypi.douban.com/simple/
3.清華大學 https://pypi.tuna.tsinghua.edu.cn/simple/
4.中國科學技術大學 http://pypi.mirrors.ustc.edu.cn/simple/
5.華中科技大學http://pypi.hustunique.com/ pip3 freeze | grep -i 'redis'
> pip3 install django_redis -i https://pypi.tuna.tsinghua.edu.cn/simple/
> 離線安裝- 下載安裝包[官網] :.tar.gz- 解壓:tar -zxvf xxx.tar.gz- 到解壓目錄尋找:setup.py [README文件中有安裝說明]- 安裝:sudo python3 setup.py install > python manage.py shell
>>> from django.core.cache import cache
>>> cache.set("zhaoliying",1016)
True # redis 里1號庫查看驗證,默認過期的事件是300s
:說明用戶之前并沒有和正式用戶綁定過,跳轉到綁定注冊頁面
-
前端:根據狀態碼決定頁面跳轉
200:跳轉到index.html
201:跳轉到綁定注冊頁面【讓用戶填寫注冊相關信息】
-
用戶:填寫注冊信息,點擊提交,發送xhr請求到后端
-
后端:把該用戶存入正式用戶表并和當前微博用戶做好關聯
access_token使用:服務器端獲取到該用戶的access_token后,可以在微博開放平臺-我的應用-接口管理,獲取該用戶的相關資源【微博開放出來的資源】
[外鏈圖片轉存中…(img-qV8dt0GN-1688875149467)]
pip切換源
sudo pip3 install 模塊名 -i https://pypi.tuna.tsinghua.edu.cn/simple/1.阿里云 http://mirrors.aliyun.com/pypi/simple/
2.豆瓣http://pypi.douban.com/simple/
3.清華大學 https://pypi.tuna.tsinghua.edu.cn/simple/
4.中國科學技術大學 http://pypi.mirrors.ustc.edu.cn/simple/
5.華中科技大學http://pypi.hustunique.com/ pip3 freeze | grep -i 'redis'
> pip3 install django_redis -i https://pypi.tuna.tsinghua.edu.cn/simple/
> 離線安裝- 下載安裝包[官網] :.tar.gz- 解壓:tar -zxvf xxx.tar.gz- 到解壓目錄尋找:setup.py [README文件中有安裝說明]- 安裝:sudo python3 setup.py install > python manage.py shell
>>> from django.core.cache import cache
>>> cache.set("zhaoliying",1016)
True # redis 里1號庫查看驗證,默認過期的事件是300s