·这一篇数微信公众号开发的第五篇,如果你是小白请点击下方第一篇的链接:
微信公众号开发-接口配置信息(第①篇)-CSDN博客
- 先获取token,代码:
<?php //获取token
$appId = 'wx08888888888888888888; //改成自己的
$appSecret = '65188888888888888888888888'; //改成自己的
$accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
$accessTokenResponse = file_get_contents($accessTokenUrl);
$accessTokenData = json_decode($accessTokenResponse, true);
$accessToken = $accessTokenData['access_token'];
- 添加openid入数据库,代码:
<?php
//获取openid存入数据库
require "./idInfo.cls.php"; //引入的就是上面的代码
$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$accessToken";
$urlDatas = file_get_contents($url);
$urlData = json_decode($urlDatas , 1);
// print_r($urlData);
$conn = new mysqli('localhost', 'root', '123456', 'weixin');
if ($conn->connect_error) {
die("连接数据库失败: " . $conn->connect_error);
}
foreach ($urlData['data']['openid'] as $openid) {
$sql = "SELECT * FROM `usermain` WHERE `userOpenId` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $openid);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// openid 已存在
echo "openid: '{$openid}' 已存在,\n";
} else {
// 插入新的 openid
$sql = "INSERT INTO `usermain` (`userOpenId`) VALUES (?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $openid);
if ($stmt->execute()) {
echo "openid 已添加到数据库\n";
} else {
echo "添加 openid 到数据库失败: " . $stmt->error . "\n";
}
}
$stmt->close();
}
$conn->close();
- 修改完上面代码后,直接运行,一共有2个openid
数据库添加成功
·以上就是openid存入数据库的所有内容
·下一篇就是功能模块了,需要的去看微信公众号开发第⑥篇