准备工作
1.获取小程序appid,aposecret:(在微信公众平台获取)
2.一个服务器(在这里用本地搭建集成环境phpstudy8.0)
使用phpstudy8.0教程
3.微信开发者工具
开始
打开微信开发者工具,点击新建项目,输入在微信公众平台获取的appid(一定要输入正确的appid,要不然后面会出现问题),点击新建完成。
进入项目,在pages新建页面,然后在xx.wxml页面,加上以下代码。
post data
然后在xx.js页面,加上以下代码。
Page({
postData: function () {
wx.login({
success: function(res){
console.log(res.code)
wx.request({
url: 'https://www.umserver.club/user.php',
data:{
code: res.code
},
success: function(res){
console.log("传递成功")
}
})
}
})
},
})
在小程序端代码已经写好了,现在从php文件下手了,在php文件只要加上以下代码。
$servername="localhost";//服务器地址,默认localhost
$username="root";//数据库用户名
$password="123456";//数据库密码
$dbname="user";数据库名
$code=$_GET["code"];
$appid='xxxxxxxxxxx';//小程序appid
$secret='xxxxxxxxxxxxxxxxxxxx';//小程序aposecret
$url="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
$Info=file_get_contents($url);
$jsInfo=json_decode($Info);
$arry=get_object_vars($jsInfo);
$secret=$arry['session_key'];
$openid=$arry['openid'];
$conn=new mysqli($servername,$username,$password,$dbname);
if($conn->connect_error){
die("连接失败".$conn->connect_error);
}
$sql="INSERT INTO getuser(secret,openid) VALUES('$secret','$openid')";//getuser是数据表
if($conn->query($sql)===TRUE){
echo "插入成功";
}
else{
echo "插入失败".$conn->error;
}
?>
代码全部写好了,接下来在数据库创建数据表,添加字段就可以了。
然后回到微信开发者工具,在菜单中找到详情按钮,在下面找到不校验合法域名,勾选上(在本地服务器测试,可以不需要正常的域名限制)。
完成后,在模拟器点击按钮。
此时,在控制面板上出现以下信息,说明code值成功传给php页面。
最后回到数据库中,查看openid,session_key 有没有成功存储到数据库中,如果出现以下数据,说明存储成功。
希望我的经验能帮到你,谢谢!