前端登錄註冊頁面、多方式登錄功能、騰訊雲簡訊發送功能二次封裝(包)、發送簡訊介面
- 2022 年 4 月 24 日
- 筆記
今日內容概要
- 登陸註冊頁面
- 多方式登陸功能
- 騰訊雲簡訊發送二次封裝
- 發送簡訊介面
內容詳細
1、登陸註冊頁面(前端項目頁面)
# 打開前端項目 luffycity:
# 如果登錄註冊是一個新頁面,比較好寫
新建一個頁面組件,跳轉到這個頁面即可
# 使用vue-router實現頁面跳轉
第一步:需要在router文件夾的index.js中配置一條路由
{
path: '/login',
name: 'login',
component: Login
}
第二步:訪問/login路徑,就會顯示Login這個頁面組件
第三步:點擊按鈕跳轉到這個路徑
js中:this.$router.push('/login')
第四步:在html頁面中跳轉-->點擊該標籤,就可以跳轉到/login這個路徑
<router-link to="/login"></router-link>
# 如果登錄註冊是單獨一個頁面的話比較簡單
# 現在要求登錄註冊是彈出模態框效果--》彈出框---》也是組件
創建:Login,Register兩個組件,普通組件---》放在components文件夾下
更改 src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Login from "@/components/Login"
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/home',
name: 'home',
component: HomeView
},
{
path: '/login',
name: 'login',
component: Login
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
更改 src/components/Header.vue :
<template>
<div class="header">
<div class="slogan">
<p>老男孩IT教育 | 幫助有志向的年輕人通過努力學習獲得體面的工作和生活</p>
</div>
<div class="nav">
<ul class="left-part">
<li class="logo">
<router-link to="/">
<img src="../assets/img/head-logo.svg" alt="">
</router-link>
</li>
<li class="ele">
<span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免費課</span>
</li>
<li class="ele">
<span @click="goPage('/actual-course')" :class="{active: url_path === '/actual-course'}">實戰課</span>
</li>
<li class="ele">
<span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">輕課</span>
</li>
</ul>
<div class="right-part">
<div>
<span @click="put_login">登錄</span>
<span class="line">|</span>
<span @click="put_register">註冊</span>
</div>
</div>
<Login v-if="is_login" @close="close_login" @go="put_register"/>
<Register v-if="is_register" @close="close_register" @go="put_login"/>
</div>
</div>
</template>
<script>
import Login from "@/components/Login";
import Register from "@/components/Register";
export default {
name: "Header",
data() {
return {
url_path: sessionStorage.url_path || '/',
is_login: false,
is_register: false
}
},
methods: {
goPage(url_path) {
// 已經是當前路由就沒有必要重新跳轉
if (this.url_path !== url_path) {
this.$router.push(url_path);
}
sessionStorage.url_path = url_path;
},
close_login() {
this.is_login = false
},
close_register() {
this.is_register = false
},
put_register() {
this.is_register = true
this.is_login = false
},
put_login() {
this.is_register = false
this.is_login = true
}
},
created() {
sessionStorage.url_path = this.$route.path;
this.url_path = this.$route.path;
},
components: {
Login, Register
}
}
</script>
<style scoped>
.header {
background-color: white;
box-shadow: 0 0 5px 0 #aaa;
}
.header:after {
content: "";
display: block;
clear: both;
}
.slogan {
background-color: #eee;
height: 40px;
}
.slogan p {
width: 1200px;
margin: 0 auto;
color: #aaa;
font-size: 13px;
line-height: 40px;
}
.nav {
background-color: white;
user-select: none;
width: 1200px;
margin: 0 auto;
}
.nav ul {
padding: 15px 0;
float: left;
}
.nav ul:after {
clear: both;
content: '';
display: block;
}
.nav ul li {
float: left;
}
.logo {
margin-right: 20px;
}
.ele {
margin: 0 20px;
}
.ele span {
display: block;
font: 15px/36px '微軟雅黑';
border-bottom: 2px solid transparent;
cursor: pointer;
}
.ele span:hover {
border-bottom-color: orange;
}
.ele span.active {
color: orange;
border-bottom-color: orange;
}
.right-part {
float: right;
}
.right-part .line {
margin: 0 10px;
}
.right-part span {
line-height: 68px;
cursor: pointer;
}
</style>
更改 src/components/Banner.vue的template標籤:
<template>
<div class="banner">
<el-carousel :interval="5000" arrow="always" height="400px">
<el-carousel-item v-for="item in banner_list">
<!-- 只跳自己的路徑,不會跳第三方 百度,cnblogs,-->
<div v-if="!(item.link.indexOf('http')>-1)">
<router-link :to="item.link">
<img :src="item.image" alt="">
</router-link>
</div>
<div v-else>
<a :href="item.link">
<img :src="item.image" alt="">
</a>
</div>
</el-carousel-item>
</el-carousel>
</div>
</template>
新建:src/components/Register.vue
<template>
<div class="register">
<div class="box">
<i class="el-icon-close" @click="close_register"></i>
<div class="content">
<div class="nav">
<span class="active">新用戶註冊</span>
</div>
<el-form>
<el-input
placeholder="手機號"
prefix-icon="el-icon-phone-outline"
v-model="mobile"
clearable
@blur="check_mobile">
</el-input>
<el-input
placeholder="密碼"
prefix-icon="el-icon-key"
v-model="password"
clearable
show-password>
</el-input>
<el-input
placeholder="驗證碼"
prefix-icon="el-icon-chat-line-round"
v-model="sms"
clearable>
<template slot="append">
<span class="sms" @click="send_sms">{{ sms_interval }}</span>
</template>
</el-input>
<el-button type="primary">註冊</el-button>
</el-form>
<div class="foot">
<span @click="go_login">立即登錄</span>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Register",
data() {
return {
mobile: '',
password: '',
sms: '',
sms_interval: '獲取驗證碼',
is_send: false,
}
},
methods: {
close_register() {
this.$emit('close', false)
},
go_login() {
this.$emit('go')
},
check_mobile() {
if (!this.mobile) return;
if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
this.$message({
message: '手機號有誤',
type: 'warning',
duration: 1000,
onClose: () => {
this.mobile = '';
}
});
return false;
}
this.is_send = true;
},
send_sms() {
if (!this.is_send) return;
this.is_send = false;
let sms_interval_time = 60;
this.sms_interval = "發送中...";
let timer = setInterval(() => {
if (sms_interval_time <= 1) {
clearInterval(timer);
this.sms_interval = "獲取驗證碼";
this.is_send = true; // 重新回復點擊發送功能的條件
} else {
sms_interval_time -= 1;
this.sms_interval = `${sms_interval_time}秒後再發`;
}
}, 1000);
}
}
}
</script>
<style scoped>
.register {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
z-index: 10;
background-color: rgba(0, 0, 0, 0.3);
}
.box {
width: 400px;
height: 480px;
background-color: white;
border-radius: 10px;
position: relative;
top: calc(50vh - 240px);
left: calc(50vw - 200px);
}
.el-icon-close {
position: absolute;
font-weight: bold;
font-size: 20px;
top: 10px;
right: 10px;
cursor: pointer;
}
.el-icon-close:hover {
color: darkred;
}
.content {
position: absolute;
top: 40px;
width: 280px;
left: 60px;
}
.nav {
font-size: 20px;
height: 38px;
border-bottom: 2px solid darkgrey;
}
.nav > span {
margin-left: 90px;
color: darkgrey;
user-select: none;
cursor: pointer;
padding-bottom: 10px;
border-bottom: 2px solid darkgrey;
}
.nav > span.active {
color: black;
border-bottom: 3px solid black;
padding-bottom: 9px;
}
.el-input, .el-button {
margin-top: 40px;
}
.el-button {
width: 100%;
font-size: 18px;
}
.foot > span {
float: right;
margin-top: 20px;
color: orange;
cursor: pointer;
}
.sms {
color: orange;
cursor: pointer;
display: inline-block;
width: 70px;
text-align: center;
user-select: none;
}
</style>
新建:src/components/Login.vue
<template>
<div class="login">
<div class="box">
<i class="el-icon-close" @click="close_login"></i>
<div class="content">
<div class="nav">
<span :class="{active: login_method === 'is_pwd'}"
@click="change_login_method('is_pwd')">密碼登錄</span>
<span :class="{active: login_method === 'is_sms'}"
@click="change_login_method('is_sms')">簡訊登錄</span>
</div>
<el-form v-if="login_method === 'is_pwd'">
<el-input
placeholder="用戶名/手機號/郵箱"
prefix-icon="el-icon-user"
v-model="username"
clearable>
</el-input>
<el-input
placeholder="密碼"
prefix-icon="el-icon-key"
v-model="password"
clearable
show-password>
</el-input>
<el-button type="primary">登錄</el-button>
</el-form>
<el-form v-if="login_method === 'is_sms'">
<el-input
placeholder="手機號"
prefix-icon="el-icon-phone-outline"
v-model="mobile"
clearable
@blur="check_mobile">
</el-input>
<el-input
placeholder="驗證碼"
prefix-icon="el-icon-chat-line-round"
v-model="sms"
clearable>
<template slot="append">
<span class="sms" @click="send_sms">{{ sms_interval }}</span>
</template>
</el-input>
<el-button type="primary">登錄</el-button>
</el-form>
<div class="foot">
<span @click="go_register">立即註冊</span>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Login",
data() {
return {
username: '',
password: '',
mobile: '',
sms: '',
login_method: 'is_pwd',
sms_interval: '獲取驗證碼',
is_send: false,
}
},
methods: {
close_login() {
this.$emit('close')
},
go_register() {
this.$emit('go')
},
change_login_method(method) {
this.login_method = method;
},
check_mobile() {
if (!this.mobile) return;
if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
this.$message({
message: '手機號有誤',
type: 'warning',
duration: 1000,
onClose: () => {
this.mobile = '';
}
});
return false;
}
this.is_send = true;
},
send_sms() {
if (!this.is_send) return;
this.is_send = false;
let sms_interval_time = 60;
this.sms_interval = "發送中...";
let timer = setInterval(() => {
if (sms_interval_time <= 1) {
clearInterval(timer);
this.sms_interval = "獲取驗證碼";
this.is_send = true; // 重新回復點擊發送功能的條件
} else {
sms_interval_time -= 1;
this.sms_interval = `${sms_interval_time}秒後再發`;
}
}, 1000);
}
}
}
</script>
<style scoped>
.login {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
z-index: 10;
background-color: rgba(0, 0, 0, 0.3);
}
.box {
width: 400px;
height: 420px;
background-color: white;
border-radius: 10px;
position: relative;
top: calc(50vh - 210px);
left: calc(50vw - 200px);
}
.el-icon-close {
position: absolute;
font-weight: bold;
font-size: 20px;
top: 10px;
right: 10px;
cursor: pointer;
}
.el-icon-close:hover {
color: darkred;
}
.content {
position: absolute;
top: 40px;
width: 280px;
left: 60px;
}
.nav {
font-size: 20px;
height: 38px;
border-bottom: 2px solid darkgrey;
}
.nav > span {
margin: 0 20px 0 35px;
color: darkgrey;
user-select: none;
cursor: pointer;
padding-bottom: 10px;
border-bottom: 2px solid darkgrey;
}
.nav > span.active {
color: black;
border-bottom: 3px solid black;
padding-bottom: 9px;
}
.el-input, .el-button {
margin-top: 40px;
}
.el-button {
width: 100%;
font-size: 18px;
}
.foot > span {
float: right;
margin-top: 20px;
color: orange;
cursor: pointer;
}
.sms {
color: orange;
cursor: pointer;
display: inline-block;
width: 70px;
text-align: center;
user-select: none;
}
</style>
2、多方式登陸功能(後端項目介面)
# 打開後端 luffy_api項目
# 輸入用戶名(手機號,郵箱),密碼,都能登陸成功,簽發token
# {username:lqz/1829348883775/[email protected],password:lqz123}--->到後端---》去資料庫查用戶,如果用戶名密碼正確,簽發token,如果不正確,返回錯誤
pip install restframework-jwt
修改視圖類 user/views.py:
from utils.common import add # pycharm提示紅,但是沒有錯
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.my_logging import logger
class TestView(APIView):
def get(self, requeste):
res = add(8, 9)
# 記錄日誌
logger.info("我執行了一下")
print(res)
return Response('ok')
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework.decorators import action
from .models import User
from rest_framework.exceptions import APIException
from utils.response import APIResponse
class MobileView(ViewSet):
# get 請求攜帶手機號,就能校驗手機號
@action(methods=["GET"], detail=False)
def check_mobile(self, request):
try:
mobile = request.query_params.get('mobile')
User.objects.get(mobile=mobile)
return APIResponse() # {code:100,msg:成功}-->前端判斷,100就是手機號存在,非100,手機號步驟
except Exception as e:
raise APIException(str(e)) # 處理了全局異常,這裡沒問題
from .serializer import MulLoginSerializer
class LoginView(GenericViewSet):
serializer_class = MulLoginSerializer
queryset = User
# 兩個登陸方式都寫在這裡面(多方式,一個是驗證碼登陸)
# login不是保存,但是用post,咱們的想法是把驗證邏輯寫到序列化類中
@action(methods=["post"], detail=False)
def mul_login(self, request):
try:
ser = MulLoginSerializer(data=request.data, context={'request': request})
ser.is_valid(raise_exception=True) # 如果校驗失敗,直接拋異常,不需要加if判斷了
token = ser.context.get('token')
username = ser.context.get('username')
icon = ser.context.get('icon')
return APIResponse(token=token, username=username, icon=icon) # {code:100,msg:成功,token:dsadsf,username:lqz}
except Exception as e:
raise APIException(str(e))
新建序列化類 user/serializer.py:
from .models import User
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
# 這個序列化類,只用來做反序列化,數據校驗,最後不保存,不用來做序列化
class MulLoginSerializer(serializers.ModelSerializer):
# 一定要重寫username這個欄位,因為username這個欄位校驗規則是從User表映射過來的,
# username是唯一,假設資料庫中存在lqz這個用戶,傳入lqz,欄位自己的校驗規則就會校驗失敗,失敗原因是資料庫存在一個lqz用戶了
# 所以需要重寫這個欄位,取消 掉它的unique
username = serializers.CharField(max_length=18, min_length=3) # 一定要重寫,不重寫,欄位自己的校驗過不去,就到不了全局鉤子
class Meta:
model = User
fields = ['username', 'password']
def validate(self, attrs):
# 在這裡面完成校驗,如果校驗失敗,直接拋異常
# 1 多方式得到user
user = self._get_user(attrs)
# 2 user簽發token
token = self._get_token(user)
# 3 把token,username,icon放到context中
self.context['token'] = token
self.context['username'] = user.username
# self.context['icon'] = '//127.0.0.1:8000/media/'+str(user.icon) # 對象ImageField的對象
# self.context['icon'] = '//127.0.0.1:8000/media/'+str(user.icon) # 對象ImageField的對象
request = self.context['request']
# request.META['HTTP_HOST']取出服務端的ip地址
icon = '//%s/media/%s' % (request.META['HTTP_HOST'], str(user.icon))
self.context['icon'] = icon
return attrs
# 意思是該方法只在類內部用,但是外部也可以用,如果寫成__就只能再內部用了
def _get_user(self, attrs):
import re
username = attrs.get('username')
if re.match(r'^1[3-9][0-9]{9}$', username):
user = User.objects.filter(mobile=username).first()
elif re.match(r'^.+@.+$', username):
user = User.objects.filter(email=username).first()
else:
user = User.objects.filter(username=username).first()
if not user:
# raise ValidationError('用戶不存在')
raise ValidationError('用戶名或密碼錯誤')
# 取出前端傳入的密碼
password = attrs.get('password')
if not user.check_password(password): # 學auth時講的,通過明文校驗密碼
raise ValidationError("用戶名或密碼錯誤")
return user
def _get_token(self, user):
# jwt模組中提供的
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return token
修改 user/urls.py:
from django.urls import path, include
from rest_framework.routers import SimpleRouter
from .views import MobileView, LoginView, SendSmsView
router = SimpleRouter()
# 127.0.0.1:8000/api/v1/user/mobile/check_mobile
router.register('mobile', UserView, 'mobile')
# # 127.0.0.1:8000/api/v1/user/login/mul_login--->post
router.register('login', LoginView, 'login')
urlpatterns = [
path('', include(router.urls)),
]
3、騰訊雲簡訊發送二次封裝
# 簡訊文檔地址:
//cloud.tencent.com/document/product/382/43196
# 安裝sdk模組:
pip install tencentcloud-sdk-python
# 進入騰訊雲創建密鑰
# 單獨文本測試簡訊能否正常接收
# 封裝成包,以後,無論什麼框架,只要把包copy過去,導入直接用即可
# 將 libs做成包 創建:
__init__.py
tencent_sms_v3 目錄下繼續創建:
__init__.py
settings.py
sms.py
在 libs/tencent_sms_v3/init.py中寫:
from .sms import get_code, send_sms
在 libs/tencent_sms_v3/settings.py中寫:
# 按照自己的騰訊雲簡訊配置填寫
SECRETID = 'AKIDWlmZ7RWLvFI5cv0pOhx1rTr0vhEVVGl1'
SECRETKEY = '3qNddNq30g6JH1WnrhJgpjPr67uUrztY'
APPID = "1400668779"
SIGNAME = '開源大牛公眾號'
TemplateId = "1379611"
在在 libs/tencent_sms_v3/sms.py中寫:
import random
from . import settings
from utils.my_logging import logger
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 導入對應產品模組的client models
from tencentcloud.sms.v20210111 import sms_client, models
# 導入可選配置類
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
# 寫兩個函數,
# 獲取驗證碼的函數
def get_code(count=4):
code_str = ''
for i in range(count):
num = random.randint(0, 9)
code_str += str(num)
return code_str
# 發送簡訊的函數
def send_sms(phone, code):
try:
cred = credential.Credential(settings.SECRETID, settings.SECRETKEY)
# 實例化一個http選項,可選的,沒有特殊需求可以跳過。
httpProfile = HttpProfile()
httpProfile.reqMethod = "POST" # post請求(默認為post請求)
httpProfile.reqTimeout = 30 # 請求超時時間,單位為秒(默認60秒)
httpProfile.endpoint = "sms.tencentcloudapi.com" # 指定接入地域域名(默認就近接入)
clientProfile = ClientProfile()
clientProfile.signMethod = "TC3-HMAC-SHA256" # 指定簽名演算法
clientProfile.language = "en-US"
clientProfile.httpProfile = httpProfile
client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
req = models.SendSmsRequest()
req.SmsSdkAppId = settings.APPID
req.SignName = settings.SIGNAME
req.TemplateId = settings.TemplateId
req.TemplateParamSet = [code, ]
req.PhoneNumberSet = ["+86%s" % phone, ]
req.SessionContext = ""
req.ExtendCode = ""
req.SenderId = ""
client.SendSms(req)
# print(resp.to_json_string(indent=2))
return True
except TencentCloudSDKException as err:
# 如果簡訊發送失敗,記錄一下日誌--》一旦使用了記錄日誌,使用的是django 的日誌,以後這個包,給別的框架用,要改日誌
logger.error('手機號為:%s發送簡訊失敗,失敗原因:%s' % phone, str(err))
sdk發送簡訊v3版本:創建send_sms_v3.py:
# -*- coding: utf-8 -*-
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 導入對應產品模組的client models。
from tencentcloud.sms.v20210111 import sms_client, models
# 導入可選配置類
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
try:
# 必要步驟:
# 實例化一個認證對象,入參需要傳入騰訊雲賬戶密鑰對secretId,secretKey。
# 這裡採用的是從環境變數讀取的方式,需要在環境變數中先設置這兩個值。
# 你也可以直接在程式碼中寫死密鑰對,但是小心不要將程式碼複製、上傳或者分享給他人,
# 以免泄露密鑰對危及你的財產安全。
# SecretId、SecretKey 查詢: //console.cloud.tencent.com/cam/capi
cred = credential.Credential("AKIDWlmZ7RWLvFI5cv0pOhx1rTr0vhEVVGl1", "3qNddNq30g6JH1WnrhJgpjPr67uUrztY")
# cred = credential.Credential(
# os.environ.get(""),
# os.environ.get("")
# )
# 實例化一個http選項,可選的,沒有特殊需求可以跳過。
httpProfile = HttpProfile()
# 如果需要指定proxy訪問介面,可以按照如下方式初始化hp(無需要直接忽略)
# httpProfile = HttpProfile(proxy="//用戶名:密碼@代理IP:代理埠")
httpProfile.reqMethod = "POST" # post請求(默認為post請求)
httpProfile.reqTimeout = 30 # 請求超時時間,單位為秒(默認60秒)
httpProfile.endpoint = "sms.tencentcloudapi.com" # 指定接入地域域名(默認就近接入)
# 非必要步驟:
# 實例化一個客戶端配置對象,可以指定超時時間等配置
clientProfile = ClientProfile()
clientProfile.signMethod = "TC3-HMAC-SHA256" # 指定簽名演算法
clientProfile.language = "en-US"
clientProfile.httpProfile = httpProfile
# 實例化要請求產品(以sms為例)的client對象
# 第二個參數是地域資訊,可以直接填寫字元串ap-guangzhou,支援的地域列表參考 //cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
# 實例化一個請求對象,根據調用的介面和實際情況,可以進一步設置請求參數
# 你可以直接查詢SDK源碼確定SendSmsRequest有哪些屬性可以設置
# 屬性可能是基本類型,也可能引用了另一個數據結構
# 推薦使用IDE進行開發,可以方便的跳轉查閱各個介面和數據結構的文檔說明
req = models.SendSmsRequest()
# 基本類型的設置:
# SDK採用的是指針風格指定參數,即使對於基本類型你也需要用指針來對參數賦值。
# SDK提供對基本類型的指針引用封裝函數
# 幫助鏈接:
# 簡訊控制台: //console.cloud.tencent.com/smsv2
# 騰訊雲簡訊小助手: //cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81
# 簡訊應用ID: 簡訊SdkAppId在 [簡訊控制台] 添加應用後生成的實際SdkAppId,示例如1400006666
# 應用 ID 可前往 [簡訊控制台](//console.cloud.tencent.com/smsv2/app-manage) 查看
req.SmsSdkAppId = "1400668779"
# 簡訊簽名內容: 使用 UTF-8 編碼,必須填寫已審核通過的簽名
# 簽名資訊可前往 [中國簡訊](//console.cloud.tencent.com/smsv2/csms-sign) 或 [國際/港澳台簡訊](//console.cloud.tencent.com/smsv2/isms-sign) 的簽名管理查看
req.SignName = "開源大牛公眾號"
# 模板 ID: 必須填寫已審核通過的模板 ID
# 模板 ID 可前往 [中國簡訊](//console.cloud.tencent.com/smsv2/csms-template) 或 [國際/港澳台簡訊](//console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
req.TemplateId = "1379611"
# 模板參數: 模板參數的個數需要與 TemplateId 對應模板的變數個數保持一致,,若無模板參數,則設置為空
req.TemplateParamSet = ["8888"]
# 下發手機號碼,採用 E.164 標準,+[國家或地區碼][手機號]
# 示例如:+8613711112222, 其中前面有一個+號 ,86為國家碼,13711112222為手機號,最多不要超過200個手機號
req.PhoneNumberSet = ["+8618956847259"]
# 用戶的 session 內容(無需要可忽略): 可以攜帶用戶側 ID 等上下文資訊,server 會原樣返回
req.SessionContext = ""
# 簡訊碼號擴展號(無需要可忽略): 默認未開通,如需開通請聯繫 [騰訊雲簡訊小助手]
req.ExtendCode = ""
# 國際/港澳台簡訊 senderid(無需要可忽略): 中國簡訊填空,默認未開通,如需開通請聯繫 [騰訊雲簡訊小助手]
req.SenderId = ""
resp = client.SendSms(req)
# 輸出json格式的字元串回包
print(resp.to_json_string(indent=2))
# 當出現以下錯誤碼時,快速解決方案參考
# - [FailedOperation.SignatureIncorrectOrUnapproved](//cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
# - [FailedOperation.TemplateIncorrectOrUnapproved](//cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
# - [UnauthorizedOperation.SmsSdkAppIdVerifyFail](//cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
# - [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](//cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
# - 更多錯誤,可諮詢[騰訊雲助手](//tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)
except TencentCloudSDKException as err:
print(err)
4、發送簡訊介面
# 效果:
get 攜帶手機號,就發送簡訊 ---》?phone=1828939944
添加路由 user/urls.py:
# 127.0.0.1:8000/api/v1/user/send/send_message/--->get
router.register('send', SendSmsView, 'send')
視圖類添加 user/views.py::
from libs import tencent_sms_v3
class SendSmsView(ViewSet):
@action(methods=['GET'], detail=False)
def send_message(self, request):
try:
phone = request.query_params.get('phone')
# 生成驗證碼
code = tencent_sms_v3.get_code()
# code要保存,否則後面沒法驗證
res = tencent_sms_v3.send_sms(phone, code)
if res:
return APIResponse(msg='簡訊發送成功')
else:
raise APIException("簡訊發送失敗")
except Exception as e:
raise APIException(str(e))