176-1345-1345
TECHNICAL SUPPORT技术支持
企业信使3.0Python、Java、C#、PHP、Go五种常用语言的调用示例
时间:2026-05-05 20:45:33 点击:
 

企业信使3.0版API接口文档说明下载

通用说明

加密方式:AES-256-CBC,PKCS7填充,IV随机生成并拼接在密文头部

签名方式:SHA-256(password + 加密后的data + timestamp)

所有请求需携带Header(userid, timestamp, sign)和Body(加密后的data)

1. Python 示例
python
import hashlib
import json
import time
import base64
import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad

class SmsClient:
    def __init__(self, userid, password, aes_key, host):
        self.userid = userid
        self.password = password
        self.aes_key = base64.b64decode(aes_key)
        self.host = host
    
    def _aes_encrypt(self, data):
        """AES加密,IV随机生成并拼接在密文头部"""
        iv = AES.new(key=self.aes_key, mode=AES.MODE_CBC).iv
        cipher = AES.new(key=self.aes_key, mode=AES.MODE_CBC, iv=iv)
        encrypted = cipher.encrypt(pad(data.encode('utf-8'), AES.block_size))
        return base64.b64encode(iv + encrypted).decode('utf-8')
    
    def _generate_sign(self, encrypted_data, timestamp):
        """生成签名"""
        raw = self.password + encrypted_data + timestamp
        return hashlib.sha256(raw.encode('utf-8')).hexdigest()
    
    def _request(self, data):
        """发送请求"""
        timestamp = str(int(time.time() * 1000))
        encrypted_data = self._aes_encrypt(data)
        sign = self._generate_sign(encrypted_data, timestamp)
        
        headers = {'Content-Type': 'application/json;charset=utf-8'}
        body = {
            'userid': self.userid,
            'timestamp': timestamp,
            'sign': sign
        }
        # 注意:加密数据放在Body的data字段
        response = requests.post(
            self.host,
            json={'data': encrypted_data},
            headers=headers
        )
        return response.json()
    
    def send_sms(self, mobile, content, send_time=None, extno=None):
        """发送短信"""
        data = {
            'action': 'send',
            'mobile': mobile,
            'content': content
        }
        if send_time:
            data['sendTime'] = send_time
        if extno:
            data['extno'] = extno
        return self._request(json.dumps(data))
    
    def get_balance(self):
        """查询余额"""
        data = {'action': 'overage'}
        return self._request(json.dumps(data))
    
    def check_keyword(self, content):
        """检测非法关键词"""
        data = {
            'action': 'checkkeyword',
            'content': content
        }
        return self._request(json.dumps(data))
    
    def get_status_report(self, status_num=4000, own_ext=None):
        """获取状态报告"""
        data = {'action': 'query'}
        if status_num:
            data['statusNum'] = status_num
        if own_ext:
            data['ownExt'] = own_ext
        return self._request(json.dumps(data))

# 使用示例
if __name__ == '__main__':
    client = SmsClient(
        userid='20',
        password='test123456',
        aes_key='J6NjSids/iqj0cd2B/ygijGJTN25OOEm5SpATB/D3zc=',
        host='https://sms.37037.com/v3sms.aspx'
    )
    
    # 发送短信
    result = client.send_sms('15100000000', '【测试】TEST')
    print('发送结果:', result)
    
    # 查询余额
    balance = client.get_balance()
    print('余额:', balance)
2. Java 示例
java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

public class SmsClient {
    private String userid;
    private String password;
    private byte[] aesKey;
    private String host;

    public SmsClient(String userid, String password, String aesKey, String host) {
        this.userid = userid;
        this.password = password;
        this.aesKey = Base64.getDecoder().decode(aesKey);
        this.host = host;
    }

    // AES加密
    private String aesEncrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        // 生成随机IV
        byte[] iv = new byte[16];
        new java.security.SecureRandom().nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        
        SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        
        byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        // 将IV拼接在密文头部
        byte[] result = new byte[iv.length + encrypted.length];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(encrypted, 0, result, iv.length, encrypted.length);
        
