jsapi.go 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * Copyright (c) 2022 Yansen Zhang
  3. * wxcomponent is licensed under Mulan PSL v2.
  4. * You can use this software according to the terms and conditions of the Mulan PSL v2.
  5. * You may obtain a copy of Mulan PSL v2 at:
  6. * http://license.coscl.org.cn/MulanPSL2
  7. * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
  8. * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
  9. * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  10. * See the Mulan PSL v2 for more details.
  11. **/
  12. package webpage
  13. import (
  14. "crypto/sha1"
  15. "encoding/json"
  16. "fmt"
  17. "net/url"
  18. "strconv"
  19. "time"
  20. "gitee.com/yansen_zh/wxcomponent/errors"
  21. "gitee.com/yansen_zh/wxcomponent/utils"
  22. "gitee.com/yansen_zh/wxcomponent/utils/request"
  23. )
  24. // JsapiTicketResult 通过 access_token 获取 jsapi_ticket 结果
  25. type JsapiTicketResult struct {
  26. errors.Error
  27. Ticket string `json:"ticket"`
  28. ExpiresIn int `json:"expires_in"`
  29. }
  30. // JsapiSignature 可以用来初始化 JS SDK
  31. type JsapiSignature struct {
  32. Timestamp int64 `json:"timestamp"`
  33. NonceStr string `json:"nonceStr"`
  34. Signature string `json:"signature"`
  35. }
  36. const (
  37. apiGetJSTicket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket"
  38. )
  39. // GetJSTicket 通过 access_token 获取 jsapi_ticket
  40. func GetJSTicket(authorizerToken string) (*JsapiTicketResult, error) {
  41. if authorizerToken == "" {
  42. return nil, errors.New("获取 jsapi_ticket authorizerToken 不能为空")
  43. }
  44. param := url.Values{}
  45. param.Set("access_token", authorizerToken)
  46. param.Set("type", "jsapi")
  47. resp, e2 := request.GetJSON(apiGetJSTicket, &param)
  48. if e2 != nil {
  49. return nil, e2
  50. }
  51. result := JsapiTicketResult{}
  52. if err := json.Unmarshal(resp, &result); err != nil {
  53. return nil, err
  54. }
  55. return &result, nil
  56. }
  57. // GetJSAPISignature 获取 JsapiSignature
  58. func GetJSAPISignature(ticket, url string) *JsapiSignature {
  59. timestamp := time.Now().Unix()
  60. timestampStr := strconv.FormatInt(timestamp, 10)
  61. nonceStr := utils.RandStr(16)
  62. s1 := "jsapi_ticket=" + ticket
  63. s2 := "&noncestr=" + nonceStr
  64. s3 := "&timestamp=" + timestampStr
  65. s4 := "&url=" + url
  66. plain := s1 + s2 + s3 + s4
  67. signature := fmt.Sprintf("%x", sha1.Sum([]byte(plain)))
  68. return &JsapiSignature{
  69. Timestamp: timestamp,
  70. NonceStr: nonceStr,
  71. Signature: signature,
  72. }
  73. }