簡訊介面封裝

HuangQiaoqi發表於2024-06-10

騰訊雲簡訊封裝

傳送簡訊

# -*- coding: utf-8 -*-
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
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 查詢: https://console.cloud.tencent.com/cam/capi
    cred = credential.Credential("123123", "123123")
    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
 
    # 例項化要請求產品(以sms為例)的client物件
    # 第二個引數是地域資訊,可以直接填寫字串ap-guangzhou,支援的地域列表參考 https://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)
    req = models.SendSmsRequest()
    # 應用 ID 可前往 [簡訊控制檯](https://console.cloud.tencent.com/smsv2/app-manage) 檢視
    req.SmsSdkAppId = "123123"
    # 簡訊簽名內容: 使用 UTF-8 編碼,必須填寫已稽核透過的簽名
    # 簽名資訊可前往 [國內簡訊](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [國際/港澳臺簡訊](https://console.cloud.tencent.com/smsv2/isms-sign) 的簽名管理檢視
    req.SignName = "123123"
    # 模板 ID: 必須填寫已稽核透過的模板 ID
    # 模板 ID 可前往 [國內簡訊](https://console.cloud.tencent.com/smsv2/csms-template) 或 [國際/港澳臺簡訊](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理檢視
    req.TemplateId = "123123"
    # 模板引數: 模板引數的個數需要與 TemplateId 對應模板的變數個數保持一致,,若無模板引數,則設定為空
    req.TemplateParamSet = ["8888",'5']
    # 下發手機號碼,採用 E.164 標準,+[國家或地區碼][手機號]
    # 示例如:+8613711112222, 其中前面有一個+號 ,86為國家碼,13711112222為手機號,最多不要超過200個手機號
    req.PhoneNumberSet = ["+8615666777888"]
    # 使用者的 session 內容(無需要可忽略): 可以攜帶使用者側 ID 等上下文資訊,server 會原樣返回
    req.SessionContext = ""
    # 簡訊碼號擴充套件號(無需要可忽略): 預設未開通,如需開通請聯絡 [騰訊雲簡訊小助手]
    req.ExtendCode = ""
    # 國內簡訊無需填寫該項;國際/港澳臺簡訊已申請獨立 SenderId 需要填寫該欄位,預設使用公共 SenderId,無需填寫該欄位。注:月度使用量達到指定量級可申請獨立 SenderId 使用,詳情請聯絡 [騰訊雲簡訊小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。
    req.SenderId = ""
 
    resp = client.SendSms(req)
    # 輸出json格式的字串回包
    print(resp.to_json_string(indent=2))
 
except TencentCloudSDKException as err:
    print(err)

封裝成包

# 1 包結構 libs
	-tx_sms
    	-__init__.py #給外部使用的,在這注冊
        -settings.py # 配置
        -sms.py      # 核心

settings

SECRET_ID = ''
SECRET_KEY = ''
SMS_SDK_APPID = ""
SIGN_NAME = ''
TEMPLATE_ID = ""

sms

from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from .settings import *
import random
 
 
# 生成n位數字的隨機驗證碼
def get_code(num=4):
    code = ''
    for i in range(num):
        r = random.randint(0, 9)
        code += str(r)
 
    return code
 
 
# 傳送簡訊函式
def send_sms(mobile, code):
    try:
        cred = credential.Credential(SECRET_ID, SECRET_KEY)
        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
 
        # 例項化要請求產品(以sms為例)的client物件
        # 第二個引數是地域資訊,可以直接填寫字串ap-guangzhou,支援的地域列表參考 https://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)
        req = models.SendSmsRequest()
        # 應用 ID 可前往 [簡訊控制檯](https://console.cloud.tencent.com/smsv2/app-manage) 檢視
        req.SmsSdkAppId = SMS_SDK_APPID
        # 簡訊簽名內容: 使用 UTF-8 編碼,必須填寫已稽核透過的簽名
        # 簽名資訊可前往 [國內簡訊](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [國際/港澳臺簡訊](https://console.cloud.tencent.com/smsv2/isms-sign) 的簽名管理檢視
        req.SignName = SIGN_NAME
        # 模板 ID: 必須填寫已稽核透過的模板 ID
        # 模板 ID 可前往 [國內簡訊](https://console.cloud.tencent.com/smsv2/csms-template) 或 [國際/港澳臺簡訊](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理檢視
        req.TemplateId = TEMPLATE_ID
        # 模板引數: 模板引數的個數需要與 TemplateId 對應模板的變數個數保持一致,,若無模板引數,則設定為空
        req.TemplateParamSet = [code, '1']
        # 下發手機號碼,採用 E.164 標準,+[國家或地區碼][手機號]
        req.PhoneNumberSet = [f"+86{mobile}"]
        # 使用者的 session 內容(無需要可忽略): 可以攜帶使用者側 ID 等上下文資訊,server 會原樣返回
        req.SessionContext = ""
        # 簡訊碼號擴充套件號(無需要可忽略): 預設未開通,如需開通請聯絡 [騰訊雲簡訊小助手]
        req.ExtendCode = ""
        # 國內簡訊無需填寫該項;國際/港澳臺簡訊已申請獨立 SenderId 需要填寫該欄位,預設使用公共 SenderId,無需填寫該欄位。注:月度使用量達到指定量級可申請獨立 SenderId 使用,詳情請聯絡 [騰訊雲簡訊小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。
        req.SenderId = ""
        resp = client.SendSms(req)
        # 輸出json格式的字串回包
        res = resp.to_json_string(indent=2)
        if res.get('SendStatusSet')[0].get('Code') == 'Ok':
            return True
        else:
            return False
 
    except TencentCloudSDKException as err:
        print(err)
        return False
 
 
