Python3.9.13 Django4.0 调用腾讯云短信API,发送短信代码

# -*- coding: utf-8 -*-

# 发送腾讯云短信  登录 - 腾讯云
import json
import random
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models


# 获取随机6位数
def captcha():
    captcha = ''
    for i in range(6):
        now_number = str(random.randint(0, 9))
        captcha += now_number
    return captcha


class TencentSMS(object):
    # 初始化数据
    def __init__(self):
        self.secretId = "****你自己的secretId *****"
        self.secretKey = "****你自己的secretKey *****"
        self.SmsSdkAppId = "****你自己的SmsSdkAppId *****"
        self.SignName = "****你自己的SignName *****"
        self.TemplateId = "****你自己的TemplateId *****"

    def send_sms(self, mobile):
        try:
            # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
            # 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            cred = credential.Credential(self.secretId, self.secretKey)
            # 实例化一个http选项,可选的,没有特殊需求可以跳过
            httpProfile = HttpProfile()
            httpProfile.endpoint = "sms.tencentcloudapi.com"
            # 生成随机6位数
            sms_code = captcha()
            # 实例化一个client选项,可选的,没有特殊需求可以跳过
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            # 实例化要请求产品的client对象,clientProfile是可选的
            client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

            # 实例化一个请求对象,每个接口都会对应一个request对象
            req = models.SendSmsRequest()
            params = {
                "PhoneNumberSet": mobile,
                "SmsSdkAppId": self.SmsSdkAppId,
                "SignName": self.SignName,
                "TemplateId": self.TemplateId,
                "TemplateParamSet": [sms_code]
            }
            req.from_json_string(json.dumps(params))

            # 返回的resp是一个SendSmsResponse的实例,与请求对象对应
            resp = client.SendSms(req)
            # 输出json格式的字符串回包
            print(resp.to_json_string())

        except TencentCloudSDKException as err:
            print(err)


if __name__ == "__main__":
    tencentSMS = TencentSMS()
    tencentSMS.send_sms(["****你自己的手机号*****"])

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值