互亿无线 · 文档中心

彩信/视频短信 - 代码示例


GO对接彩信/视频短信接口DEMO示例
本文为您提供了GO语言版本的彩信/视频短信接口对接DEMO示例

彩信/视频短信接口文档 点击下载

彩信/视频短信接口接入指南 点击访问

//接口类型:互亿无线彩信/视频短信接口。
// 账户注册:请通过该地址开通账户https://user.ihuyi.com/new/register.html

 
package main

import (
	"bytes"
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"sort"
	"strings"
	"time"
)

//内容项目
type contentItem struct {
	ConType string `json:"con_type"` //内容类型
	ExtType string `json:"ext_type"` //文件扩展名
	Data    string `json:"data"`     //数据
}

//获取签名
func sign(data map[string]string, appKEY string) string {
	var keys []string
	data["api_key"] = appKEY
	for k := range data {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	var hash []string
	for _, v := range keys {
		hash = append(hash, fmt.Sprintf("%s=%s", v, data[v]))
	}
	return getMd5String(strings.Join(hash, "&"))
}

// getMd5String 返回md5加密字符串
func getMd5String(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return hex.EncodeToString(h.Sum(nil))
}

// randomString 随机生成字符串
// randomString(8, "A")
// randomString(8, "a0")
// randomString(20, "Aa0")
func randomString(randLength int, randType string) (result string) {
	var num = "0123456789"
	var lower = "abcdefghijklmnopqrstuvwxyz"
	var upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	b := bytes.Buffer{}
	if strings.Contains(randType, "0") {
		b.WriteString(num)
	}
	if strings.Contains(randType, "a") {
		b.WriteString(lower)
	}
	if strings.Contains(randType, "A") {
		b.WriteString(upper)
	}
	var str = b.String()
	var strLen = len(str)
	if strLen == 0 {
		result = ""
		return
	}

	rand.Seed(time.Now().UnixNano())
	b = bytes.Buffer{}
	for i := 0; i < randLength; i++ {
		b.WriteByte(str[rand.Intn(strLen)])
	}
	result = b.String()
	return
}

func createContent() [][]contentItem {
	//创建测试内容开始

	//第1帧
	//文本
	retContent := [][]contentItem{}
	frameCon := []contentItem{}
	tmpCon := contentItem{}
	tmpCon.ExtType = "txt"
	tmpCon.ConType = "text"
	tmpCon.Data = "这是测试内容1" //"1:" + utils.RandomString(20, "Aa0")
	frameCon = append(frameCon, tmpCon)

	//图片
	tmpCon = contentItem{}
	tmpCon.ExtType = "jpg"
	tmpCon.ConType = "image"
	f, err := ioutil.ReadFile("yourFileFolder/test-jpg1.jpg")
	if err != nil {
		fmt.Println("read fail", err)
		return nil
	}
	tmpCon.Data = base64.StdEncoding.EncodeToString(f)
	tmpCon.Data = "test"
	frameCon = append(frameCon, tmpCon)

	retContent = append(retContent, frameCon)

	//第2帧
	frameCon = []contentItem{}
	tmpCon = contentItem{}
	tmpCon.ExtType = "txt"
	tmpCon.ConType = "text"
	tmpCon.Data = "这是测试内容2" //"2:" + utils.RandomString(20, "Aa0")
	frameCon = append(frameCon, tmpCon)

	//视频
	tmpCon = contentItem{}
	tmpCon.ExtType = "mp4"
	tmpCon.ConType = "video"
	f, err = ioutil.ReadFile("yourFileFolder/test-mp41.mp4")
	if err != nil {
		fmt.Println("read fail", err)
		return nil
	}
	tmpCon.Data = base64.StdEncoding.EncodeToString(f)
	frameCon = append(frameCon, tmpCon)

	retContent = append(retContent, frameCon)

	//第3帧
	//图片
	frameCon = []contentItem{}
	tmpCon = contentItem{}
	tmpCon.ExtType = "jpg"
	tmpCon.ConType = "image"
	f, err = ioutil.ReadFile("yourFileFolder/test-jpg2.jpg")
	if err != nil {
		fmt.Println("read fail", err)
		return nil
	}
	tmpCon.Data = base64.StdEncoding.EncodeToString(f)
	frameCon = append(frameCon, tmpCon)

	tmpCon = contentItem{}
	tmpCon.ExtType = "txt"
	tmpCon.ConType = "text"
	tmpCon.Data = "这是测试内容3" //"3:" + utils.RandomString(20, "Aa0")
	frameCon = append(frameCon, tmpCon)

	retContent = append(retContent, frameCon)

	//第4帧
	//图片
	frameCon = []contentItem{}
	tmpCon = contentItem{}
	tmpCon.ExtType = "mp3"
	tmpCon.ConType = "audio"
	f, err = ioutil.ReadFile("yourFileFolder/test-mp31.mp3")
	if err != nil {
		fmt.Println("read fail", err)
		return nil
	}
	tmpCon.Data = base64.StdEncoding.EncodeToString(f)
	frameCon = append(frameCon, tmpCon)

	tmpCon = contentItem{}
	tmpCon.ExtType = "txt"
	tmpCon.ConType = "text"
	tmpCon.Data = "这是测试内容4" //"4:" + utils.RandomString(20, "Aa0")
	frameCon = append(frameCon, tmpCon)

	retContent = append(retContent, frameCon)

	//fmt.Println("data.Content:",data.Content)
	//创建测试内容结束
	return retContent
}

//测试获取余额
func balance() {
	type sendData struct {
		APIID     string `json:"api_id"`
		Signature string `json:"signature"`
		Timestamp int    `json:"timestamp"`
		RequestID string `json:"request_id"`
	}

	data := sendData{}
	data.APIID = "xxxxxx"
	data.RequestID = randomString(20, "Aa0")
	data.Timestamp = int(time.Now().Unix())

	signData := make(map[string]string)
	signData["api_id"] = data.APIID
	signData["timestamp"] = fmt.Sprintf("%d", data.Timestamp)
	signData["request_id"] = data.RequestID
	data.Signature = sign(signData, "xxxxxx")

	url := "https://api.ihuyi.com/mms/v1/balance"
	client := &http.Client{
		Timeout: time.Second * 10,
	}

	sendRawData, _ := json.Marshal(data)
	request, err := http.NewRequest("POST", url, strings.NewReader(string(sendRawData)))
	if err != nil {
		fmt.Print(err)
		return
	}
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	if err != nil {
		fmt.Print(err)
		return
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Print(err)
		return
	}
	getData := string(body)
	fmt.Println(getData)
}

//信息批量提交(使用创建彩信方式)
func batch_send_1() {
	type sendData struct {
		APIID       string            `json:"api_id"`
		Signature   string            `json:"signature"`
		Timestamp   int               `json:"timestamp"`
		RequestID   string            `json:"request_id"`
		ProductID   int               `json:"product_id"`   //产品ID
		Phone       []string          `json:"phone"`        //手机号
		Title       string            `json:"title"`        //短信标题
		SignName    string            `json:"sign_name"`    //短信签名
		Content     [][]contentItem   `json:"content"`      //短信内容
		TemplateID  int               `json:"template_id"`  //模板ID
		TemplateVar map[string]string `json:"template_var"` //模板变量
		SendTime    string            `json:"send_time"`    //定时时间
	}

	data := sendData{}
	data.APIID = "xxxxx"
	data.RequestID = randomString(20, "Aa0")
	data.Timestamp = int(time.Now().Unix())
	data.Phone = []string{"xxxxx", "xxxxx"}
	data.ProductID = 1016
	data.Title = "这是测试标题"
	data.SignName = "您的签名"

	signData := make(map[string]string)
	signData["api_id"] = data.APIID
	signData["timestamp"] = fmt.Sprintf("%d", data.Timestamp)
	signData["request_id"] = data.RequestID
	data.Signature = sign(signData, "xxxxxx")
	data.TemplateID = 5 //测试模版模版ID

	createTestContent := true
	if createTestContent {
		data.Content = createContent()
		if data.Content == nil {
			return
		}
	}

	url := "https://api.ihuyi.com/mms/v1/batchSend"

	client := &http.Client{
		Timeout: time.Second * 10,
	}

	sendRawData, _ := json.Marshal(data)
	request, err := http.NewRequest("POST", url, strings.NewReader(string(sendRawData)))
	if err != nil {
		fmt.Print(err)
		return
	}
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	if err != nil {
		fmt.Print(err)
		return
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Print(err)
		return
	}
	getData := string(body)
	fmt.Println(getData)
}

//信息批量提交(使用调用模版ID方式)
func batch_send_2() {
	type sendData struct {
		APIID       string            `json:"api_id"`
		Signature   string            `json:"signature"`
		Timestamp   int               `json:"timestamp"`
		RequestID   string            `json:"request_id"`
		ProductID   int               `json:"product_id"`   //产品ID
		Phone       []string          `json:"phone"`        //手机号
		Title       string            `json:"title"`        //短信标题
		SignName    string            `json:"sign_name"`    //短信签名
		Content     [][]contentItem   `json:"content"`      //短信内容
		TemplateID  int               `json:"template_id"`  //模板ID
		TemplateVar map[string]string `json:"template_var"` //模板变量
		SendTime    string            `json:"send_time"`    //定时时间
	}

	data := sendData{}
	data.APIID = "xxxxx"
	data.RequestID = randomString(20, "Aa0")
	data.Timestamp = int(time.Now().Unix())
	data.Phone = []string{"xxxxx", "xxxxx"}
	data.ProductID = 1016
	data.Title = ""
	data.SignName = ""

	signData := make(map[string]string)
	signData["api_id"] = data.APIID
	signData["timestamp"] = fmt.Sprintf("%d", data.Timestamp)
	signData["request_id"] = data.RequestID
	data.Signature = sign(signData, "xxxxx")
	data.TemplateID = 5

	createTestContent := false
	if createTestContent {
		data.Content = createContent()
		if data.Content == nil {
			return
		}
	}

	url := "https://api.ihuyi.com/mms/v1/batchSend"

	client := &http.Client{
		Timeout: time.Second * 10,
	}

	sendRawData, _ := json.Marshal(data)
	request, err := http.NewRequest("POST", url, strings.NewReader(string(sendRawData)))
	if err != nil {
		fmt.Print(err)
		return
	}
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	if err != nil {
		fmt.Print(err)
		return
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Print(err)
		return
	}
	getData := string(body)
	fmt.Println(getData)
}

//创建模板
func templateCreate() {
	type sendData struct {
		APIID     string          `json:"api_id"`
		Signature string          `json:"signature"`
		Timestamp int             `json:"timestamp"`
		RequestID string          `json:"request_id"`
		Title     string          `json:"title"`     //标题
		SignName  string          `json:"sign_name"` //标题
		Content   [][]contentItem `json:"content"`   //短信内容
		Purpose   string          `json:"purpose"`   //应用场景
	}

	data := sendData{}
	data.APIID = "xxxxx"
	data.RequestID = randomString(20, "Aa0")
	data.Timestamp = int(time.Now().Unix())
	data.Title = "这是测试标题"
	data.SignName = "您的签名"
	data.Purpose = "purpose" + randomString(10, "Aa0")

	signData := make(map[string]string)
	signData["api_id"] = data.APIID
	signData["timestamp"] = fmt.Sprintf("%d", data.Timestamp)
	signData["request_id"] = data.RequestID
	data.Signature = sign(signData, "xxxxx")

	//创建测试内容
	data.Content = createContent()
	if data.Content == nil {
		return
	}

	url := "https://api.ihuyi.com/mms/v1/templateCreate"
	client := &http.Client{
		Timeout: time.Second * 30,
	}

	sendRawData, _ := json.Marshal(data)
	request, err := http.NewRequest("POST", url, strings.NewReader(string(sendRawData)))
	if err != nil {
		fmt.Println(err)
		return
	}
	request.Header.Set("Content-Type", "application/json")
	response, err := client.Do(request)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	getData := string(body)
	fmt.Println(getData)
}

func main()  {
	balance()
	templateCreate()
	batch_send_1()
	batch_send_2()
}

现在注册,即享新用户礼包!

请输入验证码免费体验产品

收不到短信验证码?
×
服务热线:
4008 808 898