Skip to content
This repository was archived by the owner on Jul 9, 2020. It is now read-only.

Commit f6beedd

Browse files
committed
微信小程序 接口请求工具
1 parent 53b4f5c commit f6beedd

File tree

3 files changed

+107
-0
lines changed

3 files changed

+107
-0
lines changed

net/http/http.go

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package http
2+
3+
import (
4+
"io/ioutil"
5+
"net/http"
6+
nurl "net/url"
7+
"strings"
8+
)
9+
10+
func Post(url, contentType string, args map[string]string) (result string, err error) {
11+
if contentType == "" {
12+
contentType = "application/x-www-form-urlencoded"
13+
}
14+
resp, err := http.Post(url, contentType, strings.NewReader(argsEncode(args)))
15+
if err != nil {
16+
return
17+
}
18+
defer resp.Body.Close()
19+
body, err := ioutil.ReadAll(resp.Body)
20+
if err != nil {
21+
return
22+
}
23+
result = string(body)
24+
return
25+
}
26+
27+
func Get(url string, args map[string]string) (result string, err error) {
28+
if args != nil {
29+
url += "?" + argsEncode(args)
30+
}
31+
resp, err := http.Get(url)
32+
if err != nil {
33+
return
34+
}
35+
defer resp.Body.Close()
36+
body, err := ioutil.ReadAll(resp.Body)
37+
if err != nil {
38+
return
39+
}
40+
result = string(body)
41+
return
42+
}
43+
44+
func argsEncode(params map[string]string) string {
45+
args := nurl.Values{}
46+
for k, v := range params {
47+
args.Set(k, v)
48+
}
49+
return args.Encode()
50+
}

wechat/applet/applet.go

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package applet
2+
3+
import (
4+
"errors"
5+
6+
"github.com/Undesoft/pkg/net/http"
7+
)
8+
9+
var (
10+
AppId = ""
11+
AppSecret = ""
12+
)
13+
14+
func Execute(url string, args map[string]string) (result string, err error) {
15+
err = checkConfig()
16+
if err != nil {
17+
return
18+
}
19+
args["appid"] = AppId
20+
args["secret"] = AppSecret
21+
return http.Get(url, args)
22+
}
23+
24+
func checkConfig() error {
25+
if AppId == "" {
26+
return errors.New("AppKey 不能为空")
27+
}
28+
if AppSecret == "" {
29+
return errors.New("AppSecret 不能为空")
30+
}
31+
return nil
32+
}

wechat/applet/applet_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package applet
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
func init() {
9+
AppId = "123"
10+
AppSecret = "abc"
11+
}
12+
13+
func TestExecute(t *testing.T) {
14+
// 小程序登录
15+
url := "https://api.weixin.qq.com/sns/jscode2session"
16+
args := map[string]string{
17+
"js_code": "登录时获取的 code",
18+
"grant_type": "authorization_code",
19+
}
20+
result, err := Execute(url, args)
21+
if err != nil {
22+
t.Fatal(err)
23+
}
24+
fmt.Println(result)
25+
}

0 commit comments

Comments
 (0)