Skip to content

Commit

Permalink
Able to set menu now
Browse files Browse the repository at this point in the history
  • Loading branch information
songquanpeng committed Nov 5, 2022
1 parent aa6358d commit f59a659
Show file tree
Hide file tree
Showing 7 changed files with 126 additions and 34 deletions.
9 changes: 8 additions & 1 deletion common/access-token-store.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func RefreshAccessToken() {
SysError("failed to refresh access token: " + err.Error())
return
}
defer responseData.Body.Close()
var res response
err = json.NewDecoder(responseData.Body).Decode(&res)
if err != nil {
Expand All @@ -61,8 +62,14 @@ func RefreshAccessToken() {
SysLog("access token refreshed")
}

func GetAccessToken() (string, int) {
func GetAccessTokenAndExpirationSeconds() (string, int) {
s.Mutex.RLock()
defer s.Mutex.RUnlock()
return s.AccessToken, s.ExpirationSeconds
}

func GetAccessToken() string {
s.Mutex.RLock()
defer s.Mutex.RUnlock()
return s.AccessToken
}
9 changes: 9 additions & 0 deletions common/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ var WeChatAppID = ""
var WeChatAppSecret = ""
var WeChatEncodingAESKey = ""
var WeChatOwnerID = ""
var WeChatMenu = `{
"button": [
{
"type": "click",
"name": "登录验证",
"key": "USER_VERIFICATION"
}
]
}`

var SessionSecret = uuid.New().String()
var SQLitePath = ".wechat-server.db"
Expand Down
32 changes: 0 additions & 32 deletions controller/misc.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
package controller

import (
"crypto/sha1"
"encoding/hex"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"sort"
"strings"
"wechat-server/common"
"wechat-server/model"
)
Expand Down Expand Up @@ -40,34 +36,6 @@ func GetNotice(c *gin.Context) {
return
}

func WeChatVerification(c *gin.Context) {
// https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html
signature := c.Query("signature")
timestamp := c.Query("timestamp")
nonce := c.Query("nonce")
echoStr := c.Query("echostr")
arr := []string{common.WeChatToken, timestamp, nonce}
sort.Strings(arr)
str := strings.Join(arr, "")
hash := sha1.Sum([]byte(str))
hexStr := hex.EncodeToString(hash[:])
if signature == hexStr {
c.String(http.StatusOK, echoStr)
} else {
c.Status(http.StatusForbidden)
}
}

func GetAccessToken(c *gin.Context) {
accessToken, expiration := common.GetAccessToken()
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"access_token": accessToken,
"expiration": expiration,
})
}

func SendEmailVerification(c *gin.Context) {
email := c.Query("email")
if err := common.Validate.Var(email, "required,email"); err != nil {
Expand Down
29 changes: 29 additions & 0 deletions controller/option.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package controller

import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"strings"
Expand Down Expand Up @@ -55,6 +57,33 @@ func UpdateOption(c *gin.Context) {
})
return
}
if option.Key == "WeChatMenu" {
httpResponse, err := http.Post(fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s", common.GetAccessToken()), "application/json", bytes.NewBuffer([]byte(option.Value)))
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
defer httpResponse.Body.Close()
var res wechatResponse
err = json.NewDecoder(httpResponse.Body).Decode(&res)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
if res.ErrCode != 0 {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": res.ErrMsg,
})
return
}
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
Expand Down
44 changes: 44 additions & 0 deletions controller/wechat.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package controller

import (
"crypto/sha1"
"encoding/hex"
"github.com/gin-gonic/gin"
"net/http"
"sort"
"strings"
"wechat-server/common"
)

type wechatResponse struct {
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}

func WeChatVerification(c *gin.Context) {
// https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html
signature := c.Query("signature")
timestamp := c.Query("timestamp")
nonce := c.Query("nonce")
echoStr := c.Query("echostr")
arr := []string{common.WeChatToken, timestamp, nonce}
sort.Strings(arr)
str := strings.Join(arr, "")
hash := sha1.Sum([]byte(str))
hexStr := hex.EncodeToString(hash[:])
if signature == hexStr {
c.String(http.StatusOK, echoStr)
} else {
c.Status(http.StatusForbidden)
}
}

func GetAccessToken(c *gin.Context) {
accessToken, expiration := common.GetAccessTokenAndExpirationSeconds()
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"access_token": accessToken,
"expiration": expiration,
})
}
3 changes: 3 additions & 0 deletions model/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ func InitOptionMap() {
common.OptionMap["WeChatAppSecret"] = ""
common.OptionMap["WeChatEncodingAESKey"] = ""
common.OptionMap["WeChatOwnerID"] = ""
common.OptionMap["WeChatMenu"] = common.WeChatMenu
common.OptionMapRWMutex.Unlock()
options, _ := AllOption()
for _, option := range options {
Expand Down Expand Up @@ -121,5 +122,7 @@ func updateOptionMap(key string, value string) {
common.WeChatEncodingAESKey = value
case "WeChatOwnerID":
common.WeChatOwnerID = value
case "WeChatMenu":
common.WeChatMenu = value
}
}
34 changes: 33 additions & 1 deletion web/src/components/WeChatSetting.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useEffect, useState } from 'react';
import { Form, Grid } from 'semantic-ui-react';
import { API, showError } from '../helpers';
import { Link } from 'react-router-dom';

const WeChatSetting = () => {
let [inputs, setInputs] = useState({
Expand All @@ -9,6 +10,7 @@ const WeChatSetting = () => {
WeChatAppSecret: '',
WeChatEncodingAESKey: '',
WeChatOwnerID: '',
WeChatMenu: '',
});
let [loading, setLoading] = useState(false);

Expand Down Expand Up @@ -48,7 +50,15 @@ const WeChatSetting = () => {
};

const handleInputChange = async (e, { name, value }) => {
await updateOption(name, value);
if (name === 'WeChatMenu') {
setInputs((inputs) => ({ ...inputs, [name]: value }));
} else {
await updateOption(name, value);
}
};

const submitWeChatMenu = async () => {
await updateOption('WeChatMenu', inputs.WeChatMenu);
};

return (
Expand Down Expand Up @@ -100,6 +110,28 @@ const WeChatSetting = () => {
onChange={handleInputChange}
/>
</Form.Group>
<Form.Group widths="equal">
<Form.TextArea
label={
<p>
公众号菜单(
<a
target="_blank"
href="https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html"
>
格式请参考此处
</a>
</p>
}
placeholder="JSON 格式"
value={inputs.WeChatMenu}
name="WeChatMenu"
onChange={handleInputChange}
style={{ minHeight: 150, fontFamily: 'JetBrains Mono, Consolas' }}
/>
</Form.Group>
<Form.Button onClick={submitWeChatMenu}>更新公众号菜单</Form.Button>
</Form>
</Grid.Column>
</Grid>
Expand Down

0 comments on commit f59a659

Please sign in to comment.