一、配置本地開發(fā)環(huán)境
由于在小程序中使用 wx.request 發(fā)送請求時,會驗證請求地址是否是已經(jīng)被配置為服務器域名。在本地開發(fā)中,會去請求本地的接口。
為了成功發(fā)起請求,在本地開發(fā)時,需要在開發(fā)者工具中勾選:
詳情 --> 不校驗合法域名、web-view(業(yè)務域名)、TLS 版本以及 HTTPS 證書
二、獲取小程序的AppID、AppSecret
登錄微信公眾平臺,進入:
設置 -> 開發(fā)者設置

img
AppSecret 不會被明文顯示在頁面上,所以生成 AppSecret 后,請妥善保存。
三、獲取 js_code
出于安全考慮,api.weixin.qq.com 不能被配置為服務器域名,相關(guān)API也不能在小程序內(nèi)調(diào)用,所以我們需要在小程序的 app.js 中 wx.login 函數(shù)中,獲取 js_code,然后將 js_code 發(fā)送給后臺
//app.js
App({
onLaunch: function () {
// 登錄
wx.login({
success: res => {
// 發(fā)送 res.code 到后臺換取 openId, sessionKey, unionId
wx.request({
//獲取openid接口
url: 'http://localhost/openid',
data: {
js_code: res.code,
},
method: 'POST',
success: function (res) {
console.log(res)
}
})
}
})
}
})
四、后臺獲取 openid
請求地址:https://api.weixin.qq.com/sns/jscode2session
請求參數(shù):
{
"appid" : "<your AppId>",
"secret" : "<your AppSecret>",
"js_code" : "<your js_code>",
"grant_type" : "authorization_code"
}
返回參數(shù):
{
"session_key" : "<your session_key>",
"openid" : "<your openid>"
}