前端代碼
data() {
return {
openid: "",
server: '',
code:''
};
},
mounted() {
this.getCode()
},
methods:{
getCode() {
// 非靜默授權(quán),第一次有彈框
this.code = '';
var callback_url = '回調(diào)地址'; // 獲取頁面url
var appid = 'APPID';
this.code = this.getUrlCode().code; // 截取code
if (this.code == null || this.code === '') {
// 如果沒有code,則去請求
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
callback_url
)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
} else {
// 當(dāng)code不等于空時(shí),調(diào)用后端接口獲取用戶信息
this.getUserInfo();
// 你自己的業(yè)務(wù)邏輯
}
},
getUserInfo() {
let token = uni.getStorageSync("token");
const header = {
"Content-Type": "application/json",
"Authorization": token
};
let data = {}
data.code = this.code
data.appid= '你的appid'
data.secret= '你的secret'
uni.request({
url: '接口地址',
data: data,
header: header,
timeout: 20000,
method: 'POST',
dataType: 'json',
success: (res) => {
this.setOpenid(res.data.openid);
uni.setStorageSync('openid', res.data.openid)
}
})
},
getUrlCode() {
// 截取url中的code方法
var url = location.search;
var theRequest = new Object();
if (url.indexOf('?') != -1) {
var str = url.substr(1);
var strs = str.split('&');
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
}
}
return theRequest;
},
}
后端php代碼
public function getOpenid(){
$code = input('post.code');
$param["appid"]=input('post.appid');
$param["secret"]=input('post.secret');
$param["code"]=$code;
$param["grant_type"]="authorization_code";
$json = $this->curlPost("https://api.weixin.qq.com/sns/oauth2/access_token",$param);
$rv=json_decode($json,true);
return json($rv);
}
public function curlPost($url = '', $postData = '', $options = array()) {
if (is_array($postData)) {
$postData = http_build_query($postData);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //設(shè)置cURL允許執(zhí)行的最長秒數(shù)
if (!empty($options)) {
curl_setopt_array($ch, $options);
}
//https請求 不驗(yàn)證證書和host
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-722041.html
文章來源:http://www.zghlxwxcb.cn/news/detail-722041.html
到了這里,關(guān)于uniapp實(shí)現(xiàn)公眾號微信登錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!