5、关键代码片段
5.1、调用BatchSendSms接口发送短信
Copied!
@staticmethod
def send_sms(ak, sk):
api_address = "https://smsapi.cn-north-4.myhuaweicloud.com:8443/sms/batchSendSms/v1"
form_data = urllib.parse.urlencode({
'from': "8824110605***",
'to': "+86137****3774,+86137****3776",
'templateId': "1d18a7f4e1b84f6c8fc1546b48b3baea",
'templateParas': "[\"123\",\"456\",\"789\"]",
'statusCallback': "https://test/report"
}).encode('ascii')
parsed_url = urlparse(api_address)
headers = {
"Content-type": "application/x-www-form-urlencoded",
"User-Agent": "huaweicloud-usdk-python/3.0",
"Accept": "application/json",
"Host": parsed_url.netloc
}
request = requests.Request(
method="POST",
url=api_address,
headers=headers,
data=form_data
)
request = BatchSendSms.sign_request(request, ak, sk)
return BatchSendSms.post_message(request)
@staticmethod
def sign_request(request, ak, sk):
parsed_url = urlparse(request.url)
sdk_request = SdkRequest(method=request.method,
schema=parsed_url.scheme,
host=parsed_url.netloc,
resource_path=parsed_url.path,
uri=parsed_url.path,
header_params=request.headers,
query_params=[],
body=request.data,
signing_algorithm=SigningAlgorithm.HMAC_SHA256)
"""The signature algorithm uses the AK and SK signature algorithms provided by HUAWEI CLOUD IAM and API
Gateway. Signature algorithm implementation. The capabilities provided by the SDK are used here. Developers
can also use the signature capability provided by HUAWEI CLOUD APIG. For details, see the following website:
https://support.huaweicloud.com/devg-apisign/api-sign-sdk-python.html For the signature operation of an
interface, the signature must contain the body."""
self = Credentials(ak, sk)
signer_cls = self._SIGNER_CASE.get(SigningAlgorithm.HMAC_SHA256)
if not signer_cls:
return None
sdk_request = signer_cls(self).sign(sdk_request)
for header_param in sdk_request.header_params:
request.headers[header_param] = sdk_request.header_params[header_param]
return request
5.2、调用BatchSendDiffSms接口发送分批短信
Copied!
@staticmethod
def send_sms_using_diff(ak, sk):
api_address = "https://smsapi.cn-north-4.myhuaweicloud.com:8443/sms/batchSendDiffSms/v1"
"""
Construct the message body of the sample code.
For details about how to construct a body, see the API description.
Sample is:
{
"from": "8824110605***",
"statusCallback": "https://test/report",
"smsContent": [{
"to": ["+86137****3774", "+86137****3775"],
"templateId": "1d18a7f4e1b84f6c8fc1546b48b3baea",
"templateParas": ["1", "23", "e"]
},
{
"to": ["+86137****3777"],
"templateId": "7824a51b3cc34976919a5418f637d0fb",
"templateParas": ["4", "5", "6"]
}
]
}
"""
json_data = json.dumps({'from': "8824110605***",
'statusCallback': "https://test/report",
'smsContent': [
{'to': ["+86137****3774", "+86137****3775"],
'templateId': "1d18a7f4e1b84f6c8fc1546b48b3baea",
'templateParas': ["1", "23", "e"],
},
{'to': ["+86137****3777"],
'templateId': "7824a51b3cc34976919a5418f637d0fb",
'templateParas': ["4", "5", "6"],
}]
}).encode('ascii')
parsed_url = urlparse(api_address)
headers = {
"Content-type": "application/json;charset=utf8",
"User-Agent": "huaweicloud-usdk-python/3.0",
"Accept": "application/json",
"Host": parsed_url.netloc
}
request = requests.Request(
method="POST",
url=api_address,
headers=headers,
data=json_data
)
request = BatchSendDiffSms.sign_request(request, ak, sk)
return BatchSendDiffSms.post_message(request)
@staticmethod
def sign_request(request, ak, sk):
parsed_url = urlparse(request.url)
sdk_request = SdkRequest(method=request.method,
schema=parsed_url.scheme,
host=parsed_url.netloc,
resource_path=parsed_url.path,
uri=parsed_url.path,
header_params=request.headers,
query_params=[],
body=request.data,
signing_algorithm=SigningAlgorithm.HMAC_SHA256)
"""The signature algorithm uses the AK and SK signature algorithms provided by HUAWEI CLOUD IAM and API
Gateway. Signature algorithm implementation. The capabilities provided by the SDK are used here. Developers
can also use the signature capability provided by HUAWEI CLOUD APIG. For details, see the following website:
https://support.huaweicloud.com/devg-apisign/api-sign-sdk-python.html For the signature operation of an
interface, the signature must contain the body."""
self = Credentials(ak, sk)
signer_cls = self._SIGNER_CASE.get(SigningAlgorithm.HMAC_SHA256)
if not signer_cls:
return None
sdk_request = signer_cls(self).sign(sdk_request)
for header_param in sdk_request.header_params:
request.headers[header_param] = sdk_request.header_params[header_param]
return request
6、运行结果
发送短信(BatchSendSms)
Copied!
{
"result": [{
"total": 1,
"originTo": "+86137****3774",
"createTime": "2024-12-12T07:37:35Z",
"from": "8824110605***",
"smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_728530",
"countryId": "CN",
"status": "000000"
}, {
"total": 1,
"originTo": "+86137****3776",
"createTime": "2024-12-12T07:37:35Z",
"from": "8824110605***",
"smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_728531",
"countryId": "CN",
"status": "000000"
}],
"code": "000000",
"description": "Success"
}
发送分批短信(BatchSendDiffSms)
Copied!
{
"result": [{
"total": 1,
"originTo": "+86137****3774",
"createTime": "2024-12-12T07:38:36Z",
"from": "8824110605***",
"smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_731440",
"countryId": "CN",
"status": "000000"
}, {
"total": 1,
"originTo": "+86137****3775",
"createTime": "2024-12-12T07:38:36Z",
"from": "8824110605***",
"smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_731441",
"countryId": "CN",
"status": "000000"
}, {
"total": 1,
"originTo": "+86137****3777",
"createTime": "2024-12-12T07:38:36Z",
"from": "8824110605***",
"smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_731442",
"countryId": "CN",
"status": "000000"
}],
"code": "000000",
"description": "Success"
}
1、功能介绍
什么是华为云消息&短信(Message & SMS)服务?
消息&短信(Message & SMS)是华为云携手全球多家优质运营商和渠道,为企业用户(不包括个体工商户、个人独资企业、合伙企业等非法人主体或组织)提供单发、群发短信服务,同时可接收用户回复短信。
您将学到什么?
该示例展示了如何使用Python调用消息&短信(Message & SMS)服务的API发送短信。
2、开发时序图
3、前置条件
4、接口参数说明
关于接口参数的详细说明可参见:
a.发送短信
b.发送分批短信
5、关键代码片段
5.1、调用BatchSendSms接口发送短信
@staticmethod def send_sms(ak, sk): # This api_address of this example is of Beijing 4. Replace it with the actual value. api_address = "https://smsapi.cn-north-4.myhuaweicloud.com:8443/sms/batchSendSms/v1" # Construct the message body of the sample code. # For details about how to construct a body, see the API description. form_data = urllib.parse.urlencode({ 'from': "8824110605***", 'to': "+86137****3774,+86137****3776", 'templateId': "1d18a7f4e1b84f6c8fc1546b48b3baea", 'templateParas': "[\"123\",\"456\",\"789\"]", 'statusCallback': "https://test/report" }).encode('ascii') parsed_url = urlparse(api_address) headers = { "Content-type": "application/x-www-form-urlencoded", "User-Agent": "huaweicloud-usdk-python/3.0", "Accept": "application/json", "Host": parsed_url.netloc } request = requests.Request( method="POST", url=api_address, headers=headers, data=form_data ) # Signature operation of the batchSendSms interface request = BatchSendSms.sign_request(request, ak, sk) # send messages return BatchSendSms.post_message(request) @staticmethod def sign_request(request, ak, sk): # The SDK signature algorithm is invoked. The original request needs to be converted into an SDK request for signature. parsed_url = urlparse(request.url) sdk_request = SdkRequest(method=request.method, schema=parsed_url.scheme, host=parsed_url.netloc, resource_path=parsed_url.path, uri=parsed_url.path, header_params=request.headers, query_params=[], body=request.data, signing_algorithm=SigningAlgorithm.HMAC_SHA256) """The signature algorithm uses the AK and SK signature algorithms provided by HUAWEI CLOUD IAM and API Gateway. Signature algorithm implementation. The capabilities provided by the SDK are used here. Developers can also use the signature capability provided by HUAWEI CLOUD APIG. For details, see the following website: https://support.huaweicloud.com/devg-apisign/api-sign-sdk-python.html For the signature operation of an interface, the signature must contain the body.""" self = Credentials(ak, sk) signer_cls = self._SIGNER_CASE.get(SigningAlgorithm.HMAC_SHA256) if not signer_cls: return None sdk_request = signer_cls(self).sign(sdk_request) for header_param in sdk_request.header_params: request.headers[header_param] = sdk_request.header_params[header_param] return request
5.2、调用BatchSendDiffSms接口发送分批短信
@staticmethod def send_sms_using_diff(ak, sk): # This api_address of this example is of Beijing 4. Replace it with the actual value. api_address = "https://smsapi.cn-north-4.myhuaweicloud.com:8443/sms/batchSendDiffSms/v1" """ Construct the message body of the sample code. For details about how to construct a body, see the API description. Sample is: { "from": "8824110605***", "statusCallback": "https://test/report", "smsContent": [{ "to": ["+86137****3774", "+86137****3775"], "templateId": "1d18a7f4e1b84f6c8fc1546b48b3baea", "templateParas": ["1", "23", "e"] }, { "to": ["+86137****3777"], "templateId": "7824a51b3cc34976919a5418f637d0fb", "templateParas": ["4", "5", "6"] } ] } """ json_data = json.dumps({'from': "8824110605***", 'statusCallback': "https://test/report", 'smsContent': [ {'to': ["+86137****3774", "+86137****3775"], 'templateId': "1d18a7f4e1b84f6c8fc1546b48b3baea", 'templateParas': ["1", "23", "e"], }, {'to': ["+86137****3777"], 'templateId': "7824a51b3cc34976919a5418f637d0fb", 'templateParas': ["4", "5", "6"], }] }).encode('ascii') parsed_url = urlparse(api_address) headers = { "Content-type": "application/json;charset=utf8", "User-Agent": "huaweicloud-usdk-python/3.0", "Accept": "application/json", "Host": parsed_url.netloc } request = requests.Request( method="POST", url=api_address, headers=headers, data=json_data ) # Signature operation of the batchSendDiffSms interface request = BatchSendDiffSms.sign_request(request, ak, sk) # send messages return BatchSendDiffSms.post_message(request) @staticmethod def sign_request(request, ak, sk): # The SDK signature algorithm is invoked. The original request needs to be converted into an SDK request for signature. parsed_url = urlparse(request.url) sdk_request = SdkRequest(method=request.method, schema=parsed_url.scheme, host=parsed_url.netloc, resource_path=parsed_url.path, uri=parsed_url.path, header_params=request.headers, query_params=[], body=request.data, signing_algorithm=SigningAlgorithm.HMAC_SHA256) """The signature algorithm uses the AK and SK signature algorithms provided by HUAWEI CLOUD IAM and API Gateway. Signature algorithm implementation. The capabilities provided by the SDK are used here. Developers can also use the signature capability provided by HUAWEI CLOUD APIG. For details, see the following website: https://support.huaweicloud.com/devg-apisign/api-sign-sdk-python.html For the signature operation of an interface, the signature must contain the body.""" self = Credentials(ak, sk) signer_cls = self._SIGNER_CASE.get(SigningAlgorithm.HMAC_SHA256) if not signer_cls: return None sdk_request = signer_cls(self).sign(sdk_request) for header_param in sdk_request.header_params: request.headers[header_param] = sdk_request.header_params[header_param] return request
6、运行结果
发送短信(BatchSendSms)
{ "result": [{ "total": 1, "originTo": "+86137****3774", "createTime": "2024-12-12T07:37:35Z", "from": "8824110605***", "smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_728530", "countryId": "CN", "status": "000000" }, { "total": 1, "originTo": "+86137****3776", "createTime": "2024-12-12T07:37:35Z", "from": "8824110605***", "smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_728531", "countryId": "CN", "status": "000000" }], "code": "000000", "description": "Success" }
发送分批短信(BatchSendDiffSms)
{ "result": [{ "total": 1, "originTo": "+86137****3774", "createTime": "2024-12-12T07:38:36Z", "from": "8824110605***", "smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_731440", "countryId": "CN", "status": "000000" }, { "total": 1, "originTo": "+86137****3775", "createTime": "2024-12-12T07:38:36Z", "from": "8824110605***", "smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_731441", "countryId": "CN", "status": "000000" }, { "total": 1, "originTo": "+86137****3777", "createTime": "2024-12-12T07:38:36Z", "from": "8824110605***", "smsMsgId": "e25cee59-1d72-4aeb-adeb-3faf446f543c_731442", "countryId": "CN", "status": "000000" }], "code": "000000", "description": "Success" }
7、参考
本示例的代码工程仅用于简单演示,实际开发过程中应严格遵循开发指南。访问以下链接可以获取详细信息:开发指南