        return Base64.getEncoder().encodeToString(result);
    }

    // 生成签名
    private String generateSign(String encryptedData, String timestamp) throws Exception {
        String raw = password + encryptedData + timestamp;
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(raw.getBytes(StandardCharsets.UTF_8));
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    // 发送请求
    private String request(String data) throws Exception {
        String timestamp = String.valueOf(System.currentTimeMillis());
        String encryptedData = aesEncrypt(data);
        String sign = generateSign(encryptedData, timestamp);

        URL url = new URL(host);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.setDoOutput(true);

        // 构建请求Body
        String body = "{\"data\":\"" + encryptedData + "\"}";
        
        try (OutputStream os = conn.getOutputStream()) {
            os.write(body.getBytes(StandardCharsets.UTF_8));
        }

        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
        }
        return response.toString();
    }

    // 发送短信
    public String sendSms(String mobile, String content) throws Exception {
        String data = String.format(
            "{\"action\":\"send\",\"mobile\":\"%s\",\"content\":\"%s\"}",
            mobile, content
        );
        return request(data);
    }

    // 查询余额
    public String getBalance() throws Exception {
        String data = "{\"action\":\"overage\"}";
        return request(data);
    }

    public static void main(String[] args) throws Exception {
        SmsClient client = new SmsClient(
            "20",
            "test123456",
            "J6NjSids/iqj0cd2B/ygijGJTN25OOEm5SpATB/D3zc=",
            "https://sms.37037.com/v3sms.aspx"
        );
        
        String result = client.sendSms("15100000000", "【测试】TEST");
        System.out.println("发送结果: " + result);
    }
}
3. C# 示例
csharp
using System;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class SmsClient
{
    private string userid;
    private string password;
    private byte[] aesKey;
    private string host;
    private static readonly HttpClient client = new HttpClient();

    public SmsClient(string userid, string password, string aesKey, string host)
    {
        this.userid = userid;
        this.password = password;
        this.aesKey = Convert.FromBase64String(aesKey);
        this.host = host;
    }

    // AES加密
    private string AesEncrypt(string data)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = aesKey;
            aesAlg.GenerateIV();
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;

            using (var encryptor = aesAlg.CreateEncryptor())
            using (var msEncrypt = new MemoryStream())
            {
                // 将IV写入密文头部
                msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);

                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                using (var swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(data);
                }

                return Convert.ToBase64String(msEncrypt.ToArray());
            }
        }
    }

    // 生成签名
    private string GenerateSignature(string encryptedData, string timestamp)
    {
        string rawString = password + encryptedData + timestamp;
        using (SHA256 sha256 = SHA256.Create())
        {
            byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(rawString));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }

    // 发送请求
    private async Task<string> RequestAsync(string data)
    {
        string timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
        string encryptedData = AesEncrypt(data);
        string sign = GenerateSignature(encryptedData, timestamp);

        var body = new { data = encryptedData };
        var content = new StringContent(
            JsonSerializer.Serialize(body),
            Encoding.UTF8,
            "application/json"
        );

        var response = await client.PostAsync(host, content);
        return await response.Content.ReadAsStringAsync();
    }

    // 发送短信
    public async Task<string> SendSmsAsync(string mobile, string content)
    {
        var data = new { action = "send", mobile = mobile, content = content };
        return await RequestAsync(JsonSerializer.Serialize(data));
    }

    // 查询余额
    public async Task<string> GetBalanceAsync()
    {
        var data = new { action = "overage" };
        return await RequestAsync(JsonSerializer.Serialize(data));
    }

    // 添加使用示例
    public static async Task Main()
    {
        var client = new SmsClient(
            "20",
            "test123456",
            "J6NjSids/iqj0cd2B/ygijGJTN25OOEm5SpATB/D3zc=",
            "https://sms.37037.com/v3sms.aspx"
        );

        string result = await client.SendSmsAsync("15100000000", "【测试】TEST");
        Console.WriteLine($"发送结果: {result}");
    }
}
4. PHP 示例
php
<?php

class SmsClient {
    private $userid;
    private $password;
    private $aesKey;
    private $host;

    public function __construct($userid, $password, $aesKey, $host) {
        $this->userid = $userid;
        $this->password = $password;
        $this->aesKey = base64_decode($aesKey);
        $this->host = $host;
    }

    // AES加密
    private function aesEncrypt($data) {
        $iv = random_bytes(16);
        $encrypted = openssl_encrypt(
            $data,
            'aes-256-cbc',
            $this->aesKey,
            OPENSSL_RAW_DATA,
            $iv
        );
        return base64_encode($iv . $encrypted);
    }

    // 生成签名
    private function generateSign($encryptedData, $timestamp) {
        $raw = $this->password . $encryptedData . $timestamp;
        return hash('sha256', $raw);
    }

    // 发送请求
    private function request($data) {
        $timestamp = (string)(microtime(true) * 1000);
        $encryptedData = $this->aesEncrypt($data);
        $sign = $this->generateSign($encryptedData, $timestamp);

        $body = json_encode(['data' => $encryptedData]);
        
        $ch = curl_init($this->host);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json;charset=utf-8',
            'Content-Length: ' . strlen($body)
        ]);

        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }

    // 发送短信
    public function sendSms($mobile, $content, $sendTime = null, $extno = null) {
        $data = [
            'action' => 'send',
            'mobile' => $mobile,
            'content' => $content
        ];
        if ($sendTime) $data['sendTime'] = $sendTime;
        if ($extno) $data['extno'] = $extno;
        
        return $this->request(json_encode($data));
    }

    // 查询余额
    public function getBalance() {
        $data = ['action' => 'overage'];
        return $this->request(json_encode($data));
    }

    // 检测关键词
    public function checkKeyword($content) {
        $data = [
            'action' => 'checkkeyword',
            'content' => $content
        ];
        return $this->request(json_encode($data));
    }
}

