思路:
- 小程序登录获取code,将code传到后台;
- 后台用code得到微信用户id,即openid,将openid存储在用户表中,完成绑定
- 登录时,再次获取code并传给后台,得到openid,若用户表中存在,便可直接登录
以下仅是代码片段,更多代码在Github
back_end/application/api/controller
mini_program/pages/student_mine
mini_program/pages/login
微信与小程序账号绑定
小程序前端获取code,将code与id传回后台
wx_binding: function () {
var that = this
wx.login({
success: function (res) {
console.log("code: ", res.code)
wx.request({
url: '******/user/wxbinding',
data: {
code: res.code,
id: getApp().globalData.user.id,
},
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
})
}
})
}
ThinkPHP5后端接受到code,用code得到openid,并将openid与账号id绑定
public function wxBinding() {
$url = "https://api.weixin.qq.com/sns/jscode2session";
$params = array();
$params['appid'] = '******';
$params['secret'] = '******';
$params['js_code'] = $_POST['code'];
$params['grant_type'] = 'authorization_code';
$arr = $this -> httpCurl($url, $params, 'POST');
$arr = json_decode($arr, true);
if (isset($arr['errcode']) && !empty($arr['errcode'])) {
return json(['error_code' => '2', 'msg' => $arr['errmsg'], "result" => null]);
}
$openid = $arr['openid'];
$bind = db('user') -> where('id', $_POST['id']) -> update(['openid' => $openid]);
if ($bind) {
return json(['error_code' => '0', 'msg' => '绑定成功']);
} else {
return json(['error_code' => '1', 'msg' => '绑定失败']);
}
}
解密获取openid
use \think\Exception;
function httpCurl($url, $params, $method = 'GET', $header = array(), $multi = false) {
date_default_timezone_set('PRC');
$opts = array(
CURLOPT_TIMEOUT => 30,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_HTTPHEADER => $header,
CURLOPT_COOKIESESSION => true,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_COOKIE
=> session_name(). '='.session_id(),
);
switch (strtoupper($method)) {
case 'GET':
$opts[CURLOPT_URL] = $url. '?'.http_build_query($params);
break;
case 'POST':
$params = $multi ? $params : http_build_query($params);
$opts[CURLOPT_URL] = $url;
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = $params;
break;
default:
throw new Exception('不支持的请求方式!');
}
$ch = curl_init();
curl_setopt_array($ch, $opts);
$data = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error) throw new Exception('请求发生错误:'.$error);
return $data;
}
微信登录小程序
小程序前端返回code
wx.login({
success: function (res) {
console.log("code: ", res.code)
wx.request({
url: '******/user/wxlogin',
data: {
code: res.code,
},
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
success: function (res) {
},
})
}
})
后端获取openid,若有用户,返回用户信息给小程序
public function wxLogin() {
if (empty($_POST['code'])) {
return json(['error_code' => '1', 'msg' => '请输入code!']);
}
$url = "https://api.weixin.qq.com/sns/jscode2session";
$params = array();
$params['appid'] = '******';
$params['secret'] = '******';
$params['js_code'] = $_POST['code'];
$params['grant_type'] = 'authorization_code';
$arr = $this -> httpCurl($url, $params, 'POST');
$arr = json_decode($arr, true);
if (isset($arr['errcode']) && !empty($arr['errcode'])) {
return json(['error_code' => '2', 'msg' => $arr['errmsg'], "result" => null]);
}
$openid = $arr['openid'];
$user = db('user') -> where('openid', $openid) -> find();
if ($user) {
unset($user['openid']);
unset($user['password']);
return json(['error_code' => '0', 'msg' => '登录成功', 'data' => $user]);
} else {
return json(['error_code' => '1', 'msg' => '您没有绑定账号,请登录后在“我的”页面绑定~']);
}
}
学习博客:
小程序和ThinkPHP5结合实现登录状态(附代码)
微信小程序授权登录+Tp5后端
从零开始开发微信小程序(三):微信小程序绑定系统账号并授权登录之微信端
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!