1.在微信公众平台后台找到网页授权获取用户基本信息接口,点击后面的修改
![](https://box.kancloud.cn/2ccebe7d939f76321f9b9088c95a9b6a_1142x101.png)
2.填写已经备案的项目域名,若域名符合条件,按确定会出现通过安全监测字样
![](https://box.kancloud.cn/b7aa8c119cad3d953769a488612dc6ff_583x438.png)
![](https://box.kancloud.cn/871dac68495e43ccf509f56f36c1fb87_722x119.png)
3.在微信公众平台后台》开发者工具下面下载web开发者工具
![](https://box.kancloud.cn/5d9f1bd08acfea36c5d46ef2166c51da_1128x510.png)
4.打开下载好的微信web开发者工具,选择项目为“公众号网页测试”,并用微信登录
![](https://box.kancloud.cn/8d589fa9bfb464b9e8d86c4fdaf743ae_1022x756.png)
5.在项目根目录下的/Application/Home/Controller文件夹中的IndexController.class.php文件,书写代码
~~~
<?php
namespace Home\Controller;
use Think\Controller;
use Com\Wechat;
use Com\WechatAuth;
class IndexController extends Controller {
public function index(){
$token="zhangyouwu";
/* 加载微信 */
$wechat = new Wechat($token);
/* 获取请求信息 */
$data = $wechat->request();
if($data && is_array($data)){
switch($data['MsgType']){
case "text":
$this->Text($wechat,$data);
}
}
}
//回复文本消息
private function Text($wechat,$data){
//回复文本消息
if(strstr($data['Content'],"文本")){
$text="我正在使用Thinkphp开发微信";
$this->logger("发送信息:\n".$text);
$wechat-> replyText($text);
}else if(strstr($data['Content'],"myself")){
$this->users($wechat,$data);
}
}
//获取用户信息
private function users($wechat,$data){
$openid=$data['FromUserName'];
$appid="wx165112bf167af76c";
$appSecret="c65b22bfcf03fdd98504eac299701b03";
$token=session('token');
if($token){
$WechatAuth=new WechatAuth($appid,$appSecret,$token);
}else{
$WechatAuth=new WechatAuth($appid,$appSecret);
$accsseToken=$WechatAuth->getAccessToken();
$token=$accsseToken['access_token'];
session('token',$token);
}
$user=$WechatAuth->userInfo($openid);
$text="你的openid是:".$user['openid']."\n你的昵称是:".$user['nickname']."\n你的性别是:".$user['sex']."\n你的城市是:"
.$user['city']."\n你所在的国家是:".$user['country']."\n你所在的省份是:".$user['province'];
$this->logger("发送用户的信息:\n".$text);
$wechat->replyText($text);
}
//网页授权获取用户基本信息
public function webUsers(){
$appid="wx165112bf167af76c";
$appSecret="c65b22bfcf03fdd98504eac299701b03";
$WechatAuth=new WechatAuth($appid,$appSecret);
if($_GET['iscode']){
$url="http://zyw.xxxxx.com/index.php/Home/Index/webUsers";//zyw.xxxxx.com为微信公众平台的授权回调页面域名
$result=$WechatAuth->getRequestCodeURL($url);
echo $result;
}
/* $user=$WechatAuth->userInfo($openid);
$text="你的openid是:".$user['openid']."\n你的昵称是:".$user['nickname']."\n你的性别是:".$user['sex']."\n你的城市是:"
.$user['city']."\n你所在的国家是:".$user['country']."\n你所在的省份是:".$user['province'];
$this->logger("发送用户的信息:\n".$text);
$wechat->replyText($text);*/
}
//日志
private function logger($content){//存储日志
$logSize=100000;//定义日志大小
$log="log.txt";//定义日志名字
if(file_exists($log)&&filesize($log)>$logSize){//如果日志存在并且大于定义的大小
unlink($log);//删除
}
//文件写入1.名字2.内容,+时间防止重复3.内容往后加而不是覆盖
file_put_contents($log,date('H:i:s')." ".$content."\n",FILE_APPEND);
}
}
~~~
6.在微信web开发工具填写地址,得到下面展示即可
![](https://box.kancloud.cn/ee722213c9a3b159912a5142d4946ac7_993x706.png)
7.本节源码下载(下载密码:yi84)
[源码下载](https://pan.baidu.com/s/12ZAi9C5jgZ2an3kR8y5aAA)