微信小程序php后台實現


這里簡單介紹用php后台實現獲取openid並保存到數據庫;

 

微信的登陸流程是這樣的 

 

首先前端發送請求到服務器:

wx.login({
        success: function (res) {
          var code = res.code;//發送給服務器的code
          wx.getUserInfo({
            success: function (res) {
              var userNick = res.userInfo.nickName;//用戶昵稱
              var avataUrl = res.userInfo.avatarUrl;//用戶頭像地址
              var gender = res.userInfo.gender;//用戶性別
              if (code) {
                wx.request({
                  url: 'http://localhost/test/getopenid.php',//服務器的地址,現在微信小程序只支持https請求,所以調試的時候請勾選不校監安全域名
                  data: {
                    code: code,
                    nick: userNick,
                    avaurl: avataUrl,
                    sex: gender,
                  },
                  header: {
                    'content-type': 'application/json'
                  },
                  success: function (res) {
                    console.log(res.data);
                    wx.setStorageSync('name', res.data.name);//將獲取信息寫入本地緩存
                    wx.setStorageSync('openid', res.data.openid);
                    wx.setStorageSync('imgUrl', res.data.imgurl);
                    wx.setStorageSync('sex', res.data.sex);
                  }
                })
              }
              else {
                console.log("獲取用戶登錄態失敗!");
              }
            }
          })
        },
        fail: function (error) {
          console.log('login failed ' + error);
        }
})    

這樣就實現了將前端獲取的code發送到服務器,code每次獲取的都不一樣;

  

服務器getopenid.php代碼:

<?php
text();
function text()
{
    $code = $_GET['code'];//小程序傳來的code值
    $nick = $_GET['nick'];//小程序傳來的用戶昵稱
    $imgUrl = $_GET['avaurl'];//小程序傳來的用戶頭像地址
    $sex = $_GET['sex'];//小程序傳來的用戶性別
    $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=yourAppid&secret=appSecret&js_code=' . $code . '&grant_type=authorization_code';
    //yourAppid為開發者appid.appSecret為開發者的appsecret,都可以從微信公眾平台獲取;
    $info = file_get_contents($url);//發送HTTPs請求並獲取返回的數據,推薦使用curl
    $json = json_decode($info);//對json數據解碼
    $arr = get_object_vars($json);
    $openid = $arr['openid'];
    $session_key = $arr['session_key'];
    $con = mysqli_connect('localhost', 'root', '123');//連接數據庫
    if ($con) {
        if (mysqli_select_db($con, 'students')) {
            $sql1 = "select * from weixin where openid = '$openid'";
            $result = mysqli_query($con, $sql1);
            $result = mysqli_fetch_assoc($result);
            if ($result!=null) {//如果數據庫中存在此用戶的信息,則不需要重新獲取
                $result = json_encode($result);
                echo $result;
            }
            else {//沒有則將數據存入數據庫
                if ($sex == '0') {
                    $sex = 'none';
                } else {
                    $sex = '1' ? 'man' : 'women';
                }
                $sql = "insert into weixin values ('$nick','$openid','$session_key','$imgUrl','$sex')";
                if (mysqli_query($con, $sql)) {
                    $arr['nick'] = $nick;
                    $arr['imgUrl'] = $imgUrl;
                    $arr['sex'] = $sex;
                    $arr = json_encode($arr);
                    echo $arr;
                } else {
                    die('failed' . mysqli_error($con));
                }
            }
        }
    } else {
        die(mysqli_error());
    }
}

?>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM