| 屬性 | 類(lèi)型 | 默認(rèn)值 | 必填 | 說(shuō)明 |
|---|---|---|---|---|
| appid | string | 是 | 小程序 appId | |
| secret | string | 是 | 小程序 appSecret | |
| js_code | string | 是 | 登錄時(shí)獲取的 code | |
| grant_type | string | 是 | 授權(quán)類(lèi)型,此處只需填寫(xiě) authorization_code |
js_code 就是我們通過(guò) wx.login 得到的 code,grant_type 為 authorization_code,只剩下 appid 和 secret 需要我們登錄微信公總平臺(tái) 里面找
小程序代碼演示
為了方便操作,我們?cè)?index 頁(yè)面編寫(xiě)了一個(gè) button,通過(guò) button 觸發(fā)事件
!--index.wxml--> view class="container"> button bindtap="onGetOpenId">點(diǎn)擊獲取openid/button> /view>
然后編寫(xiě)事件函數(shù):
//index.js
Page({
onGetOpenId() {
wx.login({
success: res => {
if (res.code) {
wx.request({
url: "http://localhost:2020/openid",
method: "POST",
data: {
code: res.code
},
success: res => {
console.log(res);
}
});
}
}
});
}
});
那么,在小程序中發(fā)送 http 請(qǐng)求強(qiáng)制要求地址必須為 https,由于我們?cè)陂_(kāi)發(fā)中,我們可以把強(qiáng)制 https 的設(shè)置關(guān)閉
Go 語(yǔ)言后端代碼演示
小程序發(fā)過(guò)來(lái)的數(shù)據(jù)和去微信 API 獲取的數(shù)據(jù)都是放在 http body 里,所以我們要從 body 獲取
package main
import (
"encoding/json"
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/openid", getOpenID)
http.ListenAndServe(":2020", nil)
}
func getOpenID(writer http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodPost {
return
}
var codeMap map[string]string
err := json.NewDecoder(request.Body).Decode(codeMap)
if err != nil {
return
}
defer request.Body.Close()
code := codeMap["code"]
openid, err := sendWxAuthAPI(code)
if err != nil {
return
}
fmt.Println("my openid", openid)
}
const (
code2sessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%ssecret=%sjs_code=%sgrant_type=authorization_code"
appID = "你的AppID"
appSecret = "你的AppSecret"
)
func sendWxAuthAPI(code string) (string, error) {
url := fmt.Sprintf(code2sessionURL, appID, appSecret, code)
resp, err := http.DefaultClient.Get(url)
if err != nil {
return "", err
}
var wxMap map[string]string
err = json.NewDecoder(resp.Body).Decode(wxMap)
if err != nil {
return "", err
}
defer resp.Body.Close()
return wxMap["openid"], nil
}
運(yùn)行結(jié)果
運(yùn)行代碼,在小程序中點(diǎn)擊:

結(jié)果:

到此這篇關(guān)于Golang通過(guò)小程序獲取微信openid的方法示例的文章就介紹到這了,更多相關(guān)Golang獲取openid內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:調(diào)研邀請(qǐng) 太原 貴陽(yáng) 阿克蘇 廣西 西雙版納 慶陽(yáng) 德州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Golang通過(guò)小程序獲取微信openid的方法示例》,本文關(guān)鍵詞 Golang,通,過(guò)小,程序,獲取,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。