對接短信驗證

使用雲片網進行短信驗證
  1.註冊雲片網帳號
  2.開發者信息認證(審覈經過)
  3.新建簽名(審覈經過)
  4.設置模板(審覈經過)
  5.查看api文檔,發送短信形式有不少,國內國外,單條多條等,以國內單條爲例。
  6.官方文檔中面向Python的代碼寫的比較麻煩,我們能夠本身寫json

    ###yunpian.pyapi

import requests
import json

class YunPian(object):
    def __init__(self,api_key):
        self.api_key = api_key
        self.single_send_url = 'https://sms.yunpian.com/v2/sms/single_send.json '  # 此地址可在api文檔裏查看

    def send_sms(self,code,mobile):
        parmas = {
            'apikey':self.api_key,
            'mobile':mobile,
            'text':'【暮雪生鮮】您的驗證碼是{code},非本人請可忽略'%code
        }

        response = requests.post(self.single_send_url,data=parmas)
        re_dict = json.loads(response.text)
        print(re_dict)

if __name__ == '__main__':  # 測試用
    yun_pian = YunPian('d6c4ddf50ab3131d46a1c662b94e')  # 將apikey傳入
    yun_pian.send_sms('4651','13572551532')  # 4651就是驗證碼,135...爲要發送的手機號

 

    ### views.pyapp

class SmsCodeViewset(CreateModelMixin,GenericViewSet):
    '''
    短信驗證碼
    '''
    serializer_class = SmsSerializer

    def generate_code(self):
        '''
        生成四位數的驗證碼
        '''
        seeds = '1234567890'
        random_str = []
        for i in range(4):
            random_str.append(choice(seeds))
        self.code = ''.join(random_str)

    def create(self, request, *args, **kwargs):
        '''
        發送驗證碼
        '''
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 如下爲重載內容
        mobile = serializer.validated_data['mobile']
        self.generate_code()  # 調用生成隨機驗證碼
        yun_pian = YunPian(APIKEY)  # 實例化,將settings裏配置的APIKEY傳入
        print('code:::',self.code,mobile)

        sms_status = yun_pian.send_sms(self.code,mobile)  # 接收雲片網發來的狀態碼,0表成功,其餘表明錯誤
        if sms_status['code'] != 0:
            return Response({
                'mobile':sms_status['msg']
            },status=status.HTTP_400_BAD_REQUEST)
        else:
            code_recod = models.VerifyCode(code=self.code, mobile=mobile)
            code_recod.save()
            return Response({
                'mobile':mobile
            },status=status.HTTP_201_CREATED)

  7.將本地ip添加到系統設置裏的白名單裏,不然系統不會讓你發送信息的,,本地ip可直接進百度搜索‘本地ip’dom

相關文章
相關標籤/搜索