移动端开发(微信开发3)
︴微信大总结
wx.php接口
<?php
require ‘./Wechat.class.php’;
/**
* wechat php test
*/
//define your token
define(“TOKEN”, “itcast”);
class wechatCallbackapiTest extends Wechat
{
public function valid()
{
$echoStr = $_GET[“echostr”];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
public function responseMsg()
{
//get post data, May be due to the different environments
$postStr = $GLOBALS[“HTTP_RAW_POST_DATA”];
//extract post data
if (!empty($postStr)){
/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
the best way is to check the validity of xml by yourself */
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($postStr, ‘SimpleXMLElement’, LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$type = trim($postObj->MsgType);
$time = time();
switch ($type) {
case ‘text’:
if ($keyword == ‘来图片’) {
$filePath = dirname(__FILE__) . DIRECTORY_SEPARATOR .’zhujiao.jpg’;
$this->sendImage($fromUsername, $toUsername, $this->getMediaId($filePath));
} else {
$this->sendText($fromUsername, $toUsername, ‘陈总’);
}
break;
default:
$this->sendText($fromUsername, $toUsername, ‘兄弟,不在服务器’);
# code…
break;
}
}else {
echo “”;
exit;
}
}
private function checkSignature()
{
// you must define TOKEN by yourself
if (!defined(“TOKEN”)) {
throw new Exception(‘TOKEN is not defined!’);
}
$signature = $_GET[“signature”];
$timestamp = $_GET[“timestamp”];
$nonce = $_GET[“nonce”];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
// use SORT_STRING rule
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
$wechatObj = new wechatCallbackapiTest();
//脚下留心:
//如果通信不成功
//解决思路:
//1.检查URL是否能正常访问
//2.检查调用的是否是valid方法
//$wechatObj->valid();
$wechatObj->responseMsg();
Wechat.class.php
<?php
define(‘APPID’, ‘wx56e3e3d75414b3d0’);
define(‘APPSECRET’, ‘f8ec8178c6dda48d1cb25c07304eff44’);
class Wechat
{
/**
* 获取access_token
* @see https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183
* @return string
*/
public function getToken()
{
$apiData = array(
‘appid’ => APPID,
‘secret’ => APPSECRET
);
$api = ‘https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&’.http_build_query($apiData);
$data = $this->httpRequest($api);
return $data[‘access_token’];
}
/**
* 上传媒体文件
* @see https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738726
* @return string
* 注:
* 图片(image): 2M,支持PNG\JPEG\JPG\GIF格式
* 语音(voice):2M,播放长度不超过60s,支持AMR\MP3格式
* 视频(video):10MB,支持MP4格式
* 缩略图(thumb):64KB,支持JPG格式
*/
public function getMediaId($filePath)
{
//1.定义接口
$apiData = array(
‘access_token’ => $this->getToken(),
‘type’=>’image’
);
$api = ‘https://api.weixin.qq.com/cgi-bin/media/upload?’.http_build_query($apiData);
//2.发送请求
//$filePath = dirname(__FILE__) . DIRECTORY_SEPARATOR .’zhujiao.jpg’; //脚下留心:window不区分\/但linux只支持 /
if(version_compare(PHP_VERSION,’5.5.0′,'<‘)) {
//脚下留心:PHP版本低于5.5
$postData = array(‘media’ => ‘@’.$filePath);
} else {
//脚下留心:PHP版本高于5.5
$postData = array(‘media’ => new Curlfile($filePath));
}
$data = $this->httpRequest($api, $postData);
return $data[‘media_id’];
// var_dump($data);
}
/**
* PHP发送请求
* @param string $api 接口地址
* @param array $postData POST请求数据
*/
public function httpRequest($api, $postData = array())
{
//1.初始化
$ch = curl_init();
//2.配置
//2.1设置请求地址
curl_setopt($ch, CURLOPT_URL, $api);
//2.2数据流不直接输出
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//2.3POST请求
if ($postData) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
//curl注意事项,如果发送的请求是https,必须要禁止服务器端校检SSL证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//3.发送请求
$data = curl_exec($ch);
//4.释放资源
curl_close($ch);
return json_decode($data, true);
}
/**
* 响应音乐消息
* @param string $fromUsername 接受者
* @param string $toUsername 发送者
* @param string $title 标题
* @param string $desc 描述
* @param string $musicUrl 音乐互联网地址(.mp3)
* @param string $ThumbMediaId 封面
* @param return
*/
protected function sendMusic($fromUsername, $toUsername, $title=’摇一摇歌声’, $desc=’甜美型,那是骗你的’, $musicUrl=’http://47.91.211.137/zxk/music.mp3′, $ThumbMediaId=’t96tqk6yOa_patBRMJNme_zrt3mlbKWCSZtXy5LMuSV8CZF58jXG5pRP67Xnciyb’) {
$tpl = ‘<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
</Music>
</xml>’;
echo sprintf($tpl, $fromUsername, $toUsername, time(), $title, $desc, $musicUrl, $musicUrl, $ThumbMediaId);
die;
}
/**
* 响应文本消息
* @param string $fromUsername 接受者
* @param string $toUsername 发送者
* @param string $content 发送的内容
* @param return
*/
protected function sendText($fromUsername, $toUsername, $content) {
$textTpl = ‘<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>’;
echo sprintf($textTpl, $fromUsername, $toUsername, time(), $content);
die;
}
/**
* 响应图片消息
* @param string $fromUsername 接受者
* @param string $toUsername 发送者
* @param string $MediaId 媒体ID(https://mp.weixin.qq.com/debug 先回去access_token 然后获取MediaId)
* @param return
*/
protected function sendImage($fromUsername, $toUsername, $MediaId = ‘G3P8hP2UXqozqUrOpt6rkfC2LEykkeD4OGTPBUyjVFgrGy0-C1yOR3Bvg0vSalic’)
{
//响应图片的xml报文
$tpl = ‘<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image><MediaId><![CDATA[%s]]></MediaId></Image>
</xml>’;
//脚下留心:MediaId是需要通过接口获取的,明天详细讲解,今天通过工具获取
//https://mp.weixin.qq.com/debug 查看MediaId(G3P8hP2UXqozqUrOpt6rkfC2LEykkeD4OGTPBUyjVFgrGy0-C1yOR3Bvg0vSalic)
echo sprintf($tpl, $fromUsername, $toUsername, time(), $MediaId);
die;
}
/**
* 响应视频消息
* @param string $fromUsername 接受者
* @param string $toUsername 发送者
* @param string $MediaId 媒体ID(https://mp.weixin.qq.com/debug 先回去access_token 然后获取MediaId)
* @param return
*/
protected function sendVideo($fromUsername, $toUsername, $MediaId = ‘8pudm18nSyQ5vBO8fCKQ_ucHm9BKTUtTDjfoLNYfoev_B1JY-hJ-E1mk5BncLCtm’)
{
$tpl = ‘<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA
]></MsgType>
<Video>
<MediaId><![CDATA[%s]]></MediaId>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
</Video>
</xml>’;
echo sprintf($tpl, $fromUsername, $toUsername, time(), $MediaId, ‘陈恒那些事’, ‘大战三百回合’);
}
}
一、微信带参数二维码接口
1、什么是微信二维码
使用php代码获取微信二维码
接口说明
2)代码
- 需求:生成带参数的二维码,用户扫码后出现下述提醒
- 步骤1;生成带参数的二维码
<?php
require ‘Wechat.class.php’;
$Wechat = new Wechat;
//步骤1:生成ticket
$api = “https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=”.$Wechat->getToken();
$postData = ‘{“expire_seconds”: 604800, “action_name”: “QR_STR_SCENE”, “action_info”: {“scene”: {“scene_str”: “php12”}}}’;
//脚下留心:OPENID是用户和公众号之间的唯一表示
$data = $Wechat->httpRequest($api, $postData);
// var_dump($data);
//步骤2:生成二维码
$api = “https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=”.$data[‘ticket’];
//方法1
//header(“location: $api”);
//方法2
$imageInfo = file_get_contents($api);
file_put_contents(‘./erweima.jpg’, $imageInfo);
- 步骤2;修改wx.php接口,当用户扫码时候提示需求信息
//推荐采用冗余策略,将支付宝支付,或者微信通知存放到mongodb中
//file_put_contents(‘./getxmldata.text’, $postStr);
switch ($type) {
case ‘event’:
if ($postObj->Event == ‘subscribe’)
{
if (isset($postObj->EventKey) && $postObj->EventKey != ”) {
//新用户扫码
$this->sendText($fromUsername, $toUsername, ‘新用户:’.$postObj->EventKey);
} else {
//关注
$this->sendText($fromUsername, $toUsername, ‘感谢老铁关注,双击666’);
}
} else if ($postObj->Event == ‘SCAN’ && isset($postObj->EventKey)) {
//老用户扫码
$this->sendText($fromUsername, $toUsername, ‘老用户:’.$postObj->EventKey);
} else if ($postObj->Event == ‘unsubscribe’) {
//取关
//业务逻辑去数据库,给用户mark已经取消关注,后期网站判断用户是否关注,如果没有
//就在页面显示一个弹框让他关注
$this->sendText($fromUsername, $toUsername, ‘妈的,要你何用’);
} else {
$this->sendText($fromUsername, $toUsername, ‘弄啥嘞!’);
}
break;
case ‘text’:
if ($keyword == ‘来图片’) {
$filePath = dirname(__FILE__) . DIRECTORY_SEPARATOR .’zhujiao.jpg’;
$this->sendImage($fromUsername, $toUsername, $this->getMediaId($filePath));
} else {
$this->sendText($fromUsername, $toUsername, ‘陈总’);
}
break;
default:
$this->sendText($fromUsername, $toUsername, ‘兄弟,不在服务器’);
# code…
break;
}
︴应用场景
问:首先明确搞活动吸粉使用微信默认提供的二维码是否而已?
答:明确可以,但是有效次没法统计门店吸粉量。
解决:通过程序生成不同参数的二维码
应用场景:门店吸粉统计二维码
二、微信LBS接口
1、什么是LBS
就是地理位置服务(获取你的位置,经度纬度)
2、接口说明(微信获取用户地理位置信息,经度和纬度)
4、使用php代码获取
1)需求
说明:用户发送位置坐标
提示:您发送的是地理位置消息,经度:xxx,纬度:xxx
2)代码
case ‘location’:
$tips = ‘您发送的是地理位置消息,经度:’.$postObj->Location_Y.’,纬度:xxx’.$postObj->Location_X;
$this->sendText($fromUsername, $toUsername, $tips);
break;
︴LBS案例:周边检索功能
步骤1:注册账号(登录)-> 创建应用 -> 获取key(b94b446f4ecad8b4f0e6cf758bacf915)
http://lbs.amap.com/dev/key/app
步骤2:获取周边检索功能接口
高德地图开发平台 http://lbs.amap.com/
步骤3:PHP获取周边数据
接口:
<?php
//1.定义接口
$apiData = array(
‘key’ => ‘b94b446f4ecad8b4f0e6cf758bacf915’,
‘location’ => ‘121.611812,31.034795’,
‘keywords’ => ‘传智播客’,
‘types’ => ”,
‘radius’ => ‘10000’,
‘offset’ => ’20’,
‘page’ => ‘1’,
‘extensions’ => ‘all’
);
$api = ‘http://restapi.amap.com/v3/place/around?’.http_build_query($apiData);
//2.请求
$data = file_get_contents($api);
$data = json_decode($data, true);
echo ‘<pre>’;
print_r($data);
︴应用场景
场景1:用户发送地理位置 -> 直接文字响应周边商家门店
场景2:用户发送地理位置 -> 响应网址/或图文消息,点击网址看到下图效果
场景3:用户发送地理位置 -> 响应网址,点击网址看到下图效果(可以搜索附近关键词)
三、微信的语音识别接口
1、什么是语音识别
就是发送语音转化为文字
接口说明
使用php代码获取微信的语音识别结果
步骤1:开启语音识别功能(注:因为缓存开启前已经关注需要取消关注)
步骤2:wx.php接口检测是语音,响应文字消息
//脚下留心:只有开启语音识别才有Recognition参数
$this->sendText($fromUsername, $toUsername, $postObj->Recognition);
break;
四、图灵机器人接口(第三方平台)
1、什么是图灵机器人
就是智能聊天机器人(定义一个php接口传递关键词他会自动识别响应合理的内容)
以前使用的叫小黄鸡
图灵机器人接口
1)步骤1:注册/登录获取APPKEY(105042050cc245fd9ec31f21f5da6952)
2)接口说明
使用php代码对接图灵机器人
<?php
require ‘Wechat.class.php’;
$Wechat = new Wechat;
//1.定义接口
$api = “http://www.tuling123.com/openapi/api”;
//2.定义接口数据
$postData = array(
‘key’ => ‘105042050cc245fd9ec31f21f5da6952’,
‘info’ => $_GET[‘k’],
‘userid’ => ‘chenheng’,
);
//3.发送请求
$data = $Wechat->httpRequest($api, json_encode($postData), true);
echo ‘<pre>’;
print_r($data);
在微信中整合图灵机器人
$content = $this->liaotian($keyword, $userid = ‘aaaa’);
$this->sendText($fromUsername, $toUsername, $content);
/***
* 聊天机器人
* @param string $keyword 聊天内容
* @param string $userid 用户标识
*/
private function liaotian($keyword, $userid = ”)
{
//1.定义接口
$api = “http://www.tuling123.com/openapi/api”;
//2.定义接口数据
$postData = array(
‘key’ => ‘105042050cc245fd9ec31f21f5da6952’,
‘info’ => $keyword,
‘userid’ => $userid,
);
//3.发送请求
$data = $this->httpRequest($api, json_encode($postData), true);
return isset($data[‘text’]) ? $data[‘text’] : ”;
}
︴扩展:发语音美女陪聊
说明:就是语音识别+图灵机器人
五、微信接口与MySQL数据库
1、需求
用户输入【新闻】可以查看网站最新的新闻数据(推送图文消息)
创建相应数据库
create database wechat;
use wechat;
create table news (
id int unsigned primary key auto_increment,
title varchar(30) not null,
description varchar(200) not null,
picurl varchar(50) not null,
url varchar(50) not null
)engine=MyISAM charset=utf8;
insert into news
values
(null,’美女’,’大河绕青山,知己又红颜’,’http://47.91.211.137/zxk/img/b1.png’,’http://www.baidu.cn’),
(null,’靓仔’,’我是你爸爸’,’http://47.91.211.137/zxk/img/one.png’,’http://www.baidu.cn’),
(null,’adsf’,’我是手动阀’,’http://47.91.211.137/zxk/img/two.png’,’http://www.baidu.cn’),
(null,’sdfsd’,’我手动阀’,’http://47.91.211.137/zxk/img/three.png’,’http://www.baidu.cn’),
(null,’释放掉’,’发送的爸’,’http://47.91.211.137/zxk/img/one.png’,’http://www.baidu.cn’),
(null,’水电费’,’手动阀’,’http://47.91.211.137/zxk/img/one.png’,’http://www.baidu.cn’),
(null,’水电费’,’我手动阀爸爸’,’http://47.91.211.137/zxk/img/two.png’,’http://www.baidu.cn’),
(null,’第三方’,’啥地方爸爸’,’http://47.91.211.137/zxk/img/three.png’,’http://www.baidu.cn’);
3、在微信的代码读取表中对的数据,然后拼接图文消息
if ($keyword == ‘来新闻’) {
$pdo = new PDO(‘mysql:dbname=wechat’, ‘root’, ”);
$pdostatement = $pdo->query(“select * from news order by id desc limit 5”);
$newsData = $pdostatement->fetchAll(PDO::FETCH_ASSOC);
foreach ($newsData as $key => $news) {
$temp[] = array(
‘title’=> $news[‘title’],
‘desc’=> $news[‘description’],
‘img’ => $news[‘picurl’],
‘url’ => $news[‘url’]
);
}
$this->sendNews($fromUsername, $toUsername, $temp);
die;
}
/**
* 响应图文消息
* @param string $fromUsername 接受者
* @param string $toUsername 发送者
* @param string $data 数据
* @param return
*/
protected function sendNews($fromUsername, $toUsername, $datas)
{
// 格式:
// $datas = array(
// array(‘title’=>’a’, ‘desc’=> ‘bb’, ‘img’ => ‘http://47.91.211.137/zxk/img/b1.jpg’, ‘url’ => ‘http://baidu.com’),
// array(‘title’=>’a’, ‘desc’=> ‘bb’, ‘img’ => ‘http://47.91.211.137/zxk/img/b1.jpg’, ‘url’ => ‘http://baidu.com’),
// array(‘title’=>’a’, ‘desc’=> ‘bb’, ‘img’ => ‘http://47.91.211.137/zxk/img/b1.jpg’, ‘url’ => ‘http://baidu.com’),
// array(‘title’=>’a’, ‘desc’=> ‘bb’, ‘img’ => ‘http://47.91.211.137/zxk/img/b1.jpg’, ‘url’ => ‘http://baidu.com’)
// );
//响应图文消息,切记:ArticleCount是几则有几个item
$tpl = ‘<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>’;
foreach ($datas as $data) {
$tpl .= “<item>
<Title><![CDATA[{$data[‘title’]}]]></Title>
<Description><![CDATA[{$data[‘desc’]}]]></Description>
<PicUrl><![CDATA[{$data[‘img’]}]]></PicUrl>
<Url><![CDATA[{$data[‘url’]}]]></Url>
</item>”;
}
$tpl .= ‘</Articles></xml>’;
echo sprintf($tpl, $fromUsername, $toUsername, time(), count($datas));
}
六、网页授权接口(Oauth2.0) 【★★★★★★★★】
1、什么是网页授权接口(Oauth2.0)
2、网页授权模式说明
3、实现网页授权功能
1)授权回调页面域名
2)用户同意授权,获取code
接口:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=用户同意后处理的PHP程序&response_type=
code&scope=snsapi_userinfo&state=STATE#wechat_redirect
替换自己的链接后,登录PC端将链接发送给自己然后手机端访问
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx56e3e3d75414b3d0&redirect_uri=http://php.skschool.cn/zhaoxiaokang/member.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
3)通过code换取网页授权access_token 和 openid(创建member.php页面输入下属代码)
<?php
//步骤1:设置安全回调地址
//步骤2:手动访问https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx56e3e3d75414b3d0&redirect_uri=http://47.91.211.137/zxk/member.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
//步骤3:根据code获取access_token和openid
$apiData = array(
‘appid’=>’wx56e3e3d75414b3d0’,
‘secret’=>’f8ec8178c6dda48d1cb25c07304eff44’,
‘code’=>$_GET[‘code’],
‘grant_type’=>’authorization_code’
);
$api = ‘https://api.weixin.qq.com/sns/oauth2/access_token?’.http_build_query($apiData);
$data = file_get_contents($api);
$data = json_decode($data, true);
︴拉取用户信息(需scope为 snsapi_userinfo)
<?php
//步骤1:设置安全回调地址
//步骤2:手动访问https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx56e3e3d75414b3d0&redirect_uri=http://47.91.211.137/zxk/member.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
//步骤3:根据code获取access_token和openid
$apiData = array(
‘appid’=>’wx56e3e3d75414b3d0’,
‘secret’=>’f8ec8178c6dda48d1cb25c07304eff44’,
‘code’=>$_GET[‘code’],
‘grant_type’=>’authorization_code’
);
$api = ‘https://api.weixin.qq.com/sns/oauth2/access_token?’.http_build_query($apiData);
$data = file_get_contents($api);
$data = json_decode($data, true);
//步骤4:获取用户信息
$apiData = array(
‘access_token’ => $data[‘access_token’],
‘openid’ => $data[‘openid’],
‘lang’ => ‘zh_CN’
);
$api = ‘https://api.weixin.qq.com/sns/userinfo?’.http_build_query($apiData);
$data = file_get_contents($api);
$data = json_decode($data, true);
echo ‘<pre>’;
print_r($data);
︴小总结【★★★★★】
需 求:获取用户信息
步骤1:设置回调域名(测试账号页面)
步骤2:获取code
替换自己的链接后,登录PC端将链接发送给自己然后手机端访问
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx56e3e3d75414b3d0&redirect_uri=http://47.91.211.137/zxk/member.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
步骤3:根据code获取access_token和openid(member.php)
步骤4:根据openid和access_token获取用户信息(member.php)
实战开发流程
用户访问某需要登录的页面 -> 通过会话技术判断用户是否登录(openid) : 已登录-> 不用管正常访问,未登录-> 程序跳转到
(https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx56e3e3d75414b3d0&redirect_uri=http://php.skschool.cn/zhaoxiaokang/member.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect)获取openid并通过会话技术保存即可。
七、微信JSSDK接口【★★★★★】
1、什么是JSSDK接口
2、下载JSSDK官方接口
http://demo.open.weixin.qq.com/jssdk/sample.zip
实现JSSDK接口功能
步骤1:设置安全域名
步骤2:解压JSSDK
步骤3:修改sample.php文件
步骤4:修改sample.php配置接口
步骤4:上传到服务器访问
综合案例
需求
发送关键词【1024】响应链接参加活动(PC端:说明用微信打开,微信端:已登录不管,未登录授权登录)
代码
步骤1:加载静态页面
步骤2:判断用户是否登录
思路:通过session中的openid判断用户是否登录
逻辑:当用户访问index.php 通过 isWeixinApp.php判断用户是否通过微信客户端打开,通过isLogin.php是否登录(是-则不管,否-则跳转到网页授权)
index.php
isWeixinApp.php
<?php
$user_agent = $_SERVER[‘HTTP_USER_AGENT’];
if (strpos($user_agent, ‘MicroMessenger’) === false) {
// 非微信浏览器禁止浏览
//echo “HTTP/1.1 401 Unauthorized”;
echo ‘你有瑕疵,because 你 out 了,快用微信客户端’;
die;
}
isLogin.php
<?php
//步骤1:设置安全回调地址
//步骤2:手动访问https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx56e3e3d75414b3d0&redirect_uri=http://47.91.211.137/zxk/member.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
//步骤3:根据code获取access_token和openid
$apiData = array(
‘appid’=>’wx56e3e3d75414b3d0’,
‘secret’=>’f8ec8178c6dda48d1cb25c07304eff44’,
‘code’=>$_GET[‘code’],
‘grant_type’=>’authorization_code’
);
$api = ‘https://api.weixin.qq.com/sns/oauth2/access_token?’.http_build_query($apiData);
$data = file_get_contents($api);
$data = json_decode($data, true);
// //步骤4:获取用户信息
$apiData = array(
‘access_token’ => $data[‘access_token’],
‘openid’ => $data[‘openid’],
‘lang’ => ‘zh_CN’
);
$api = ‘https://api.weixin.qq.com/sns/userinfo?’.http_build_query($apiData);
$data = file_get_contents($api);
$data = json_decode($data, true);
//登录成功,保存用户信息,并跳转到首页
session_start();
$_SESSION[‘userinfo’] = array(
‘openid’ => $data[‘openid’],
‘nickname’ => $data[‘nickname’],
‘headimgurl’ => $data[‘headimgurl’]
);
header(“location: ./index.php”);
扫码抽奖