阿里雲短信驗證


一 阿里雲短信平台配置

1 創建accesskey

1) 獲取accesskey

2) 創建子key

3) 拿到子key

2 添加簽名

3 添加模板

4 保證賬戶有余額

5 個人用戶驗證碼系統默認限制頻率

# 同一個手機號
1分鍾內短信發送條數不超過:1

1小時內短信發送條數不超過:5

1個自然日內短信發送條數不超過:10

二使用阿里雲短信

1 安裝sdk

1)安裝

pip install aliyun-python-sdk-core

2)自己做一下測試

# 測試的時候要把你的accesskeyid,accessSecret,簽名內容,模板code,短信內容(json格式)填入

2 封裝到我們的項目中

1)libs/ali_sms/ali_sms_hander.py

#!/usr/bin/env python
#coding=utf-8

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import json,random
from utils.logging import logger
from django.conf import settings

#-------阿里sms--------
# ACCESS_KEY_SECRET_SMS = ACCESS_KEY_SECRET_SMS
# ACCESS_KEY_ID_SMS = ACCESS_KEY_ID_SMS
# REGIONID = "cn-beijing"
# SIGN_NAME = "路飛學城"
# TEMPLATE_CODE = "SMS_153790638"
#------end--------------



def send_sms(mobile,code):
    client = AcsClient(settings.ACCESS_KEY_ID_SMS, settings.ACCESS_KEY_SECRET_SMS, settings.REGIONID)
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https') # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    request.add_query_param('RegionId', settings.REGIONID)
    request.add_query_param('PhoneNumbers',str(mobile))
    request.add_query_param('SignName', settings.SIGN_NAME)
    request.add_query_param('TemplateCode', settings.TEMPLATE_CODE)
    TemplateParam = json.dumps({"code":code})
    request.add_query_param('TemplateParam', TemplateParam)
    try:
        response = client.do_action_with_exception(request)
        response = json.loads(response)
        print(response)
    except Exception as e:
        logger.error(f'短信發送失敗:{mobile},{e}')
        return False
    if response and response.get('Code') == 'OK':
        return True
    
    logger.error(f"短信發送失敗:{mobile},{response.get('Message')}")
    return False

def get_code():
    code = ''
    for i in range(4):
        code += str(random.randint(0, 9))
    return code


2)api調用

class SMSAPIView(APIView):
    def post(self,request,*args,**kwargs):

        mobile = request.data.get('mobile')
        if not mobile or not re.match(r'^1[3-9][0-9]{9}$', mobile):
            return APIResponse(1, '手機號有誤')

        # 產生驗證碼
        code = get_code()

        # 通知第三方發送短信
        result = send_sms(mobile,code)

        # 失敗:
        if not result:
            return APIResponse(1,'短信發送失敗')
        # 成功:
        # todo: 成功后存到redis里面
        return APIResponse(0,'短信發送成功')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM