阿里雲簡訊服務的使用-----獲取簡訊驗證碼

爬遍天下無敵手發表於2020-12-25

開通阿里雲簡訊服務

 

 

  • 申請簽名和模板

 

 

  • 下載pythonSDK

pip install aliyun-python-sdk-core

  • 設定AK和SK

 

 

封裝發簡訊程式碼utils/BaseView.py

  1. import json

  2.  
  3. from aliyunsdkcore.client import AcsClient

  4. from aliyunsdkcore.request import CommonRequest

  5. from syl.settings import ALY_ACCESSKEY_SECRET, ALY_ACCESSKEY_ID

  6.  
  7.  
  8. # phone = ""

  9. # phone_code = ""

  10. # data = {"code": phone_code}

  11.  
  12.  
  13. def send_sms(phone, data):

  14. # accessKeyId

  15. # accessSecret

  16. # cn-hangzhou

  17.  
  18. client = AcsClient('<ALY_ACCESSKEY_SECRET>', '<ALY_ACCESSKEY_ID>', 'cn-hangzhou')

  19.  
  20. request = CommonRequest()

  21. request.set_accept_format('json')

  22. request.set_domain('dysmsapi.aliyuncs.com')

  23. request.set_method('POST')

  24. request.set_protocol_type('https') # https | http

  25. request.set_version('2017-05-25')

  26. request.set_action_name('SendSms')

  27.  
  28. request.add_query_param('RegionId', "cn-hangzhou")

  29. request.add_query_param('PhoneNumbers', phone)

  30. request.add_query_param('SignName', "美多商城")

  31. request.add_query_param('TemplateCode', "SMS_185212884")

  32. request.add_query_param('TemplateParam', data)

  33.  
  34. response1 = client.do_action(request)

  35. # python2: print(response)

  36. res=json.loads(str(response1, encoding='utf-8'))

 

  • 簡訊傳送和驗證的邏輯

  • # verificationsapp/view.py 傳送介面 #

  1. #verificationsapp/VIEW.PY

  2.  
  3. class SendSMSCode(APIView):

  4. def post(self, request):

  5. # 獲取資料

  6. phone = request.data.get("phone")

  7. image_code = request.data.get("image_code")

  8. image_code_uuid = request.data.get("image_code_uuid")

  9. print('=====================', phone, image_code_uuid, image_code)

  10. # 驗證資料

  11. if not all([phone, image_code, image_code_uuid]):

  12. return Response({"code": 4005, "msg": "引數不全"})

  13.  
  14. # 邏輯與入庫

  15. # 3、驗證圖片驗證碼是否正確

  16. # 3.1連線redis

  17. redis_cli = get_redis_connection("img_code")

  18. # 3.2拿著uuid獲取圖片驗證碼

  19. redis_img_code = redis_cli.get(image_code_uuid).decode('utf-8')

  20. # 3.3比對redis裡的code和發來的code是否一致

  21. if image_code.lower() != redis_img_code.lower():

  22. return Response({"code": 4009, "msg": "圖片驗證碼錯誤"})

  23.  
  24. # 4、使用阿里雲傳送簡訊

  25. # 4.1準備手機驗證碼

  26. number = random.randint(100000, 999999)

  27. data = {"code": number}

  28. print(data)

  29. # 4.2使用封裝好的介面傳送簡訊

  30. send_sms(phone, data)

  31.  
  32. # 5.將簡訊驗證碼繫結並存入redis

  33. redis_cli.setex(phone, 60 * 60, number)

  34.  
  35. # 6.刪除image_code

  36. redis_cli.delete(image_code_uuid)

  37.  
  38. return Response({"code": 0, "msg": "傳送成功"})

後記

近期有很多朋友通過私信諮詢有關Python學習問題。為便於交流,點選藍色自己加入討論解答資源基地

 

相關文章