发送手机验证码

发送手机验证码

1. 利用网易云云信平台发送手机验证码

import random
import string
import time
import hashlib
from urllib import parse, request
def send_sms():
    # 请求的url
    api = 'https://api.netease.im/sms/sendcode.action'

    # 准备headers中的参数
    # 网易云信平台分配的appkey
    AppKey = '097c1bd21e9e24279517ddbe07cf8a84'
    # 最大128个字符的随机字符串
    Nonce = ''.join(random.sample(string.ascii_letters + string.digits, 20))
    # 当前UTC时间戳从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
    CurTime = str(int(time.time()))
    #appsecret
    AppSecret = '12b619be2374'
    # 校验码
    Sumstr = AppSecret + Nonce + CurTime
    sha = hashlib.sha1(Sumstr.encode())
    CheckSum = sha.hexdigest()
    # 另一种使用hash的用法。
    hash = hashlib.sha1()
    hash.update(Sumstr)
    hash.hexdigest()

    # 设置头
    headers = {
        'AppKey': AppKey,
        'Nonce' : Nonce,
        'CurTime': CurTime,
        'CheckSum': CheckSum,
        'Content-Type': 'application/x-www-form-urlencoded',
        'charset': 'utf-8'
    }

    # 准备要发送的数据,必填的只有一个手机号
    data = {
        'mobile': '18676689715',
        'templateid': '4032501'
    }
    # 把字典解析成url中传参的格式,即:mobile='18676689715'
    data = parse.urlencode(data).encode()
    # 创建request实例对象
    r = request.Request(url=api, headers=headers, data=data)
    req = request.urlopen(r)
    response = req.read()
    print(response)


if __name__ == '__main__':
    send_sms()

2. 利用云片网发送手机验证码

注意:云片网需要把自己的ip加入到IP白名单里面。发送短信的模板必须是你在云片网中配置好的。


import requests

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'

    def send_sms(self,code,mobile):
        parmas={
            "apikey":self.api_key,
            'mobile':mobile,
            'text':'您的验证码是{code}'.format(code=code)
        }

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

if __name__ == '__main__':
    yun_pian = YunPian("自己的api_key")
    yun_pian.send_sms('2018',"电话号码")

猜你喜欢

转载自blog.csdn.net/g_sangsk/article/details/80867681