uniapp微信小程序WebApi_openid、phone接口獲取代碼詳解
前言
今天發(fā)現(xiàn)小程序數(shù)據(jù)接口訪問(wèn)不到了,查詢是因?yàn)樾〕绦蚪煤戏ㄓ蛎鹔ttps://api.weixin.qq.com,索性就干脆做一次詳細(xì)的微信接口調(diào)用記錄。
不得不說(shuō),好久沒(méi)用可,微信這API改動(dòng)真的大。閑話不說(shuō)了,開(kāi)干
一、查文檔
首先肯定是查API
uniapp文檔:https://uniapp.dcloud.net.cn/api/plugins/login.html


這是啥也不給啊,gerUserInfo棄用了,查微信API吧
微信API文檔:https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/

查看后,就這兩個(gè)接口能使。獲取openid、phone,openid可以做用戶唯一識(shí)別,phone先保存起來(lái)吧
二、定流程
1、打開(kāi)小程序-- > 2、獲取openid--> 3、openid 綁user(游客) --->4、獲取phone---> 5、openid、phone綁定user(注冊(cè))--->6、下次訪問(wèn) openid直接讀取用戶
好了思路有了,就開(kāi)始寫(xiě)實(shí)現(xiàn),主要的就獲取openid、phone
三、uniapp實(shí)現(xiàn)
getOpenid() {
// #ifdef H5
this.wxid="o9zUn7SMr5hI47oAGeMqU-pzExxx";
this.GetToken();//我的后臺(tái)業(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)后端進(jìn)行業(yè)務(wù)處理
this.wxid = res.data.openid;
this.GetToken();//我的后臺(tái)業(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("用戶手機(jī)號(hào)獲取");
console.log(res);
//寫(xiě)入緩存
this.user.moblie=res.data.phone_info.purePhoneNumber;
this.user.name=this.user.name.replace("游客","用戶");
this.$assist.zset('user', this.user);
this.AddUser();
}
})
}
})
}
運(yùn)行很成功,上傳。
四、合法域名屏蔽
我以為這就完事了,很明顯我還是太年輕了
問(wèn)題是,真機(jī)測(cè)試、微信開(kāi)發(fā)者工具都成功,但線上訪問(wèn)不到數(shù)據(jù)
一翻排查,原來(lái)是我屏蔽了測(cè)試的:合法域名檢測(cè)


當(dāng)我把這個(gè)選中的勾勾取消了,bug終于呈現(xiàn)在俺的眼前
我看了下,開(kāi)發(fā)者工具啟動(dòng),這勾子默認(rèn)啟動(dòng),你這就有點(diǎn)不合適了?? ( ‾? ?‾? )? ??

#¥%……&*()——,天下居然有這種事,自己家說(shuō)自己的API地址不合法???


行吧,你是爸爸,咱把HTTP訪問(wèn)寫(xiě)后端就是
五、微信訪問(wèn)遷移到后臺(tái)
1、創(chuàng)建用于json解析的model
using System.ComponentModel.DataAnnotations;
namespace WebApi.Models
{
/// <summary>
/// 微信jscode2session接口 返回對(duì)象
/// </summary>
public class OpenidApiRes
{
/// <summary>
/// 其中 [Required] 表示非空判斷
/// </summary>
[Required]
public string ? session_key { get; set; }
[Required]
public string? openid { get; set; }
}
/// <summary>
/// 微信client_credential接口 返回對(duì)象
/// </summary>
public class AccessApiRes
{
/// <summary>
/// 其中 [Required] 表示非空判斷
/// </summary>
[Required]
public string? access_token { get; set; }
}
/// <summary>
/// 微信getuserphonenumber接口 返回對(duì)象
/// </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)上隨便找個(gè)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,改了個(gè)名
3、寫(xiě)訪問(wèn)
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、獲取手機(jī)號(hào)
//---uniapp----
getPhoneNumber(e) {
//console.log(e);
if(e.errMsg!="getPhoneNumber:ok")return;
this.user.pwd=e.code;//懶得建字段,湊個(gè)塞吧
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 ?? "";
上傳 測(cè)試,解決了。

對(duì)了,手機(jī)號(hào)獲取,是收費(fèi)了,不過(guò)好在送了1000次。用著先把,不夠再充點(diǎn)。

六、加一個(gè)用戶昵稱、頭像

<input class="input" type="nickname" v-model="nickname" placeholder="請(qǐng)輸入昵稱" placeholder-style="color: #AAAAAA;">

<button class="button"open-type="chooseAvatar" @chooseavatar="chooseAvatarEvent"/>
微信這個(gè)有點(diǎn)bug,就選擇了昵稱,返回值為空,測(cè)試注意就行。真機(jī)測(cè)試、發(fā)布后還是沒(méi)問(wèn)題
// 頭像選擇
chooseAvatarEvent(e) {
this.imgtofile(e.detail.avatarUrl);
},
//圖片鏈接轉(zhuǎn)二進(jìn)制 并上傳圖片到服務(wù)器
imgtofile(src) {
const fileSystemManager = uni.getFileSystemManager();
return new Promise((resolve, reject) => {
fileSystemManager.readFile({
filePath: src, // 微信服務(wù)器 圖片臨時(shí)路徑
success: (data) => {
let file = data.data;
this.uploadFile(src, file).then((data) => {
resolve(data);
});
},
fail: (err) => {
console.log('讀取文件失敗', err);
}
});
});
},
//上傳文件到服務(wù)器 根據(jù)項(xiàng)目對(duì)應(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, //自定義請(qǐng)求頭信息
},
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) => {}
});
});
}
就是說(shuō) 雖然可以獲取到微信頭像,但卻是臨時(shí)路徑(只讀),那肯定要下載并存到自己服務(wù)器上,對(duì)吧。

這兩也挺好玩的,隨便找個(gè)標(biāo)簽 open-type= 設(shè)置一下。測(cè)試一下分享和自帶客服吧。
總結(jié)
到此這篇關(guān)于uniapp微信小程序WebApi_openid、phone接口獲取的文章就介紹到這了,更多相關(guān)uniapp小程序WebApi_openid、phone接口獲取內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Vue3+TypeScript實(shí)現(xiàn)鼠標(biāo)框選功能
這篇文章主要介紹了基于Vue3+TypeScript實(shí)現(xiàn)鼠標(biāo)框選功能,文中通過(guò)代碼示例給大家講解的非常纖細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-07-07
解決VantUI popup 彈窗不彈出或無(wú)蒙層的問(wèn)題
這篇文章主要介紹了解決VantUI popup 彈窗不彈出或無(wú)蒙層的問(wèn)題。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-11-11
Element-UI清空表單及驗(yàn)證不生效的問(wèn)題解決
本文主要介紹了Element-UI清空表單及驗(yàn)證不生效的問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08
vue3中reactive數(shù)據(jù)被重新賦值后無(wú)法雙向綁定的解決
這篇文章主要介紹了vue3中reactive數(shù)據(jù)被重新賦值后無(wú)法雙向綁定的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
解決vue-cli webpack打包后加載資源的路徑問(wèn)題
今天小編就為大家分享一篇解決vue-cli webpack打包后加載資源的路徑問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09
vue-cli項(xiàng)目無(wú)法用本機(jī)IP訪問(wèn)的解決方法
今天小編就為大家分享一篇vue-cli項(xiàng)目無(wú)法用本機(jī)IP訪問(wèn)的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09

