四时宝库

程序员的知识宝库

微信小程序获取用户的手机号码(小程序 获取用户手机号)

在小程序开发中,特别是一些电商平台,需要获取用户的手机号码.

前端是无法直接获取用户手机号码,前端需要用户点击同意授权后,把获取到用户的code传给后端.后端收到code后,要先获取一下token(获取token的代码,下次发).具体代码如下(我是用golang原生写的).

//获取微信手机号码

func GetPhoneNumber(wxCode string) interface{} {
   //获取用户的token 明天发获取token的代码
   accessToken := GetAccessToken()

   httpData := make(map[string]interface{})
   httpData["code"] = wxCode

   httpDataCode, _ := json.Marshal(httpData)

   httpUrl := "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken
   client := &http.Client{}
   req, _ := http.NewRequest("POST", httpUrl, bytes.NewReader(httpDataCode))
   req.Header.Add("content-type", "application/json")

   res, _ := client.Do(req)

   defer func() {
      _ = res.Body.Close()
   }()

   body, _ := ioutil.ReadAll(res.Body)
   fmt.Print(string(body))
   var bodyData map[string]interface{}
   _ = json.Unmarshal(body, &bodyData)
   return bodyData["phone_info"].(interface{}).(map[string]interface{})["purePhoneNumber"]
}

注意!!!
  "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken 
token一定要拼接到url后面,至于为啥,微信规定的哈.

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接