知識
不管是網(wǎng)站,軟件還是小程序,都要直接或間接能為您產(chǎn)生價值,我們在追求其視覺表現(xiàn)的同時,更側(cè)重于功能的便捷,營銷的便利,運(yùn)營的高效,讓網(wǎng)站成為營銷工具,讓軟件能切實提升企業(yè)內(nèi)部管理水平和效率。優(yōu)秀的程序為后期升級提供便捷的支持!
您當(dāng)前位置>首頁 » 新聞資訊 » 小程序相關(guān) >
微信小程序獲取openid的兩種方法
發(fā)表時間:2021-1-5
發(fā)布人:葵宇科技
瀏覽次數(shù):52
第一種:使用云開發(fā)
這種比較簡單,只需要開通云開發(fā),創(chuàng)建云函數(shù),調(diào)用云函數(shù)就可獲得。
調(diào)用云函數(shù) Promise Cloud.callFunction(Object object) 返回一個Promise對象,所以不用考慮異步問題。
callFunction說明 https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/functions/Cloud.callFunction.html
具體代碼如下:
我這里云函數(shù)名為helloCloud
// helloCloud-index.js 云函數(shù)入口函數(shù)
exports.main = async (event, context) => {
let{ APPID,OPENID}=cloud.getWXContext()
return {
APPID,
OPENID
}
//------------------------------------------------------
//云函數(shù)調(diào)用
wx.cloud.callFunction({
name:'helloCloud',
data:{
message:'helloCloud',
}
}).then(res=>{
console.log(res)//res就將appid和openid返回了
//做一些后續(xù)操作,不用考慮代碼的異步執(zhí)行問題。
})
第二種:不使用云開發(fā)
這種方式就需要開發(fā)者有自己的后臺了。
首先需要在微信小程序調(diào)用登錄開放接口 wx.login() 獲取用戶登陸憑證code。
wx.login()接口說明 https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
然后,向自己的服務(wù)器發(fā)送請求,并將code一起發(fā)送過去。
wx.login({
success (res) {
if (res.code) {
//發(fā)起網(wǎng)絡(luò)請求
wx.request({
url: '自己的服務(wù)器請求接口',
data: {
code: res.code
}
})
} else {
console.log('登錄失敗!' + res.errMsg)
}
}
})
接下來,在自己的服務(wù)端調(diào)用auth.code2Session接口,我這里是用Java后臺。
auth.code2Session接口說明 https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
@RequestMapping("/testopenid")
public String getUserInfo(@RequestParam(name = "code") String code) throws Exception {
System.out.println("code" + code);
String url = "https://api.weixin.qq.com/sns/jscode2session";
url += "?appid=xxxxxxxxxxxxx";//自己的appid
url += "&secret=xxxxxxxxxxxxxxxxxxx";//自己的appSecret
url += "&js_code=" + code;
url += "&grant_type=authorization_code";
url += "&connect_redirect=1";
String res = null;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// DefaultHttpClient();
HttpGet httpget = new HttpGet(url); //GET方式
CloseableHttpResponse response = null;
// 配置信息
RequestConfig requestConfig = RequestConfig.custom() // 設(shè)置連接超時時間(單位毫秒)
.setConnectTimeout(5000) // 設(shè)置請求超時時間(單位毫秒)
.setConnectionRequestTimeout(5000) // socket讀寫超時時間(單位毫秒)
.setSocketTimeout(5000) // 設(shè)置是否允許重定向(默認(rèn)為true)
.setRedirectsEnabled(false).build(); // 將上面的配置信息 運(yùn)用到這個Get請求里
httpget.setConfig(requestConfig); // 由客戶端執(zhí)行(發(fā)送)Get請求
response = httpClient.execute(httpget); // 從響應(yīng)模型中獲取響應(yīng)實體
HttpEntity responseEntity = response.getEntity();
System.out.println("響應(yīng)狀態(tài)為:" + response.getStatusLine());
if (responseEntity != null) {
res = EntityUtils.toString(responseEntity);
System.out.println("響應(yīng)內(nèi)容長度為:" + responseEntity.getContentLength());
System.out.println("響應(yīng)內(nèi)容為:" + res);
}
// 釋放資源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
JSONObject jo = JSON.parseObject(res);
String openid = jo.getString("openid");
System.out.println("openid" + openid);
return openid;
}
這樣就獲得openid了。
但是在實際應(yīng)用場景中,往往需要在界面展示之前獲得openid來做一些操作或者什么。
用以上代碼會發(fā)現(xiàn),openid后臺雖然獲取到了,但是小程序端頁面剛展示時好像并沒有獲取到openid,但是之后查看數(shù)據(jù)能看到openid。
這是因為wx.request()是異步請求。也就是在請求的過程中,小程序的其他工作沒有因為請求而停止。
所以,我們需要將請求封裝成一個返回Promise對象的函數(shù)。
這樣就能在請求完做一些后續(xù)操作。
代碼如下:
//封裝wx.request()
function request(requestMapping, data, requestWay, contentType) {
wx.showLoading({
title: '請稍后',
})
return new Promise(function(resolve, reject) {
console.log('請求中。。。。。')
wx.request({
url: '自己的服務(wù)器地址' + requestMapping,
data: data,
header: {
'content-type': contentType // 默認(rèn)值
},
timeout: 3000,
method: requestWay,
success(res) {
//console.log(res)
if (res.data.success == false || res.data.statusCode == 404) {
reject(res)
} else {
resolve(res)
}
},
fail: (e) => {
wx.showToast({
title: '連接失敗',
icon: 'none'
})},
complete: () => {
wx.hideLoading()
}
})
})
}
?//獲取openid
function getOpenId(app, that){
return new Promise(function (resolve, reject) {
wx.login({
success: function (yes) {
// 發(fā)送 res.code 到后臺換取 openId, sessionKey, unionId
var requestMapping = '/testopenid'
var data = http://www.wxapp-union.com/{
code: yes.code
}
var requestWay = 'GET'
var contentType = 'application/json'
var p =request(requestMapping, data, requestWay, contentType)
p.then(res => {
//console.log(res) 做一些后續(xù)操作
app.globalData.openId = res.data;
resolve(res)
}).catch(e => {
reject(e)
})
},
fail(e) {
console.log(e)
}
})
})
}
這樣就解決了因為異步獲取不到數(shù)據(jù)的問題。
相關(guān)案例查看更多
相關(guān)閱讀
- painter
- 云南網(wǎng)站開發(fā)
- 網(wǎng)站建設(shè)百度官方
- 網(wǎng)站建設(shè)服務(wù)公司
- 云南網(wǎng)站制作
- 百度小程序公司
- 云南網(wǎng)絡(luò)公司
- 昆明小程序公司
- 百度自然排名
- 云南網(wǎng)站建設(shè)百度
- 云南軟件定制
- 網(wǎng)站制作哪家好
- 小程序模板開發(fā)公司
- 云南網(wǎng)站建設(shè)選
- 云南小程序被騙蔣軍
- 百度人工排名
- 云南小程序開發(fā)課程
- 排名
- 小程序表單
- 微分銷
- web前端
- 網(wǎng)站建設(shè)需要多少錢
- 軟件定制
- 報廢車回收管理系統(tǒng)
- 怎么做網(wǎng)站
- 昆明軟件公司
- 小程序分銷商城
- 微信小程序
- 小程序設(shè)計
- 小程序開發(fā)排名前十名