Go
GO调取QQ小程序API接口
GO调取QQ小程序API接口
今天在调取微信小程序获取用户openId接口,由于之前有调过微信小程序的接口,所以比较轻松的拿到用户openId,在这里跟大家分享代码段,代码如下:
//引入模块
import (
"net/http"
"io/ioutil"
"encoding/json"
"fmt"
)
func getUserOpenId(code string)string {
//获取信息
appId := "QQ小程序appId"
secret := "QQ小程序secret"
//调取微信API接口
apiUrl := "https://api.q.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code"
resp, err := http.Get(apiUrl)
//判断调用是否失败
if err != nil {
return "系统API异常"
}
//关闭连接
defer resp.Body.Close()
//读取返回内容
result, err := ioutil.ReadAll(resp.Body)
//处理json
var resultList interface{}
errResult := json.Unmarshal(result, &resultList)
if errResult != nil {
return "JSON 解码失败"
}
//提取数据
resultDataList, _ := resultList.(map[string]interface{})
//判断结果
openIdResult := resultDataList["openid"]
//判断是否存在openId
if openIdResult == nil {
return "系统API参数错误"
}
//提取转化数据
openId = openIdResult.(string)
//返回
return openId
}大家如果有更优的方法,可以在评论区评论,跟大家分享~
0条评论