短信
短信接入示例
更新时间: 2023/04/06 11:49:15
功能概述
短信服务(Short Message Service)是网易网易云信为用户提供的一种通信服务的能力,目前支持验证码类短信、通知类短信、运营类短信、语音类短信、国际短信等是事务性短信。
短信接口为标准的HTTP接口,以下示例包含了常见语言如何发起HTTP请求,帮助开发者更高效的接入短信接口。
注:最重要的四个参数,务必参考计算示例服务器API,否则会出现{"desc":"bad http header","code":414}
参数 | 参数说明 |
---|---|
AppKey | 云信控制台上您的应用对应的appkey |
Nonce | 随机数(最大长度128个字符) |
CurTime | 当前UTC时间戳,从1970年1月1日0点0 分0 秒开始到现在的秒数(String) |
CheckSum | SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串,进行SHA1哈希计算,转化成16进制字符(String,小写) |
Appkey,Appsecret获取步骤:
- 成为云信开发者。
- 登录云信控制台。
- 创建应用。
- 打开App Key管理。
CheckSum计算示例:
Java
import java.security.MessageDigest;
public class CheckSumBuilder {
// 计算并获取CheckSum
public static String getCheckSum(String appSecret, String nonce, String curTime) {
return encode("sha1", appSecret + nonce + curTime);
}
// 计算并获取md5值
public static String getMD5(String requestBody) {
return encode("md5", requestBody);
}
private static String encode(String algorithm, String value) {
if (value == null) {
return null;
}
try {
MessageDigest messageDigest
= MessageDigest.getInstance(algorithm);
messageDigest.update(value.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
Node.js
const { SHA1 } = require("crypto-js");
function randString(x) {
let s = "";
while (s.length < x && x > 0) {
const v = Math.random() < 0.5 ? 32 : 0;
s += String.fromCharCode(
Math.round(Math.random() * (122 - v - (97 - v)) + (97 - v))
);
}
return s;
}
const [Nonce, CurTime] = [randString(20), new Date().getTime().toString().slice(0, 10)]
function CheckSum(AppSecret, Nonce, CurTime) {
return SHA1(AppSecret + Nonce + CurTime);
}
Python
import hashlib
import time
# 随机数
nonce = hashlib.new('sha512', str(time.time()).encode("utf-8")).hexdigest()
# 获取当前时间戳
curtime = str(int(time.time()))
# 网易云信的 App Secret
AppSecret = ""
check_sum = hashlib.sha1((AppSecret + nonce + curtime).encode("utf-8")).hexdigest()
print(check_sum)
短信URL请求:(务必请将您创建的模板和对应的URL请求对应上,否则会出现404错误) 管理后台创建的模板分为:
- 通知类短信,请求的URL(https://api.netease.im/sms/sendtemplate.action )
- 运营类短信,请求的URL(https://api.netease.im/sms/sendtemplate.action )
- 验证码短信,请求的URL(https://api.netease.im/sms/sendcode.action )
Java-发送短信/语音短信验证码
package com.netease.code;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.netease.checksum.CheckSumBuilder;
/**
* 发送验证码
* @author liuxuanlin
*
*/
public class SendCode {
//发送验证码的请求路径URL
private static final String
SERVER_URL="https://api.netease.im/sms/sendcode.action";
//网易云信分配的账号,请替换你在管理后台应用下申请的Appkey
private static final String
APP_KEY="fd460d34e786e7754e505bc4fab0f027";
//网易云信分配的密钥,请替换你在管理后台应用下申请的appSecret
private static final String APP_SECRET="xxxxxxxx";
//随机数
private static final String NONCE="123456";
//短信模板ID
private static final String TEMPLATEID="3057527";
//手机号
private static final String MOBILE="13888888888";
//验证码长度,范围4~10,默认为4
private static final String CODELEN="6";
public static void main(String[] args) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
String curTime = String.valueOf((new Date()).getTime() / 1000L);
/*
* 参考计算CheckSum的java代码,在上述文档的参数列表中,有CheckSum的计算文档示例
*/
String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);
// 设置请求的header
httpPost.addHeader("AppKey", APP_KEY);
httpPost.addHeader("Nonce", NONCE);
httpPost.addHeader("CurTime", curTime);
httpPost.addHeader("CheckSum", checkSum);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 设置请求的的参数,requestBody参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
/*
* 1.如果是模板短信,请注意参数mobile是有s的,详细参数配置请参考“发送模板短信文档”
* 2.参数格式是jsonArray的格式,例如 "['13888888888','13666666666']"
* 3.params是根据你模板里面有几个参数,那里面的参数也是jsonArray格式
*/
nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));
nvps.add(new BasicNameValuePair("mobile", MOBILE));
nvps.add(new BasicNameValuePair("codeLen", CODELEN));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
// 执行请求
HttpResponse response = httpClient.execute(httpPost);
/*
* 1.打印执行结果,打印结果一般会200、315、403、404、413、414、500
* 2.具体的code有问题的可以参考官网的Code状态表
*/
System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
}
}
Java-发送通知类和运营类短信
package com.netease.code;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.netease.checksum.CheckSumBuilder;
/**
* 发送模板短信请求
* @author liuxuanlin
*
*/
public class SendCode {
//发送验证码的请求路径URL
private static final String
SERVER_URL="https://api.netease.im/sms/sendtemplate.action";
//网易云信分配的账号,请替换你在管理后台应用下申请的Appkey
private static final String
APP_KEY="fd460d34e786e7754e505bc4fab0f027";
//网易云信分配的密钥,请替换你在管理后台应用下申请的appSecret
private static final String APP_SECRET="xxxxxxxx";
//随机数
private static final String NONCE="123456";
//短信模板ID
private static final String TEMPLATEID="3057527";
//手机号,接收者号码列表,JSONArray格式,限制接收者号码个数最多为100个
private static final String MOBILES="['13888888888','13666666666']";
//短信参数列表,用于依次填充模板,JSONArray格式,每个变量长度不能超过30字,对于不包含变量的模板,不填此参数表示模板即短信全文内容
private static final String PARAMS="['xxxx','xxxx']";
public static void main(String[] args) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
String curTime = String.valueOf((new Date()).getTime() / 1000L);
/*
* 参考计算CheckSum的java代码,在上述文档的参数列表中,有CheckSum的计算文档示例
*/
String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);
// 设置请求的header
httpPost.addHeader("AppKey", APP_KEY);
httpPost.addHeader("Nonce", NONCE);
httpPost.addHeader("CurTime", curTime);
httpPost.addHeader("CheckSum", checkSum);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 设置请求的的参数,requestBody参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
/*
* 1.如果是模板短信,请注意参数mobile是有s的,详细参数配置请参考“发送模板短信文档”
* 2.参数格式是jsonArray的格式,例如 "['13888888888','13666666666']"
* 3.params是根据你模板里面有几个参数,那里面的参数也是jsonArray格式
*/
nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));
nvps.add(new BasicNameValuePair("mobiles", MOBILES));
nvps.add(new BasicNameValuePair("params", PARAMS));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
// 执行请求
HttpResponse response = httpClient.execute(httpPost);
/*
* 1.打印执行结果,打印结果一般会200、315、403、404、413、414、500
* 2.具体的code有问题的可以参考官网的Code状态表
*/
System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
}
}
Jar包下载
- [org.apache.http.HttpResponse]
- [org.apache.http.NameValuePair]
- [org.apache.http.message.BasicNameValuePair]
- [org.apache.http.util.EntityUtils]
- [org.apache.http.client.entity.UrlEncodedFormEntity]
- [org.apache.http.client.methods.HttpPost]
- [org.apache.http.impl.client.DefaultHttpClient]
PHP-验证码及通知运营类短信
<?php
/**
* 发送模板短信
* @author chensheng
***/
//使用示例
require('./ServerAPI.php');
//网易云信分配的账号,请替换你在管理后台应用下申请的Appkey
$AppKey = 'fd460d34e786e7754e505bc4fab0f027';
//网易云信分配的账号,请替换你在管理后台应用下申请的appSecret
$AppSecret = 'xxxxxxxx';
$p = new ServerAPI($AppKey,$AppSecret,'fsockopen'); //fsockopen伪造请求
//发送短信验证码
print_r( $p->sendSmsCode('6272','13888888888','','5') );
//发送模板短信
print_r( $p->sendSMSTemplate('6272',array('13888888888','13666666666'),array('xxxx','xxxx' )));
?>
<?php
/**
* 网易云信server API 简单实例
* Class ServerAPI
* @author chensheng dengyuan
* @created date 2018-02-02 13:45
*
*
***/
class ServerAPI
{
public $AppKey; //开发者平台分配的AppKey
public $AppSecret; //开发者平台分配的AppSecret,可刷新
public $Nonce; //随机数(最大长度128个字符)
public $CurTime; //当前UTC时间戳,从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
public $CheckSum; //SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串,进行SHA1哈希计算,转化成16进制字符(String,小写)
const HEX_DIGITS = "0123456789abcdef";
/**
* 参数初始化
* @param $AppKey
* @param $AppSecret
* @param $RequestType [选择php请求方式,fsockopen或curl,若为curl方式,请检查php配置是否开启]
*/
public function __construct($AppKey, $AppSecret, $RequestType = 'curl')
{
$this->AppKey = $AppKey;
$this->AppSecret = $AppSecret;
$this->RequestType = $RequestType;
}
/**
* API checksum校验生成
* @param void
* @return $CheckSum(对象私有属性)
*/
public function checkSumBuilder()
{
//此部分生成随机字符串
$hex_digits = self::HEX_DIGITS;
$this->Nonce;
for ($i = 0; $i < 128; $i++) { //随机字符串最大128个字符,也可以小于该数
$this->Nonce .= $hex_digits[rand(0, 15)];
}
$this->CurTime = (string)(time()); //当前时间戳,以秒为单位
$join_string = $this->AppSecret . $this->Nonce . $this->CurTime;
$this->CheckSum = sha1($join_string);
//print_r($this->CheckSum);
}
/**
* 将json字符串转化成php数组
* @param $json_str
* @return $json_arr
*/
public function json_to_array($json_str)
{
if (is_array($json_str) || is_object($json_str)) {
$json_str = $json_str;
} else if (is_null(json_decode($json_str))) {
$json_str = $json_str;
} else {
$json_str = strval($json_str);
$json_str = json_decode($json_str, true);
}
$json_arr = array();
foreach ($json_str as $k => $w) {
if (is_object($w)) {
$json_arr[$k] = $this->json_to_array($w); //判断类型是不是object
} else if (is_array($w)) {
$json_arr[$k] = $this->json_to_array($w);
} else {
$json_arr[$k] = $w;
}
}
return $json_arr;
}
/**
* 使用CURL方式发送post请求
* @param $url [请求地址]
* @param $data [array格式数据]
* @return $请求返回结果(array)
*/
public function postDataCurl($url, $data)
{
$this->checkSumBuilder(); //发送请求前需先生成checkSum
$timeout = 5000;
$http_header = array(
'AppKey:' . $this->AppKey,
'Nonce:' . $this->Nonce,
'CurTime:' . $this->CurTime,
'CheckSum:' . $this->CheckSum,
'Content-Type:application/x-www-form-urlencoded;charset=utf-8'
);
//print_r($http_header);
// $postdata = '';
$postdataArray = array();
foreach ($data as $key => $value) {
array_push($postdataArray, $key . '=' . urlencode($value));
}
$postdata = join('&', $postdataArray);
// var_dump($postdata);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $http_header);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //处理http证书问题
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (false === $result) {
$result = curl_errno($ch);
}
curl_close($ch);
return $this->json_to_array($result);
}
/**
* 使用FSOCKOPEN方式发送post请求
* @param $url [请求地址]
* @param $data [array格式数据]
* @return $请求返回结果(array)
*/
public function postDataFsockopen($url, $data)
{
$this->checkSumBuilder();//发送请求前需先生成checkSum
$postdata = '';
foreach ($data as $key => $value) {
$postdata .= ($key . '=' . urlencode($value) . '&');
}
// building POST-request:
$URL_Info = parse_url($url);
if (!isset($URL_Info["port"])) {
$URL_Info["port"] = 80;
}
$request = '';
$request .= "POST " . $URL_Info["path"] . " HTTP/1.1\r\n";
$request .= "Host:" . $URL_Info["host"] . "\r\n";
$request .= "Content-type: application/x-www-form-urlencoded;charset=utf-8\r\n";
$request .= "Content-length: " . strlen($postdata) . "\r\n";
$request .= "Connection: close\r\n";
$request .= "AppKey: " . $this->AppKey . "\r\n";
$request .= "Nonce: " . $this->Nonce . "\r\n";
$request .= "CurTime: " . $this->CurTime . "\r\n";
$request .= "CheckSum: " . $this->CheckSum . "\r\n";
$request .= "\r\n";
$request .= $postdata . "\r\n";
print_r($request);
$fp = fsockopen($URL_Info["host"], $URL_Info["port"]);
fputs($fp, $request);
$result = '';
while (!feof($fp)) {
$result .= fgets($fp, 128);
}
fclose($fp);
$str_s = strpos($result, '{');
$str_e = strrpos($result, '}');
$str = substr($result, $str_s, $str_e - $str_s + 1);
print_r($result);
return $this->json_to_array($str);
}
/**
* 发送短信验证码
* @param $templateid [模板编号(由客服配置之后告知开发者)]
* @param $mobile [目标手机号]
* @param $deviceId [目标设备号,可选参数]
* @return $codeLen [验证码长度,范围4~10,默认为4]
*/
public function sendSmsCode($templateid, $mobile, $deviceId = '', $codeLen)
{
$url = 'https://api.netease.im/sms/sendcode.action';
$data = array(
'templateid' => $templateid,
'mobile' => $mobile,
'deviceId' => $deviceId,
'codeLen' => $codeLen
);
if ($this->RequestType == 'curl') {
$result = $this->postDataCurl($url, $data);
} else {
$result = $this->postDataFsockopen($url, $data);
}
return $result;
}
/**
* 发送模板短信
* @param $templateid [模板编号(由客服配置之后告知开发者)]
* @param $mobiles [验证码]
* @param $params [短信参数列表,用于依次填充模板,JSONArray格式,如["xxx","yyy"];对于不包含变量的模板,不填此参数表示模板即短信全文内容]
* @return $result [返回array数组对象]
*/
public function sendSMSTemplate($templateid, $mobiles = array(), $params = '')
{
$url = 'https://api.netease.im/sms/sendtemplate.action';
$data = array(
'templateid' => $templateid,
'mobiles' => json_encode($mobiles),
'params' => json_encode($params)
);
if ($this->RequestType == 'curl') {
$result = $this->postDataCurl($url, $data);
} else {
$result = $this->postDataFsockopen($url, $data);
}
return $result;
}
}
?>
C#-发送短信/语音短信验证码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;
namespace server_http_api
{
class CheckSumBuilder
{
// 计算并获取CheckSum
public static String getCheckSum(String appSecret, String nonce, String curTime)
{
byte[] data = Encoding.Default.GetBytes(appSecret + nonce + curTime);
byte[] result;
SHA1 sha = new SHA1CryptoServiceProvider();
// This is one implementation of the abstract class SHA1.
result = sha.ComputeHash(data);
return getFormattedText(result);
}
// 计算并获取md5值
public static String getMD5(String requestBody)
{
if (requestBody == null)
return null;
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(requestBody));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return getFormattedText(Encoding.Default.GetBytes(sBuilder.ToString()));
}
private static String getFormattedText(byte[] bytes)
{
char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
int len = bytes.Length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++) {
buf.Append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.Append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.ToString();
}
}
class HttpClient
{
//发起Http请求
public static void HttpPost(string url, Stream data, IDictionary<object, string> headers = null)
{
System.Net.WebRequest request = HttpWebRequest.Create(url);
request.Method = "POST";
if (data != null)
request.ContentLength = data.Length;
//request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
if (headers != null)
{
foreach (var v in headers)
{
if (v.Key is HttpRequestHeader)
request.Headers[(HttpRequestHeader)v.Key] = v.Value;
else
request.Headers[v.Key.ToString()] = v.Value;
}
}
HttpWebResponse response = null;
try
{
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(response.StatusDescription);
}
}
}
class Program
{
static void Main(string[] args)
{
String url = "https://api.netease.im/sms/sendcode.action";
url += "?templateid=3030410&mobile=13888888888";//请输入正确的手机号
//网易云信分配的账号,请替换你在管理后台应用下申请的Appkey
String appKey = "fd460d34e786e7754e505bc4fab0f027";
//网易云信分配的密钥,请替换你在管理后台应用下申请的appSecret
String appSecret = "xxxxxxxx";
//随机数(最大长度128个字符)
String nonce = "12345";
TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
Int32 ticks = System.Convert.ToInt32(ts.TotalSeconds);
//当前UTC时间戳,从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
String curTime = ticks.ToString();
//SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串,进行SHA1哈希计算,转化成16进制字符(String,小写)
String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
IDictionary<object, String> headers = new Dictionary<object, String>();
headers["AppKey"] = appKey;
headers["Nonce"] = nonce;
headers["CurTime"] = curTime;
headers["CheckSum"] = checkSum;
headers["ContentType"] = "application/x-www-form-urlencoded;charset=utf-8";
//执行Http请求
HttpClient.HttpPost(url, null, headers);
}
}
}
C#-发送通知类和运营类短信
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Net;
using System.IO;
namespace server_http_api
{
class CheckSumBuilder
{
// 计算并获取CheckSum
public static String getCheckSum(String appSecret, String nonce, String curTime)
{
byte[] data = Encoding.Default.GetBytes(appSecret + nonce + curTime);
byte[] result;
SHA1 sha = new SHA1CryptoServiceProvider();
// This is one implementation of the abstract class SHA1.
result = sha.ComputeHash(data);
return getFormattedText(result);
}
// 计算并获取md5值
public static String getMD5(String requestBody)
{
if (requestBody == null)
return null;
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(requestBody));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return getFormattedText(Encoding.Default.GetBytes(sBuilder.ToString()));
}
private static String getFormattedText(byte[] bytes)
{
char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
int len = bytes.Length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++) {
buf.Append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.Append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.ToString();
}
}
class HttpClient
{
//发起Http请求
public static void HttpPost(string url, Stream data, IDictionary<object, string> headers = null)
{
System.Net.WebRequest request = HttpWebRequest.Create(url);
request.Method = "POST";
if (data != null)
request.ContentLength = data.Length;
//request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
if (headers != null)
{
foreach (var v in headers)
{
if (v.Key is HttpRequestHeader)
request.Headers[(HttpRequestHeader)v.Key] = v.Value;
else
request.Headers[v.Key.ToString()] = v.Value;
}
}
HttpWebResponse response = null;
try
{
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(response.StatusDescription);
}
}
}
class Program
{
static void Main(string[] args)
{
String url = "https://api.netease.im/sms/sendtemplate.action";
url += "?templateid=3030410&mobiles=['13888888888','13666666666']¶ms=['xxxx','xxxx']";//请输入正确的手机号
//网易云信分配的账号,请替换你在管理后台应用下申请的Appkey
String appKey = "fd460d34e786e7754e505bc4fab0f027";
//网易云信分配的密钥,请替换你在管理后台应用下申请的appSecret
String appSecret = "xxxxxxxx";
//随机数(最大长度128个字符)
String nonce = "12345";
TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
Int32 ticks = System.Convert.ToInt32(ts.TotalSeconds);
//当前UTC时间戳,从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
String curTime = ticks.ToString();
//SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串,进行SHA1哈希计算,转化成16进制字符(String,小写)
String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
IDictionary<object, String> headers = new Dictionary<object, String>();
headers["AppKey"] = appKey;
headers["Nonce"] = nonce;
headers["CurTime"] = curTime;
headers["CheckSum"] = checkSum;
headers["ContentType"] = "application/x-www-form-urlencoded;charset=utf-8";
//执行Http请求
HttpClient.HttpPost(url, null, headers);
}
}
}
Python-发送短信/语音短信验证码
# coding=utf-8
import hashlib
import time
import requests
def send_code(mobile):
url = 'https://api.netease.im/sms/sendcode.action'
"""
AppKey 网易云信分配的账号,请替换你在管理后台应用下申请的Appkey
Nonce 随机数(最大长度128个字符)
CurTime 当前UTC时间戳,从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
CheckSum SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串,进行SHA1哈希计算,转化成16进制字符(String,小写)
"""
AppKey = ""
# 生成128个长度以内的随机字符串
nonce = hashlib.new('sha512', str(time.time()).encode("utf-8")).hexdigest()
# 获取当前时间戳
curtime = str(int(time.time()))
# 网易云信的 App Secret
AppSecret = ""
# 根据要求进行SHA1哈希计算
check_sum = hashlib.sha1((AppSecret + nonce + curtime).encode("utf-8")).hexdigest()
header = {
"AppKey": AppKey,
"Nonce": nonce,
"CurTime": curtime,
"CheckSum": check_sum
}
data = {
'mobile': mobile, # 手机号
"templateid": 123456,
}
resp = requests.post(url, data=data, headers=header)
print("Response:", resp.content)
if __name__ == '__main__':
send_code("12345678910") #要发送的手机号
Python-发送通知类和运营类短信
# coding=utf-8
import hashlib
import time
import requests
import json
def send_notice(mobiles,params):
url = 'https://api.netease.im/sms/sendtemplate.action'
"""
AppKey 网易云信分配的账号,请替换你在管理后台应用下申请的Appkey
Nonce 随机数(最大长度128个字符)
CurTime 当前UTC时间戳,从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
CheckSum SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串,进行SHA1哈希计算,转化成16进制字符(String,小写)
"""
AppKey = ""
# 生成128个长度以内的随机字符串
nonce = hashlib.new('sha512', str(time.time()).encode("utf-8")).hexdigest()
# 获取当前时间戳
curtime = str(int(time.time()))
# 网易云信的 App Secret
AppSecret = ""
# 根据要求进行SHA1哈希计算
check_sum = hashlib.sha1((AppSecret + nonce + curtime).encode("utf-8")).hexdigest()
header = {
"AppKey": AppKey,
"Nonce": nonce,
"CurTime": curtime,
"CheckSum": check_sum
}
data = {
'mobiles': json.dumps(mobiles), # 手机号
"templateid": 123456, # 模板id
"params":json.dumps(params),
}
resp = requests.post(url, data=data, headers=header)
print("Response:", resp.content)
if __name__ == '__main__':
mobiles = ["12345678910", "12345678911"] # 要发送的手机号
params = ["name","day"] # 模板中的变量
send_notice(mobiles,params)
相关参考
余额预警阙值
余额预警阙值,先可以登录管理后台,点击左侧“总览”,当前页有个“”余额预警”,可以自行配置,余额提醒。
短信回执抄送
现在云信支持短信的回执抄送,抄送详细解释在Server端文档,配置抄送地址在管理后台中的当前应用下,有个“消息抄送配置”,配置地址可以是地址,也可以是域名。短信的抄送只要通道给了回执,原封不动的给抄送出去,包括发送成功和失败(如黑名单,空号等等),如果通道那边没有给回执,那我们这边就不会抄送。另外,如果短信被反垃圾了,也不会有抄送,这个相当于,短信都没投递到通道服务商那边。
此文档是否对你有帮助?
有帮助
我要吐槽