Go
Go调取微信小程序API接口
Go调取微信小程序API接口
今天在调取微信小程序获取用户openId接口,可能刚入门,功力不深,中途碰到了一些坑,最后还是成功调取接口并拿到用户openId,在这里跟大家分享代码段,代码如下:
//引入模块
import (
"net/http"
"io/ioutil"
"encoding/json"
"fmt"
)
func getUserOpenId(code string) string {
//获取信息
appId := "微信小程序appId"
secret := "微信小程序secret"
//调取微信API接口
apiUrl := "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code"
resp, err := http.Get(apiUrl)
//判断调用是否失败
if err != nil {
return ""
}
//关闭连接
defer resp.Body.Close()
//读取返回内容
result, err := ioutil.ReadAll(resp.Body)
//处理json
var resultList interface{}
errResult := json.Unmarshal(result, &resultList)
if errResult != nil {
return ""
}
//提取数据
resultDataList, _ := resultList.(map[string]interface{})
//判断结果
openIdResult := resultDataList["openid"]
//判断是否存在openId
if openIdResult == nil {
//获取错误结果
errorMsg := fmt.Sprint(resultDataList["errmsg"])
return errorMsg
}
//提取转化数据
openId = openIdResult.(string)
//返回
return openId
}这样就成功调取微信API并获得用户openId,大家如果有更好的方式,可以在下面评论~
0条评论