// 使用示例
$client = new SmsClient(
    '20',
    'test123456',
    'J6NjSids/iqj0cd2B/ygijGJTN25OOEm5SpATB/D3zc=',
    'https://sms.37037.com/v3sms.aspx'
);

$result = $client->sendSms('15100000000', '【测试】TEST');
echo "发送结果: " . $result . "\n";

?>
5. Go 示例
go
package main

import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "crypto/sha256"
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io"
    "math/rand"
    "net/http"
    "strconv"
    "time"
)

type SmsClient struct {
    userid   string
    password string
    aesKey   []byte
    host     string
}

func NewSmsClient(userid, password, aesKey, host string) *SmsClient {
    key, _ := base64.StdEncoding.DecodeString(aesKey)
    return &SmsClient{
        userid:   userid,
        password: password,
        aesKey:   key,
        host:     host,
    }
}

// AES加密
func (c *SmsClient) aesEncrypt(data string) (string, error) {
    block, err := aes.NewCipher(c.aesKey)
    if err != nil {
        return "", err
    }

    // 生成随机IV
    iv := make([]byte, aes.BlockSize)
    rand.Read(iv)

    // PKCS7填充
    plaintext := []byte(data)
    padding := aes.BlockSize - len(plaintext)%aes.BlockSize
    for i := 0; i < padding; i++ {
        plaintext = append(plaintext, byte(padding))
    }

    ciphertext := make([]byte, len(plaintext))
    mode := cipher.NewCBCEncrypter(block, iv)
    mode.CryptBlocks(ciphertext, plaintext)

    // 拼接IV和密文
    result := append(iv, ciphertext...)
    return base64.StdEncoding.EncodeToString(result), nil
}

// 生成签名
func (c *SmsClient) generateSign(encryptedData, timestamp string) string {
    raw := c.password + encryptedData + timestamp
    hash := sha256.Sum256([]byte(raw))
    return fmt.Sprintf("%x", hash)
}

// 发送请求
func (c *SmsClient) request(data string) (string, error) {
    timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
    encryptedData, err := c.aesEncrypt(data)
    if err != nil {
        return "", err
    }
    sign := c.generateSign(encryptedData, timestamp)

    body := map[string]string{"data": encryptedData}
    jsonBody, _ := json.Marshal(body)

    req, _ := http.NewRequest("POST", c.host, bytes.NewBuffer(jsonBody))
    req.Header.Set("Content-Type", "application/json;charset=utf-8")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    respBody, _ := io.ReadAll(resp.Body)
    return string(respBody), nil
}

// 发送短信
func (c *SmsClient) SendSms(mobile, content string) (string, error) {
    data := map[string]string{
        "action":  "send",
        "mobile":  mobile,
        "content": content,
    }
    jsonData, _ := json.Marshal(data)
    return c.request(string(jsonData))
}

// 查询余额
func (c *SmsClient) GetBalance() (string, error) {
    data := map[string]string{"action": "overage"}
    jsonData, _ := json.Marshal(data)
    return c.request(string(jsonData))
}

func main() {
    client := NewSmsClient(
        "20",
        "test123456",
        "J6NjSids/iqj0cd2B/ygijGJTN25OOEm5SpATB/D3zc=",
        "https://sms.37037.com/v3sms.aspx",
    )

    result, err := client.SendSms("15100000000", "【测试】TEST")
    if err != nil {
        fmt.Println("错误:", err)
    } else {
        fmt.Println("发送结果:", result)
    }
}


注意事项

IV处理:IV是随机生成的,需要拼接到密文头部(前16字节),解密时需要先取出IV

签名顺序:password + 加密后的data + timestamp(注意是加密后的data,不是原始data)

时间戳:毫秒级时间戳,服务端会校验时效性(默认60秒)

响应格式:返回的data也是AES加密的,需要按同样方式解密

状态报告/上行拉取:使用不同的接口地址(v3statusApi.aspx、v3callApi.aspx)

推送接收:收到推送后需要返回大写OK
 

上一篇:网关移动CMPP标准协议

咨询热线:176-1345-1345     工作时间:周一至周日:8:00-20:00
售后电话:170-0392-8888  售后QQ/微信:37037 
声明:本公司其它地区暂无分支机构,请勿上当受骗.

扫一扫
加关注

Copyright 2008-2023 MingNet All Rights Reserved
增值业务许可证:豫B2-20160055 豫ICP备09005601号   豫公网安备 41010502002208号