微信小程序php后台实现
生活随笔
收集整理的這篇文章主要介紹了
微信小程序php后台实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這里簡單介紹用php后臺實現獲取openid并保存到數據庫;
微信的登陸流程是這樣的
首先前端發送請求到服務器:
這樣就實現了將前端獲取的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());} }?>總結
以上是生活随笔為你收集整理的微信小程序php后台实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hoj2677 Instruction
- 下一篇: C#开发基础类库