阿里云短信验证码接口的使用 安装python核心SDK库(推荐用新版) 旧版:pip install aliyun-python-sdk-core3 新版:pip install aliyun-python-sdk-core-v3 创建签名 创建AccessKey
AccessKey ID与 AccessKey Secret后面会用到
搜索阿里云的短信服务 获取官方提供的demo官方提供的DEMO如下
from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest client = AcsClient(\'<accessKeyId>\', \'<accessSecret>\', \'default\') 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\', "default") request.add_query_param(\'PhoneNumbers\', "接收验证码的手机号") request.add_query_param(\'SignName\', "你的签名名称") request.add_query_param(\'TemplateCode\', "你的模版CODE") response = client.do_action(request) # python2: print(response) print(str(response, encoding = \'utf-8\')) 将代码写成一个公共方法以便我们使用 # checkCode.py from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest def send_sms(template, mobile): client = AcsClient(\'你的AccessKey ID\', \'你的Access Key Secret\', \'default\') 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\') # set_action_name 选择调用的接口的名称,如:SendSms,SendBatchSms等 request.set_action_name(\'SendSms\') request.add_query_param(\'RegionId\', "default") # 98A66994-3DF4-4FA5-A33F-CCB36EB599D0 # request.add_query_param(\'RegionId\', "cn-hangzhou") request.add_query_param(\'PhoneNumbers\', mobile) # 发送的人 request.add_query_param(\'SignName\', "你的签名名称") # 签名 request.add_query_param(\'TemplateCode\', "你的模板编号") # 模板编号 request.add_query_param(\'TemplateParam\', f"{template}") # 发送验证码内容 response = client.do_action_with_exception(request) # response = client.do_action(request) # # python2: print(response) # print(str(response, encoding=\'utf-8\')) return response 使用公共方法 code = "%06d" % random.randint(0, 999999) # 将验证码存入session request.session[\'sms\'] = code template = { \'code\': code, } res = send_sms(template, mobile) # res_dict = json.loads(res) if res_dict.get(\'Message\') == \'OK\' and res_dict.get(\'Code\') == \'OK\': return APIResponse(\'ok\') else: return APIResponse(status=0, msg=\'error\')