if __name__ == '__main__':
    print(get_code(3))

傳送簡訊介面

GET - http://127.0.0.1:8000/api/v1/user/mobile/send_sms/?mobile=

views

class UserMobileView(GenericViewSet):
    @action(methods=['GET'], detail=False)
    def send_sms(self, request, *args, **kwargs):
        mobile = request.query_params.get('mobile')
        code = get_code()
        print(code)
        cache.set(f'cache_code_{mobile}', code)
        # 傳送簡訊 - 同步傳送
        # res=sms(mobile,code)
        # 返回給前端
        # if res:
        #     return APIResponse(msg='簡訊傳送成功')
        # else:
        #     return APIResponse(code=101,msg='傳送簡訊失敗,請稍後再試')
        t = Thread(target=sms, args=[mobile, code])
        t.start()
        return APIResponse(msg='簡訊已傳送')

簡訊登陸介面

POST - http://127.0.0.1:8000/api/v1/user/mul_login/sms_login/

之前寫過多方式登入,程式碼一樣,可以抽出來做成公用的

views

class UserLoginView(GenericViewSet):
    serializer_class = LoginSerializer
 
    def get_serializer_class(self):
        if self.action == 'sms_login':
            return SMSLoginSerializer
        else:
            return LoginSerializer
 
    def _login(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        token = serializer.context.get('token')
        username = serializer.context.get('username')
        icon = serializer.context.get('icon')
        return APIResponse(token=token, username=username, icon=icon)
 
    @action(methods=['POST'], detail=False)
    def multiple_login(self, request, *args, **kwargs):
        return self._login(request, *args, **kwargs)
 
    @action(methods=['POST'], detail=False)
    def sms_login(self, request, *args, **kwargs):
        return self._login(request, *args, **kwargs)

SMSLoginSerializer

這個地方一樣,序列化類也可以抽出來

class CommonLoginSerializer():
    def _get_user(self, attrs):
        raise Exception('這個方法必須被重寫')
 
    def _get_token(self, user):
        refresh = RefreshToken.for_user(user)
        return str(refresh.access_token)
 
    def _pre_data(self, token, user):
        self.context['token'] = token
        self.context['username'] = user.username
        # self.instance=user # 當前使用者,放到instance中了
        self.context['icon'] = settings.BACKEND_URL + "media/" + str(user.icon)  # 不帶 域名字首的
 
    def validate(self, attrs):
        # 1 取出使用者名稱(手機號,郵箱)和密碼
        user = self._get_user(attrs)
        # 2 如果存在:簽發token,返回
        token = self._get_token(user)
        # 3 把token,使用者名稱和icon放入context
        self._pre_data(token, user)
        return attrs
 
 
class SMSLoginSerializer(CommonLoginSerializer, serializers.Serializer):
    code = serializers.CharField()
    mobile = serializers.CharField()
 
    def _get_user(self, attrs):
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        old_code = cache.get(f'cache_code_{mobile}')
        assert old_code == code or (settings.DEBUG and code == '8888'), ValidationError('驗證碼錯誤')
        user = User.objects.filter(mobile=mobile).first()
        assert user, ValidationError('該手機號未註冊!')
        return user

簡訊註冊介面

POST - http://127.0.0.1:8000/api/v1/user/register/

views

class UserRegisterView(GenericViewSet):
    serializer_class = RegisterSerializer
 
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return APIResponse(msg='註冊成功')

RegisterSerializer

class RegisterSerializer(serializers.ModelSerializer):
    code = serializers.CharField()
 
    class Meta:
        model = User
        fields = ['mobile', 'password', 'code']
 
    def validate(self, attrs):
        code = attrs.pop("code")
        mobile = attrs.get('mobile')
        old_code = cache.get(f'cache_code_{mobile}')
        assert old_code == code or (settings.DEBUG and code == '8888'), ValidationError('驗證碼錯誤')
        attrs['username'] = mobile
        return attrs
 
 
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

課程(分類、列表、詳情)介面

相關文章