介绍

这期内容当中小编将会给大家带来有关使用Golang怎么通过小程序获取微信openid,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

<强>小程序获取openid的流程

那么小程序获取openid的流程具体如下

使用Golang怎么通过小程序获取微信openid

我们需要在小程序中调用wx.login()获取代码码,然后将这个代码码发送给后端,后端带着这个代码码和appid, appsecret向微信接口发起http请求获取openid。

<强>注意事项

在开发的小程序中的appid一定要和后端使用的appid保持一致,否则会获取openid失败

使用Golang怎么通过小程序获取微信openid

我们请求的微信API为身份验证。code2Session,

请求地址为:

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&秘密=SECRET& js_code=JSCODE& grant_type=authorization_code

所需的四个参数为:

属性类型默认值必填说明appidstring
是小程序appIdsecretstring
是小程序appSecretjs_codestring
是登录时获取的codegrant_typestring
是授权类型,此处只需填写authorization_code

js_code就是我们通过wx。登录得到的代码,grant_type为authorization_code,只剩下appid和秘密需要我们登录微信公总平台里面找

使用Golang怎么通过小程序获取微信openid”>, </p> <p> <强>小程序代码演示</强> </p> <p>为了方便操作,我们在索引页面编写了一个按钮,通过按钮触发事件</p> <pre类= & lt; !——index.wxml祝辞   & lt; view 类=癱ontainer"祝辞   ,& lt; button  bindtap=皁nGetOpenId"在点击获取openid   & lt;/view>

然后编写事件函数:

//index.js   页面({   ,onGetOpenId (), {   wx.login({才能   ,,,成功:res =祝辞,{   ,,,if  (res.code), {   ,,,,wx.request ({   ,,,,,url:,“http://localhost: 2020/openid"   ,,,,,方法:,“POST",   ,,,,,数据:,{   ,,,,,,代码:res.code   ,,,,,},   ,,,,,成功:,res =祝辞,{   ,,,,,,console.log (res);   ,,,,,}   ,,,,});   ,,,}   ,,}   ,,});   ,}   });

那么,在小程序中发送http请求强制要求地址必须为https,由于我们在开发中,我们可以把强制https的设置关闭

使用Golang怎么通过小程序获取微信openid”>, </p> <p> <强>去语言后端代码演示</强> </p> <p>小程序发过来的数据和去微信API获取的数据都是放在http的身体里,所以我们要从身体获取</p> <pre类= package 主要      import  (   “编码/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  {   ,才能返回   ,,}      var 才能;codeMap  map [string]字符串   err 才能;:=,json.NewDecoder (request.Body) .Decode(及codeMap)   if 才能;err  !=, nil  {   ,才能返回   ,,}   defer 才能;request.Body.Close ()      code 才能;:=,codeMap (“code")   openid,才能,err :=, sendWxAuthAPI(代码)   if 才能;err  !=, nil  {   ,才能返回   ,,}   fmt.Println才能(“my  openid",, openid)   }      const  (   code2sessionURL =,才能“https://api.weixin.qq.com/sns/jscode2session?appid=%s&秘密=% s& js_code=% s& grant_type=authorization_code"   appID 才能,,,,,,=,“你的AppID"   appSecret 才能,,,,=,“你的AppSecret"   )      func  sendWxAuthAPI (code 字符串),(字符串,,错误),{   url 才能;:=,fmt.Sprintf (appID, code2sessionURL,还以为,appSecret,代码)   职责,才能,err :=, http.DefaultClient.Get (url)   if 才能;err  !=, nil  {   ,,,return ““,犯错   ,,}   var 才能;wxMap  map [string]字符串   时间=err 才能;json.NewDecoder (resp.Body) .Decode(及wxMap)   if 才能;err  !=, nil  {   ,,,return ““,犯错   ,,}   defer 才能;resp.Body.Close ()      return 才能wxMap [“openid"], nil   null