一:前往微信公众平台基本配置,配置服务器配置
二:服务器地址URL要对应控制器中的方法
public function valid(){
$xml_str = file_get_contents("php://input");
//如果不知道扫码进来是个什么东西,那就存数据库(或日志看看)
//Db::name('aaaa')->insert(['content'=>$xml_str]);
$xml = (array)simplexml_load_string($xml_str,"SimpleXMLElement",LIBXML_NOCDATA);
//判断是否首次关注
if ($xml['MsgType'] == 'event')
{
if ($xml['Event'] == 'subscribe')
{
if(empty($xml['EventKey'])){
$res = new Wechattwo();
$a = $res -> getUserMessage($xml['FromUserName'],0);//获取用户信息的方法
if($a){
$msg = '感谢关注';
}
}else{
$uid = str_replace('qrscene_','',$xml['EventKey']);
$res = new Wechattwo();
$a = $res -> getUserMessage($xml['FromUserName'],$uid);//获取用户信息的方法
if($a){
$msg = '已经关注过了';
}
}
echo $this->sendText($msg,$xml);
die;
}
if ($xml['Event'] == 'unsubscribe')
{
echo "取消关注";die;
}
}
}
三:扫描二维码(我生成的是静态二维码)直接通过app_id 和 app_secret 获取(没有获取code)
//获取accesstoken
public function getToken($appid,$appsecret){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
$token = $this->http_curl($url, 'get');
$access_token = $token['access_token'];
return $access_token;
}
/**
* @param $accesstoken token
* @param $uid 我给二维码传的参数
* @return string
*/
public function qrCode($accesstoken,$uid){
$u = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $accesstoken;
$param = array();
$param['action_name'] = "QR_LIMIT_SCENE";
$param['action_info'] = array('scene' => array('scene_id' => $uid));
$param = json_encode($param);
// 返回二维码的ticket和二维码图片解析地址
$res = $this->http_curl($u, 'post', 'json', $param);
// 通过ticket换取二维码
$qrcode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . $res['ticket'];
return $qrcode;
}
附加:这个是curl接口代码
/*
* $url curl要抓取数据地址
* $type curl抓取数据的类型 是post类型还是get类型
* $res 抓取完成后,返回的数据类型 默认为json
* $arr 如果是post类型 需要给post类型传递数据,数据是json形式的
*/
public function http_curl($url, $type = 'get', $res = 'json', $arr = '')
{
//初始化curl
$ch = curl_init();
//设置curl的参数
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//判断传递数据是什么类型 get还是post
if ($type == 'post') {
//是否开启post传递
curl_setopt($ch, CURLOPT_POST, 1);
//传递数据 $arr是在post方式中要传递的数据 是json形式的
curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
}
//采集数据 因为get根本不需要上面 那2行代码 所以 type=get的话直接就可以采集了
$output = curl_exec($ch);
//判断返回信息的类型 默认为json
if ($res == 'json') {
if (curl_errno($ch)) {
//请求失败 返回错误信息
return curl_error($ch);
} else {
//请求成功
return json_decode($output, true);//curl抓取的返回值 然后返回数组形式
}
}
//关闭curl
curl_close($ch);
}
这样扫描二维码就直接进入公众号关注页面了。