互億無線 · 文檔中心

彩信/視頻短信 - 代碼示例


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"
)

//內(nèi)容項目
type contentItem struct {
	ConType string `json:"con_type"` //內(nèi)容類型
	ExtType string `json:"ext_type"` //文件擴展名
	Data    string `json:"data"`     //數(shù)據(jù)
}

//獲取簽名
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 {
	//創(chuàng)建測試內(nèi)容開始

	//第1幀
	//文本
	retContent := [][]contentItem{}
	frameCon := []contentItem{}
	tmpCon := contentItem{}
	tmpCon.ExtType = "txt"
	tmpCon.ConType = "text"
	tmpCon.Data = "這是測試內(nèi)容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 = "這是測試內(nèi)容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 = "這是測試內(nèi)容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 = "這是測試內(nèi)容4" //"4:" + utils.RandomString(20, "Aa0")
	frameCon = append(frameCon, tmpCon)

	retContent = append(retContent, frameCon)

	//fmt.Println("data.Content:",data.Content)
	//創(chuàng)建測試內(nèi)容結(jié)束
	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)
}

//信息批量提交(使用創(chuàng)建彩信方式)
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"`   //產(chǎn)品ID
		Phone       []string          `json:"phone"`        //手機號
		Title       string            `json:"title"`        //短信標題
		SignName    string            `json:"sign_name"`    //短信簽名
		Content     [][]contentItem   `json:"content"`      //短信內(nèi)容
		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)
}

//信息批量提交(使用調(diào)用模版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"`   //產(chǎn)品ID
		Phone       []string          `json:"phone"`        //手機號
		Title       string            `json:"title"`        //短信標題
		SignName    string            `json:"sign_name"`    //短信簽名
		Content     [][]contentItem   `json:"content"`      //短信內(nèi)容
		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)
}

//創(chuàng)建模板
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"`   //短信內(nèi)容
		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")

	//創(chuàng)建測試內(nèi)容
	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()
}

現(xiàn)在注冊,即享新用戶禮包!

在線咨詢
電話咨詢

服務熱線:

4008 808 898

服務熱線(工作時間):

4008 808 898

業(yè)務咨詢(非工作時間):

售后咨詢(非工作時間):

驗證碼已發(fā)送到您的手機,請查收!

輸入驗證碼后,點擊“開通體驗賬戶”按鈕可立即開通體驗賬戶。

收不到短信驗證碼?
互億無線不提供接碼服務,接碼用戶請勿點擊開通按鈕。
×