python3.7实现云之讯、聚合短信平台的短信发送
1、云之讯平台数据返回Json格式:
{'reason': '操作成功', 'result': {'sid': '17209241456456455454', 'fee': 1,
'count': 1}, 'error_code': 0}
2、聚合平台数据返回Json格式:
{"code":"000000","count":"1","create_date":"2019-09-24
16:16:30","mobile":"187024545447","msg":"OK","smsid":"0f1245454545454
144545444","uid":""}
import time
from time import sleep
import sys
from datetime import datetime
import urllib.request
import json
from urllib import parse
import uuid
import http.client
#云之讯-短信请求url
sms_yzx_url = "https://open.ucpaas.com/ol/sms/sendsms"
#云之讯-账号相关信息-应用ID
sms_yzx_appid = "93649dcfexxxxxxxxxxxxxxxxxx"
#云之讯-账号相关信息-用户sid
sms_yzx_account_Sid = "eb6fxxxxxxxxxxxxxxxx"
#云之讯-账号相关信息-密钥
sms_yzx_auth_token = "027xxxxxxxxxxxxxxxx"
#云之讯-账号相关信息-短信模板
sms_yzx_templateid = "475631"
#聚合数据-短信平台-请求地址
sms_juhe_url = "http://v.juhe.cn/sms/send"
#聚合数据-短信平台-短信模板
sms_juhe_templateid = "17488"
#聚合数据-短信平台-密钥
sms_juhe_auth_token = "40xxxxxxxxxxxxxxxx"
#短信服务平台(0:云之讯短信 1: 聚合短信)
sms_service_choice = 0
date = datetime.now()
print(date.strftime("%Y-%m-%d %H:%M:%S"))
def juhe_sendsms(appkey, mobile, tpl_id, tpl_value):
sendurl = sms_juhe_url # 短信发送的URL,无需修改
params = 'key=%s&mobile=%s&tpl_id=%s&tpl_value=%s'%(appkey, mobile, tpl_id, parse.quote(tpl_value)) # 组合参数
wp = urllib.request.urlopen(sendurl + "?" + params)
content = wp.read() # 获取接口返回内容
result = json.loads(content)
# print(result)
if result:
error_code = result['error_code']
if error_code == 0:
# 发送成功
smsid = result['result']['sid']
print("sendsms success,smsid: %s" % (smsid) )
else:
# 发送失败
print( "sendsms error :(%s), %s" % (error_code, result['reason']) )
else:
# 请求失败
print( "request sendsms error" )
def yzx_sendsms(to, params, temp_id):
# @param to 手机号码
# @param params 内容数据 格式为数组 例如:{'12','34'},如不需替换请填 ''
# @param temp_id 模板Id
data = {
"sid": sms_yzx_account_Sid,
"token": sms_yzx_auth_token,
"appid": sms_yzx_appid,
"templateid": temp_id,
"param": params,
"mobile": to,
}
# 将字典转换为JSON字符串
json_data = json.dumps(data)
#print(json_data)
#发送请求头
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=utf-8',
}
connect = http.client.HTTPConnection('open.ucpaas.com')
# 发送请求
connect.request(method='POST', url=sms_yzx_url, body=json_data, headers=headers)
# 获取响应
resp = connect.getresponse()
# print(resp)
# 响应内容
result = resp.read().decode('utf-8')
# print(result)
result = json.loads(result)
# 发送成功
# print(result)
# 如果发送短信成功,返回的字典数据中code字段的值为"000000"
if result["code"] == "000000":
# 返回0 表示发送短信成功
smsid = result['smsid']
print("sendsms success,smsid: %s, %s"% (smsid, result['msg']))
return 0
else:
# 返回-1 表示发送失败
print("sendsms error :(%s), %s"% (result['code'], result['msg']))
return -1
def main():
mobile = '182xxxx' # 短信接受者的手机号码
tpl_value = '#code#=4567'
juhe_sendsms(sms_juhe_auth_token, mobile, sms_juhe_templateid, tpl_value) # 请求发送短信
yzx_sendsms(mobile, ['1234'], sms_yzx_templateid)
if __name__ == '__main__':
main()