关键词搜索

源码搜索 ×
×

微信小程序php后台登陆开发

发布2020-05-25浏览591次

详情内容

微信的登陆流程

 

首先前端发送请求到服务器:

  1. wx.login({
  2. success: function (res) {
  3. var code = res.code;//发送给服务器的code
  4. wx.getUserInfo({
  5. success: function (res) {
  6. var userNick = res.userInfo.nickName;//用户昵称
  7. var avataUrl = res.userInfo.avatarUrl;//用户头像地址
  8. var gender = res.userInfo.gender;//用户性别
  9. if (code) {
  10. wx.request({
  11. url: 'http://localhost/test/getopenid.php',//服务器的地址,现在微信小程序只支持https请求,所以调试的时候请勾选不校监安全域名
  12. data: {
  13. code: code,
  14. nick: userNick,
  15. avaurl: avataUrl,
  16. sex: gender,
  17. },
  18. header: {
  19. 'content-type': 'application/json'
  20. },
  21. success: function (res) {
  22. console.log(res.data);
  23. wx.setStorageSync('name', res.data.name);//将获取信息写入本地缓存
  24. wx.setStorageSync('openid', res.data.openid);
  25. wx.setStorageSync('imgUrl', res.data.imgurl);
  26. wx.setStorageSync('sex', res.data.sex);
  27. }
  28. })
  29. }
  30. else {
  31. console.log("获取用户登录态失败!");
  32. }
  33. }
  34. })
  35. },
  36. fail: function (error) {
  37. console.log('login failed ' + error);
  38. }
  39. })

 这样就实现了将前端获取的code发送到服务器,code每次获取的都不一样;
服务器getopenid.php代码:

  1. <?php
  2. text();
  3. function text()
  4. {
  5. $code = $_GET['code'];//小程序传来的code
  6. $nick = $_GET['nick'];//小程序传来的用户昵称
  7. $imgUrl = $_GET['avaurl'];//小程序传来的用户头像地址
  8. $sex = $_GET['sex'];//小程序传来的用户性别
  9. $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=yourAppid&secret=appSecret&js_code=' . $code . '&grant_type=authorization_code';
  10. //yourAppid为开发者appid.appSecret为开发者的appsecret,都可以从微信公众平台获取;
  11. $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据,推荐使用curl
  12. $json = json_decode($info);//对json数据解码
  13. $arr = get_object_vars($json);
  14. $openid = $arr['openid'];
  15. $session_key = $arr['session_key'];
  16. $con = mysqli_connect('localhost', 'root', '123');//连接数据库
  17. if ($con) {
  18. if (mysqli_select_db($con, 'students')) {
  19. $sql1 = "select * from weixin where openid = '$openid'";
  20. $result = mysqli_query($con, $sql1);
  21. $result = mysqli_fetch_assoc($result);
  22. if ($result!=null) {//如果数据库中存在此用户的信息,则不需要重新获取
  23. $result = json_encode($result);
  24. echo $result;
  25. }
  26. else {//没有则将数据存入数据库
  27. if ($sex == '0') {
  28. $sex = 'none';
  29. } else {
  30. $sex = '1' ? 'man' : 'women';
  31. }
  32. $sql = "insert into weixin values ('$nick','$openid','$session_key','$imgUrl','$sex')";
  33. if (mysqli_query($con, $sql)) {
  34. $arr['nick'] = $nick;
  35. $arr['imgUrl'] = $imgUrl;
  36. $arr['sex'] = $sex;
  37. $arr = json_encode($arr);
  38. echo $arr;
  39. } else {
  40. die('failed' . mysqli_error($con));
  41. }
  42. }
  43. }
  44. } else {
  45. die(mysqli_error());
  46. }
  47. }

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载