| 屬性 | 類型 | 默認值 | 必填 | 說明 |
|---|---|---|---|---|
| appid | string | 是 | 小程序 appId | |
| secret | string | 是 | 小程序 appSecret | |
| js_code | string | 是 | 登錄時獲取的 code | |
| grant_type | string | 是 | 授權類型,此處只需填寫 authorization_code |
js_code 就是我們通過 wx.login 得到的 code,grant_type 為 authorization_code,只剩下 appid 和 secret 需要我們登錄微信公總平臺 里面找
小程序代碼演示
為了方便操作,我們在 index 頁面編寫了一個 button,通過 button 觸發事件
!--index.wxml--> view class="container"> button bindtap="onGetOpenId">點擊獲取openid/button> /view>
然后編寫事件函數:
//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);
}
});
}
}
});
}
});
那么,在小程序中發送 http 請求強制要求地址必須為 https,由于我們在開發中,我們可以把強制 https 的設置關閉
Go 語言后端代碼演示
小程序發過來的數據和去微信 API 獲取的數據都是放在 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
}
運行結果
運行代碼,在小程序中點擊:

結果:

到此這篇關于Golang通過小程序獲取微信openid的方法示例的文章就介紹到這了,更多相關Golang獲取openid內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
標簽:調研邀請 太原 貴陽 阿克蘇 廣西 西雙版納 慶陽 德州
巨人網絡通訊聲明:本文標題《Golang通過小程序獲取微信openid的方法示例》,本文關鍵詞 Golang,通,過小,程序,獲取,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。