微信开发端的js文件:
const APP_ID = 'wx0843bxxxxxxxf6fc'; //输入小程序appid const APP_SECRET = '637e11bf3dxxxxxxxxx9f9b1ef5221'; //输入小程序app_secret var OPEN_ID = '' //储存获取到openid var SESSION_KEY = '' //储存获取到session_key Page({ getOpenIdTap: function() { var that = this; wx.login({ success: function(data) { console.log(data); wx.request({ //获取openid接口 url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + APP_ID + '&secret=' + APP_SECRET + '&js_code=' + data.code + '&grant_type=authorization_code', data: {}, method: 'GET', success: function(res) { console.log(res.data) OPEN_ID = res.data.openid; //获取到的openid SESSION_KEY = res.data.session_key; //获取到session_key that.setData({ openid: OPEN_ID, session_key: SESSION_KEY }); wx.request({ url: 'https://127.0.0.1/wx_test/test.php',//访问的接口地址 data: { //传的数据 openid: OPEN_ID, session_key: SESSION_KEY }, success: function() { } }) } }) } }) } })
php文件:
<?php $openid = $_REQUEST['openid']; $session_key = $_REQUEST['session_key']; $db = new mysqli("localhost","root","","test"); !mysqli_connect_error() or die("数据库连接错误"); $date = date("Y-h-d H-i-s"); $sql = "insert into user (phone,openid,session_key,date) values('175****1175','$openid','$session_key','$date')"; $db->query($sql);
点击button后获取到的openid和session_key就可以存到数据库中了: