API文档

Go

  1. package main
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "fmt"
  8. "sort"
  9. "time"
  10. "math/rand"
  11. "strconv"
  12. "encoding/json"
  13. "io/ioutil"
  14. "net/http"
  15. "net/url"
  16. )
  17. func random(min, max int) int {
  18. rand.Seed(time.Now().Unix())
  19. randNum := rand.Intn(max - min) + min
  20. return randNum
  21. }
  22. func postData(apiUrl string, data url.Values) string {
  23. res, err := http.PostForm(apiUrl, data)
  24. if err != nil {
  25. return err.Error()
  26. }
  27. defer res.Body.Close()
  28. result, _ := ioutil.ReadAll(res.Body)
  29. return string(result)
  30. }
  31. func main() {
  32. apiUrl := "https://api.yisu.com/sms/sendSms"
  33. accessId := "*****"
  34. accessSecret := "*****"
  35. vars, _ := json.Marshal(map[string]string{"code":"123123","min":"5"})
  36. params := make(url.Values)
  37. params["accessId"] = []string{accessId}
  38. params["nonce"] = []string{strconv.Itoa(random(10000000, 99999999))} // 随机数
  39. params["timestamp"] = []string{strconv.Itoa(int(time.Now().Unix()))} // 时间戳
  40. params["phone"] = []string{"13800000000"} // 手机号码
  41. params["templateCode"] = []string{"100001"} // 模板号码
  42. params["templateVars"] = []string{string(vars)} // 模板变量
  43. var buf bytes.Buffer
  44. keys := make([]string, 0, len(params))
  45. for k, _ := range params {
  46. keys = append(keys, k)
  47. }
  48. sort.Strings(keys)
  49. for i := range keys {
  50. k := keys[i]
  51. buf.WriteString(k)
  52. buf.WriteString("=")
  53. buf.WriteString(params.Get(k))
  54. buf.WriteString("&")
  55. }
  56. buf.Truncate(buf.Len() - 1)
  57. hashed := hmac.New(sha1.New, []byte(accessSecret))
  58. hashed.Write(buf.Bytes())
  59. params["signature"] = []string{base64.StdEncoding.EncodeToString(hashed.Sum(nil))} // 签名
  60. result := postData(apiUrl, params)
  61. fmt.Println(result)
  62. }