参考文档:
https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html
uniapp:
<template>
<view class="content">
<button open-type="getPhoneNumber" class="login_button" @getphonenumber="login" v-show="!logged">登录</button>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
},
methods: {
//登录按钮
login(e) {
console.log(e)
var detail = e.detail
if (detail.errMsg == "getPhoneNumber:ok") {
console.log("用户同意授权")
var code = detail.code
uni.request({
url: "https://gen.dongpaiweb.cn/index/getPhone", //调用接口
method: 'POST',
header: {
'content-type': 'application/json'
},
data: {
code: code, //请求体中封装code
},
success(e) {
console.log(e)
var userId = e.data.phone_info.purePhoneNumber;
uni.setStorage({
key: "userId",
data: userId,
success() {
uni.switchTab({
url: "../../pages/homePage/homepage"
})
}
})
},
fail(e) {
uni.showModal({
title: "错误!",
content: "网络错误!",
complete() {
}
})
}
})
}
}
}
}
</script>
<style>
@import url("../../static/font/iconfont.css");
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.name{
font-size: 24px;
width: 90%;
margin:0 auto;
text-align: center;
font-family: 'siyuanheiti-medium';
}
.button{
background: #00c800;
color: #fff;
border-radius: 50px;
margin: 50rpx 0;
padding: 23rpx 100rpx;
display: flex;
align-items: center;
}
.button .text{
margin-left: 5px;
}
.privacy{
display: flex;
align-items: center;
}
.privacy .text{
font-size: 26rpx;
color: #aaa;
}
.privacy .checkbox{
transform:scale(0.6);
}
</style>php端:
public function getPhone(){
$code=input('code');
$appid='wxb707axxxxbe7b';
$appSecret='31c2e9d3b4551fxxxx51c04';
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appSecret;
$response=file_get_contents($url);
$data= json_decode($response, true);
//获取手机号
$code_data = json_encode(['code'=>$code]);
$url='https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$data['access_token'];
$headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $code_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
halt($output);
}效果:

