jsapi.go 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. "errors"
  17. "fmt"
  18. "net/url"
  19. "strconv"
  20. "time"
  21. wxerr "gitee.com/yansen_zh/wxcomponent/errors"
  22. "gitee.com/yansen_zh/wxcomponent/utils"
  23. "gitee.com/yansen_zh/wxcomponent/utils/request"
  24. )
  25. // JsapiTicketResult 通过 access_token 获取 jsapi_ticket 结果
  26. type JsapiTicketResult struct {
  27. wxerr.Error
  28. Ticket string `json:"ticket"`
  29. ExpiresIn int `json:"expires_in"`
  30. }
  31. // JsapiSignature 可以用来初始化 JS SDK
  32. type JsapiSignature struct {
  33. Timestamp int64 `json:"timestamp"`
  34. NonceStr string `json:"nonceStr"`
  35. Signature string `json:"signature"`
  36. }
  37. const (
  38. apiGetJSTicket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket"
  39. )
  40. // GetJSTicket 通过 access_token 获取 jsapi_ticket
  41. func GetJSTicket(authorizerToken string) (*JsapiTicketResult, error) {
  42. if authorizerToken == "" {
  43. return nil, errors.New("获取 jsapi_ticket authorizerToken 不能为空")
  44. }
  45. param := url.Values{}
  46. param.Set("access_token", authorizerToken)
  47. param.Set("type", "jsapi")
  48. resp, e2 := request.GetJSON(apiGetJSTicket, &param)
  49. if e2 != nil {
  50. return nil, e2
  51. }
  52. result := JsapiTicketResult{}
  53. if err := json.Unmarshal(resp, &result); err != nil {
  54. return nil, err
  55. }
  56. return &result, nil
  57. }
  58. // GetJSAPISignature 获取 JsapiSignature
  59. func GetJSAPISignature(ticket, url string) *JsapiSignature {
  60. timestamp := time.Now().Unix()
  61. timestampStr := strconv.FormatInt(timestamp, 10)
  62. nonceStr := utils.RandStr(16)
  63. s1 := "jsapi_ticket=" + ticket
  64. s2 := "&noncestr=" + nonceStr
  65. s3 := "&timestamp=" + timestampStr
  66. s4 := "&url=" + url
  67. plain := s1 + s2 + s3 + s4
  68. signature := fmt.Sprintf("%x", sha1.Sum([]byte(plain)))
  69. return &JsapiSignature{
  70. Timestamp: timestamp,
  71. NonceStr: nonceStr,
  72. Signature: signature,
  73. }
  74. }