雲之訊簡訊介面GO實現

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

 將項目變數appId, accountSId和token使用自己的替換掉就可以了。

發送資訊時直接調用函數SendSMS即可,傳入參數電話號碼,模板ID以及模板中參數。由於雲之訊的參數是以逗號分隔的,所以參數值中不能有逗號,同時參數值也不可為空。

package UcGoSdkimport ("bytes""errors""crypto/md5""encoding/base64""encoding/json""fmt""io/ioutil""net/http""net/url""strconv""strings""time")const (softVersion   = "2014-06-30"baseUrl       = "https://api.ucpaas.com"appId         = "appId"accountSId    = "accountSId"token         = "token")var timestamp stringtype UcPaaS struct {TmplSMS templateSMS `json:"templateSMS"`}type templateSMS struct {AppId      string `json:"appId"`TemplateId string `json:"templateId"`PhoneNum   string `json:"to"`Param      string `json:"param"`}type result struct {Resp response `json:"resp"`}type response struct {RespCode      string        `json:"respCode"`Failure       int           `josn:"failure,omitempty"`ReturnTmplSMS returnTmplSMS `json:"templateSMS"`}type returnTmplSMS struct {CreateDate string `json:"createDate"`SMSId      string `json:"smsId"`}/** * Name: initUc * Description: Create the instance of UcPaaS */func initUc(phoneNum, tempId string, params ...string) *UcPaaS {curTime := time.Now().Format("20060102150405000")intCurTime, _ := strconv.Atoi(curTime)timestamp = strconv.Itoa(intCurTime)catParam := ""for index, param := range params {if index == 0 {catParam = param} else {catParam = catParam + "," + param}}//param := verifyCode + "," + expireTimereturn &UcPaaS{TmplSMS: templateSMS{AppId:      appId,TemplateId: tempId,PhoneNum:   phoneNum,Param:      catParam,},}}/** * Name: getAuthorization * Descriotion: 包頭驗證資訊,使用Base64編碼(賬戶Id:時間戳記) */func (res *result) getAuthorization(accountSId string) string {src := accountSId + ":" + timestampreturn base64.StdEncoding.EncodeToString([]byte(src))}/** * Name: getSigParameter * Description: 驗證參數,URL後必須帶有sig參數,sig= MD5(賬戶Id + 賬戶授權令牌 + 時間戳記,共32位)(注:轉成大寫) */func (res *result) getSigParameter(accountSId, token string) string {sig := accountSId + token + timestamp//擷取MD5return strings.ToUpper(fmt.Sprintf("%x", md5.Sum([]byte(sig))))}/** * Name: getResult * @return respcode 000000表示發送成功 * */func (res *result) getResult(url, dataType, method string, data []byte) {resp := res.connection(url, dataType, method, data)_ = json.Unmarshal([]byte(resp), res)}/** * Name: connection * @param url * @param dataType * @param method post或get * @param body POST資料 * @return string */func (res *result) connection(url, dataType, method string, data []byte) string {mine := ""if dataType == "json" {mine = "application/json"} else {mine = "application/xml"}client := &http.Client{}//Get datareq, err := http.NewRequest(method, url, bytes.NewBuffer(data))if err != nil {return err.Error()}req.Header.Add("Accept", mine)req.Header.Add("Content-Type", (mine + ";charset=utf-8"))req.Header.Add("Content-Type", "application/x-www-form-urlencoded")req.Header.Add("Authorization", res.getAuthorization(accountSId))req.Header.Add("Content-Length", strconv.Itoa(len(data)))resp, err := client.Do(req)defer resp.Body.Close()if err != nil {return ""}respBody, err := ioutil.ReadAll(resp.Body)if err != nil {return ""}return string(respBody)}/** * Name:SendSMS * Description: Send the text message. * @param phoneNum: The phone number * @param tempId: The message template id * @param params... : The parameter list. */func SendSMS(phoneNum, tempId string, params ...string) (respCode string, err error) {var rs result//初始化uc := initUc(phoneNum, tempId, params...)//擷取Urlresource := "/" + softVersion + "/Accounts/" + accountSId + "/Messages/templateSMS"parseUrl, err := url.ParseRequestURI(baseUrl)if err != nil {return "", errors.New("請求地址出錯")}parseUrl.Path = resourceurlStr := fmt.Sprintf("%v?sig=%s", parseUrl, rs.getSigParameter(accountSId, token))//擷取post資料data, err := json.MarshalIndent(uc, "", "  ")if err != nil {return "", err}//POST必須大寫rs.getResult(urlStr, "json", "POST", data)respCode = rs.Resp.RespCodeif respCode != "000000" {return respCode, errors.New("發送驗證碼失敗。")}return "", nil}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.