uniapp微信小程序WebApi_openid、phone接口獲取代碼詳解
前言
今天發(fā)現(xiàn)小程序數(shù)據(jù)接口訪問不到了,查詢是因為小程序禁用合法域名https://api.weixin.qq.com,索性就干脆做一次詳細的微信接口調(diào)用記錄。
不得不說,好久沒用可,微信這API改動真的大。閑話不說了,開干
一、查文檔
首先肯定是查API
uniapp文檔:https://uniapp.dcloud.net.cn/api/plugins/login.html
這是啥也不給啊,gerUserInfo棄用了,查微信API吧
微信API文檔:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/
查看后,就這兩個接口能使。獲取openid、phone,openid可以做用戶唯一識別,phone先保存起來吧
二、定流程
1、打開小程序-- > 2、獲取openid--> 3、openid 綁user(游客) --->4、獲取phone---> 5、openid、phone綁定user(注冊)--->6、下次訪問 openid直接讀取用戶
好了思路有了,就開始寫實現(xiàn),主要的就獲取openid、phone
三、uniapp實現(xiàn)
getOpenid() { // #ifdef H5 this.wxid="o9zUn7SMr5hI47oAGeMqU-pzExxx"; this.GetToken();//我的后臺業(yè)務(wù) // #endif // #ifdef MP-WEIXIN //獲取code uni.login({ provider: 'weixin', success: (res) => { console.log(res.code) //獲取code const code = res.code //獲取成功后 uni.request({ url: `https://api.weixin.qq.com/sns/jscode2session?appid=${this.appid}&secret=${this.secret}&js_code=$[code]&grant_type=authorization_code`, success: (res) => { //獲取session_key和openid,此處關(guān)聯(lián)后端進行業(yè)務(wù)處理 this.wxid = res.data.openid; this.GetToken();//我的后臺業(yè)務(wù) }, fail: (res) => { console.log(res.data) } }) }, fail: (res) => { console.log(res.data) } }); // #endif }
獲取openid 很成功,然后再獲取電話
open-type=“getPhoneNumber” @getphonenumber=“getPhoneNumber”
不管啥標(biāo)簽,這句是觸發(fā) 小程序接口的關(guān)鍵。
getPhoneNumber(e) { //console.log(e); if(e.errMsg!="getPhoneNumber:ok")return; const mycode=e.code; uni.request({ url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.appid}&secret=${this.secret}`, success: (res) => { console.log(res.data); var accessToken = res.data.access_token; uni.request({ url: "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, method: 'POST', data: { code:mycode }, success: (res) => { console.log("用戶手機號獲取"); console.log(res); //寫入緩存 this.user.moblie=res.data.phone_info.purePhoneNumber; this.user.name=this.user.name.replace("游客","用戶"); this.$assist.zset('user', this.user); this.AddUser(); } }) } }) }
運行很成功,上傳。
四、合法域名屏蔽
我以為這就完事了,很明顯我還是太年輕了
問題是,真機測試、微信開發(fā)者工具都成功,但線上訪問不到數(shù)據(jù)
一翻排查,原來是我屏蔽了測試的:合法域名檢測
當(dāng)我把這個選中的勾勾取消了,bug終于呈現(xiàn)在俺的眼前
我看了下,開發(fā)者工具啟動,這勾子默認啟動,你這就有點不合適了?? ( ‾? ?‾? )? ??
#¥%……&*()——,天下居然有這種事,自己家說自己的API地址不合法???
行吧,你是爸爸,咱把HTTP訪問寫后端就是
五、微信訪問遷移到后臺
1、創(chuàng)建用于json解析的model
using System.ComponentModel.DataAnnotations; namespace WebApi.Models { /// <summary> /// 微信jscode2session接口 返回對象 /// </summary> public class OpenidApiRes { /// <summary> /// 其中 [Required] 表示非空判斷 /// </summary> [Required] public string ? session_key { get; set; } [Required] public string? openid { get; set; } } /// <summary> /// 微信client_credential接口 返回對象 /// </summary> public class AccessApiRes { /// <summary> /// 其中 [Required] 表示非空判斷 /// </summary> [Required] public string? access_token { get; set; } } /// <summary> /// 微信getuserphonenumber接口 返回對象 /// </summary> public class MoblieApiRes { /// <summary> /// 其中 [Required] 表示非空判斷 /// </summary> [Required] public int ? errcode { get; set; } [Required] public string? errmsg { get; set; } [Required] public phone_info? phone_info { get; set; } } /// <summary> /// public class MoblieApiRes 子集 /// </summary> public class phone_info { /// <summary> /// 其中 [Required] 表示非空判斷 /// </summary> [Required] public string? phoneNumber { get; set; } [Required] public string? purePhoneNumber { get; set; } } }
2、網(wǎng)上隨便找個httphelper,
/// <summary> /// 向指定URL發(fā)送文本數(shù)據(jù) /// </summary> /// <param name="url">網(wǎng)址</param> /// <param name="postData">urlencode編碼的文本數(shù)據(jù)</param> /// <returns></returns> public string Post(string url, string postData) { byte[] data = encoding.GetBytes(postData); return Post(url, data); } /// <summary> /// 向指定URL發(fā)送字節(jié)數(shù)據(jù) /// </summary> /// <param name="url">網(wǎng)址</param> /// <param name="postData">發(fā)送的字節(jié)數(shù)組</param> /// <returns></returns> public string Post(string url, byte[] postData) { HttpWebRequest request = CreateRequest(url, "POST"); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postData.Length; request.KeepAlive = true; PostData(request, postData); respHtml = encoding.GetString(GetData(request)); return respHtml; }
注:這里的post ,就是下面的requestwx,改了個名
3、寫訪問
A、獲取openid
//--uniapp--- getOpenid() { // #ifdef MP-WEIXIN uni.login({ provider: 'weixin', success: (res) => { console.log(res.code) //獲取code const code = res.code this.GetToken(code);//把code傳到后端 }, fail: (res) => { console.log(res.data) } }); // #endif }
//--webapi---- string appid = MySet.WXConfig.Appid; string secret= MySet.WXConfig.Secret; string apiurl = $"https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={info.code}&grant_type=authorization_code"; string resdata = AppApi.requestwx(apiurl, ""); OpenidApiRes res = JsonConverter.DeserializeObject<OpenidApiRes>(resdata); if (res.openid == null) return BadRequest(""); string wxid = res.openid??"";
B、獲取手機號
//---uniapp---- getPhoneNumber(e) { //console.log(e); if(e.errMsg!="getPhoneNumber:ok")return; this.user.pwd=e.code;//懶得建字段,湊個塞吧 AddUser(); }
//--webapi---- string appid = MySet.WXConfig.Appid; string secret = MySet.WXConfig.Secret; string code = info.pwd??""; //1、獲取access_token string apiurl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}"; string resdata = AppApi.requestwx(apiurl, ""); AccessApiRes res = JsonConverter.DeserializeObject<AccessApiRes>(resdata); if (res.access_token == null) return BadRequest(""); string access_token = res.access_token ?? ""; //2、獲取userphonenumber apiurl = $"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={access_token}"; string data = "{\"code\":\"" + code + "\"}"; resdata = AppApi.requestwx(apiurl, data); MoblieApiRes res2 = JsonConverter.DeserializeObject<MoblieApiRes>(resdata); if (res2.errcode != 0) return BadRequest(""); string phone = res2.phone_info.phoneNumber ?? "";
上傳 測試,解決了。
對了,手機號獲取,是收費了,不過好在送了1000次。用著先把,不夠再充點。
六、加一個用戶昵稱、頭像
<input class="input" type="nickname" v-model="nickname" placeholder="請輸入昵稱" placeholder-style="color: #AAAAAA;">
<button class="button"open-type="chooseAvatar" @chooseavatar="chooseAvatarEvent"/>
微信這個有點bug,就選擇了昵稱,返回值為空,測試注意就行。真機測試、發(fā)布后還是沒問題
// 頭像選擇 chooseAvatarEvent(e) { this.imgtofile(e.detail.avatarUrl); }, //圖片鏈接轉(zhuǎn)二進制 并上傳圖片到服務(wù)器 imgtofile(src) { const fileSystemManager = uni.getFileSystemManager(); return new Promise((resolve, reject) => { fileSystemManager.readFile({ filePath: src, // 微信服務(wù)器 圖片臨時路徑 success: (data) => { let file = data.data; this.uploadFile(src, file).then((data) => { resolve(data); }); }, fail: (err) => { console.log('讀取文件失敗', err); } }); }); }, //上傳文件到服務(wù)器 根據(jù)項目對應(yīng)修改 uploadFile(tempFilePath, file) { let token = this.$assist.zget('token'); return new Promise((resolve, reject) => { uni.uploadFile({ url: this.$config.dataUrl+"Upload/Img",//你的 服務(wù)器地址 filePath: tempFilePath,//圖片地址 name: 'file', formData: { file: file,//文件流 biz: 'temp' }, header: { Authorization: 'Bearer ' + token, //自定義請求頭信息 }, success: (res) => { console.log(res); console.log(res.data); var datas=JSON.parse(res.data); this.userInfo.avatar= this.$assist.getimg(datas.data.fileUrl); }, fail: (err) => {} }); }); }
就是說 雖然可以獲取到微信頭像,但卻是臨時路徑(只讀),那肯定要下載并存到自己服務(wù)器上,對吧。
這兩也挺好玩的,隨便找個標(biāo)簽 open-type= 設(shè)置一下。測試一下分享和自帶客服吧。
總結(jié)
到此這篇關(guān)于uniapp微信小程序WebApi_openid、phone接口獲取的文章就介紹到這了,更多相關(guān)uniapp小程序WebApi_openid、phone接口獲取內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3報錯‘defineProps‘?is?not?defined的解決方法
最近工作中遇到vue3中使用defineProps中報錯,飄紅,所以這篇文章主要給大家介紹了關(guān)于Vue3報錯‘defineProps‘?is?not?defined的解決方法,需要的朋友可以參考下2023-01-01基于Vue中點擊組件外關(guān)閉組件的實現(xiàn)方法
下面小編就為大家分享一篇基于Vue中點擊組件外關(guān)閉組件的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03Vue引入高德地圖并觸發(fā)實現(xiàn)多個標(biāo)點的示例詳解
這篇文章主要介紹了Vue引入高德地圖并觸發(fā)實現(xiàn)多個標(biāo)點,主要是在public下的index.html中引入地圖,引入組件設(shè)置寬高100%,本文通過示例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-05-05Vue POST請求頭'Content-Type':'application/j
這篇文章主要介紹了Vue POST請求頭'Content-Type':'application/json;',data上傳過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03