码迷,mamicode.com
首页 > 微信 > 详细

微信笔记

时间:2017-10-30 14:52:48      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:nsf   get   html   判断   ...   div   创建   func   mkdir   

一、获取授权并得到用户信息
1.发者需要先到公众平台官网中的开发者中心页配置授权回调域名
2.授权回调域名配置规范为全域名
3.以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
4.以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过。
5.UnionID机制的作用说明:如果开发者拥有多个移动应用、网站应用和公众帐号,可通过获取用户基本信息中的unionid来区分用户的唯一性,因为同一用户,对同一个微信开放平台下的不同应用(移动应用、网站应用和公众帐号),unionid是相同的。
需要函数工具
6.snsapi_base与snsapi_userinfo的区别:
snsapi_base只能获取access_token和openID
snsapi_userinfo可以获取更详细的用户资料,比如头像、昵称、性别等
1.function https_request($url, $data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
2.public function user_info(){
// 回调地址为全域名
$url = urlencode("http://jsph.lision.cn/index.php?g=wechat&m=Index&a=user_info");
// 公众号的id和secret
$appid = ‘xxxxxxxxx‘;
$appsecret = ‘xxxxxxxxx‘;
//开启session
session_start();
// 获取code码,用于和微信服务器申请token。此处授权登录需要用户端操作
if(!isset($_GET[‘code‘]) && !isset($_SESSION[‘code‘])){
echo
‘<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=‘.$appid.‘&redirect_uri=‘.$url.‘&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"><font style="font-size:30">授权</font></a>‘;
exit;
}
// 依据code码去获取openid和access_token,自己的后台服务器直接向微信服务器申请即可
if (isset($_GET[‘code‘]) && !isset($_SESSION[‘token‘])){
$_SESSION[‘code‘] = $_GET[‘code‘];
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$_GET[‘code‘]."&grant_type=authorization_code";
$res = https_request($url);
$res =(json_decode($res, true));
$_SESSION[‘token‘] = $res;
}
// 依据申请到的access_token和openid,申请Userinfo信息。
if (isset($_SESSION[‘token‘][‘access_token‘])){
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$_SESSION[‘token‘][‘access_token‘]."&openid=".$_SESSION[‘token‘][‘openid‘]."&lang=zh_CN";
$res = https_request($url);
$res = json_decode($res, true);
//将用户信息存储到session中
$_SESSION[‘userinfo‘] = $res;
}
//打印用户信息
print_r($_SESSION);
}
二、获取微信菜单
1.创建菜单(若是修改菜单需要先删除以前的菜单再重新获取新菜单)
2.获取菜单
3.删除菜单
4.显示菜单
public function menu(){
header("Content-type: text/html; charset=utf-8");
$data = ‘{
"button":[
{
"type":"view",
"name":"链接",
"url":"http://jsph.lision.cn/index.php?g=wechat&m=index&a=info"
},
{
"name":"按钮",
"sub_button":[
{
"type":"view",
"name":"当前订单",
"url":"http://jsph.lision.cn/index.php?g=wechat&m=index&a=current"
},
{
"type":"view",
"name":"历史订单",
"url":"http://jsph.lision.cn/index.php?g=wechat&m=index&a=history"
}]
},
{
"type":"click",
"name":"联系我们",
"key":"V1001_GOOD"
}]
}‘;
// 公众号的id和secret
$appid = ‘xxxxxxxxx‘;
$appsecret = ‘xxxxxxxxx‘;
$token = session("token");
if($token){
$auth = new WechatAuth($appid, $appsecret, $token);
$access_token = $token;
} else {
$auth = new WechatAuth($appid, $appsecret);
$token = $auth->getAccessToken();

session(array(‘expire‘ => $token[‘expires_in‘]));
session("token", $token[‘access_token‘]);
$access_token = $token[‘access_token‘];
}
return self::createMenu($data,$access_token);
}
三、自动回复
在微信公众平台配置服务器时的地址例如http://swxt.lision.cn/portal/index/wechat
那么关注的方法就要写在wechat里面,如不这样配置关注无法自动回复
所需方法如下
public function wechat($id = ‘‘){
//调试
try{
$appid = self::APPID; //AppID(应用ID)
$token = self::TOKEN; //微信后台填写的TOKEN
$crypt = self::CRYPT; //消息加密KEY(EncodingAESKey)

/* 加载微信SDK */
$wechat = new Wechat($token, $appid, $crypt);

/* 获取请求信息 */
$data = $wechat->request();

if($data && is_array($data)){
/**
* 你可以在这里分析数据,决定要返回给用户什么样的信息
* 接受到的信息类型有10种,分别使用下面10个常量标识
* Wechat::MSG_TYPE_TEXT //文本消息
* Wechat::MSG_TYPE_IMAGE //图片消息
* Wechat::MSG_TYPE_VOICE //音频消息
* Wechat::MSG_TYPE_VIDEO //视频消息
* Wechat::MSG_TYPE_SHORTVIDEO //视频消息
* Wechat::MSG_TYPE_MUSIC //音乐消息
* Wechat::MSG_TYPE_NEWS //图文消息(推送过来的应该不存在这种类型,但是可以给用户回复该类型消息)
* Wechat::MSG_TYPE_LOCATION //位置消息
* Wechat::MSG_TYPE_LINK //连接消息
* Wechat::MSG_TYPE_EVENT //事件消息
*
* 事件消息又分为下面五种
* Wechat::MSG_EVENT_SUBSCRIBE //订阅
* Wechat::MSG_EVENT_UNSUBSCRIBE //取消订阅
* Wechat::MSG_EVENT_SCAN //二维码扫描
* Wechat::MSG_EVENT_LOCATION //报告位置
* Wechat::MSG_EVENT_CLICK //菜单点击
*/

//记录微信推送过来的数据
file_put_contents(‘./data.json‘, json_encode($data));

/* 响应当前请求(自动回复) */
//$wechat->response($content, $type);

/**
* 响应当前请求还有以下方法可以使用
* 具体参数格式说明请参考文档
*
* $wechat->replyText($text); //回复文本消息
* $wechat->replyImage($media_id); //回复图片消息
* $wechat->replyVoice($media_id); //回复音频消息
* $wechat->replyVideo($media_id, $title, $discription); //回复视频消息
* $wechat->replyMusic($title, $discription, $musicurl, $hqmusicurl, $thumb_media_id); //回复音乐消息
* $wechat->replyNews($news, $news1, $news2, $news3); //回复多条图文消息
* $wechat->replyNewsOnce($title, $discription, $url, $picurl); //回复单条图文消息
*
*/

//执行Demo
$this->demo($wechat, $data);
}
} catch(\Exception $e){
file_put_contents(‘./error.json‘, json_encode($e->getMessage()));
}
}


private function demo($wechat, $data){
switch ($data[‘MsgType‘]) {
case Wechat::MSG_TYPE_EVENT:
switch ($data[‘Event‘]) {
// 关注事件
case Wechat::MSG_EVENT_SUBSCRIBE:
$wechat->replyNewsOnce(
"合肥书文学堂",
"书文学堂 专做语文\n市府广场校区:13349295520 13339282938\n香港街校区:13339286717 63848431",
"http://swxt.lision.cn/portal/wechat/about",
"http://swxt.lision.cn/themes/simplebootx/Public/assets/images/swxt.png"
); //回复单条图文消息
break;
case Wechat::MSG_EVENT_SUBSCRIBE:
$wechat->replyText(‘欢迎您关注合肥书文学堂公众平台!‘);
break;

default:
$wechat->replyText("欢迎访问合肥书文学堂公众平台!您的事件类型:{$data[‘Event‘]},EventKey:{$data[‘EventKey‘]}");
break;
}
break;

case Wechat::MSG_TYPE_TEXT:
switch ($data[‘Content‘]) {
case ‘如何报班‘:
$wechat->replyNewsOnce(
"合肥书文学堂",
"书文学堂 专做语文\n市府广场校区:13349295520 13339282938\n香港街校区:13339286717 63848431",
"http://swxt.lision.cn/",
"http://swxt.lision.cn/themes/simplebootx/Public/assets/images/swxt.png"
); //回复单条图文消息
break;
default:
$wechat->replyText("书文学堂 专做语文\n 市府广场校区:13349295520 13339282938\n 香港街校区:13339286717 63848431");
break;
}
break;

default:
# code...
break;
}
}
四、图片上传
1.在php 页面需要获取签名在html里面配置js
$signature=$this->getSignPackage();
public function getSignPackage() {
$jsapiTicket = $this->getJsApiTicket();
// 注意 URL 一定要动态获取,不能 hardcode.
$protocol = (!empty($_SERVER[‘HTTPS‘]) && $_SERVER[‘HTTPS‘] !== ‘off‘ || $_SERVER[‘SERVER_PORT‘] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$timestamp = time();
$nonceStr = $this->createNonceStr();
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
$signature = sha1($string);
$signPackage = array(
"appId" => self::APPID,
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $signature,
"rawString" => $string
);
return $signPackage;
}
private function getJsApiTicket() {
// jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("jsapi_ticket.json"));
if ($data->expire_time < time()) {
$accessToken = $this->getAccessToken();
// 如果是企业号用以下 URL 获取 ticket
// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
$res = json_decode($this->httpGet($url));
$ticket = $res->ticket;
if ($ticket) {
$data->expire_time = time() + 7000;
$data->jsapi_ticket = $ticket;
$fp = fopen("jsapi_ticket.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$ticket = $data->jsapi_ticket;
}

return $ticket;
}
private function createNonceStr($length = 16) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
private function getAccessToken() {
// 公众号的id和secret
$appid = ‘xxxxxxxxx‘;
$appsecret = ‘xxxxxxxxx‘;
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("access_token.json"));
if ($data->expire_time < time()) {
// 如果是企业号用以下URL获取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$appSecret";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appSecret}";
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$fp = fopen("access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
2.html页面需要引入js
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
3.在html页面对引入的js使用方法
<script>
1.配置(页面中即使有多个地方需要图片上传也只需要配置一次)
wx.config({
// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
debug: false,
appId:‘{$signature.appId}‘, // 必填,公众号的唯一标识
timestamp:‘{$signature.timestamp}‘, // 必填,生成签名的时间戳
nonceStr: ‘{$signature.nonceStr}‘, // 必填,生成签名的随机串
signature:‘{$signature.signature}‘,// 必填,签名,见附录1
jsApiList: [‘chooseImage‘,‘previewImage‘,‘uploadImage‘,‘downloadImage‘] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
2.点击对象id var choose=document.getElementById(‘choose‘);
3. 需要注意如果有多个位置需要图片上传则需要重新定义一个images
var images={
localId:[],
serverId:[],
}
4.
wx.ready(function(){
var total=5;/*限制上传的数量,最多9个*/
var sum=0;/*每次上传的数量*/
var upsum=0;/*已上传的总数*/
choose1.onclick=function(){
wx.chooseImage({
count:1,/*默认为9*/
success:function(res){
images1.localId=res.localIds;/*保存到images*/
sum=images1.localId.length;
if((upsum+sum)>total){
var last=total-upsum;
alert(‘你还可以选择:‘+last+‘张‘);
return false;
}
var count=res.localIds.length+upsum;
for(j=upsum;j<count;j++){
if(j==0){
//hrml页面预览图片的id=“ImgPr1”
$("#ImgPr1").attr(‘src‘,res.localIds[0]);
}else{
//页面中多张图片预览图片的div的class=“imageitem”,页面中若有多个位置图片上传则class不同
$new=$(".imageitem").last().clone(true);
$new.find(‘img‘).attr(‘src‘,res.localIds[j-upsum]);
$new.insertAfter($(".imageitem").last());
}
}
upsum=upsum+sum;
/*上传图片到微信服务器*/
var i=0;len=images1.localId.length;
wxupload();
function wxupload(){
wx.uploadImage({
localId: images1.localId[i], // 需要上传的图片的本地ID,由chooseImage接口获得
//isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
i++;
//将上传成功后的serverId保存到serverid
images1.serverId.push(res.serverId);
if(i < len){
wxupload();
}
}

});
}
/*上传图片*/
}
});
}
});
5.
/*验证失败时执行的函数*/
wx.error(function(res){
alert(res.errMsg);
});
6.获取媒体id
//不同的位置图片长传此处不同(serverId,images对应前面定义的images)
var serverId = images.serverId;
//多张图片循环获取将其以字符串的形式存储起来
var str3=“”;
for (var i = 0; i < serverId.length; i++) {
str3 += ‘img=‘ + serverId[i];
};
</script>
4.在php页面需要加入的代码
<?php
1.获取之前传过来的媒体id,多个为字符串
$media_id=“********”;
//获取access_token(即使有多个在此值都是相同的,仅需获取一次即可)
$access_token=$this->get_ak();
2.获取access_token的函数
public function get_ak() {
return $this->getAccessToken();
}
private function getAccessToken() {
// 公众号的id和secret
$appid = ‘xxxxxxxxx‘;
$appsecret = ‘xxxxxxxxx‘;
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("access_token.json"));
if ($data->expire_time < time()) {
// 如果是企业号用以下URL获取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$appSecret";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appSecret}";
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$fp = fopen("access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
private function httpGet($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
3.$url1 = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";
4.获取图片的地址
$fileInfo=$this->getmedia($access_token,$media_id,‘img‘);//img为存入的地址
5.多张图片需要对图片进行分割
$media_zxbg=explode(‘img=‘, $media_id);
$media_id_zxbg=array();
for($j=0;$j<count($media_zxbg);$j++){
if(!empty($media_zxbg[$j])){
array_push($media_id_zxbg, $media_zxbg[$j]);
}
}
for($i=0;$i<count($media_id_zxbg);$i++){
$serverId3=$media_id_zxbg[$i];
$myresult3=$this->getmedia($access_token,$serverId3,‘img‘);
if(empty($myresult3)){
$msgdata[‘msg‘]="图片上传失败,请重新上传!";
} else {
$lbimg[$i][‘img‘]=$myresult3;
$str3.=$lbimg[$i][‘img‘].",";
}
}
6. 获取图片地址
public function getmedia($access_token,$media_id,$foldername){
header("Content-Type: text/html; charset=UTF-8");
$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
if (!file_exists("./uploads/".$foldername)) {//判断目录是否存在,不存在则重新创建
mkdir("./uploads/".$foldername, 0777, true);//0777为设置图片存入的目录权限
}
$targetName = ‘./Uploads/‘.$foldername.‘/‘.date(‘YmdHis‘).rand(1000,9999).‘.jpg‘;
$ch = curl_init($url); // 初始化
$fp = fopen($targetName, ‘wb‘); // 打开写入
curl_setopt($ch, CURLOPT_FILE, $fp); // 设置输出文件的位置,值是一个资源类型
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
return $targetName;
}
?>
注:正常情况下access_token有效期为7200秒
接口授权,网页授权域名需要配置,

 

一、获取授权并得到用户信息
1.发者需要先到公众平台官网中的开发者中心页配置授权回调域名
2.授权回调域名配置规范为全域名
3.以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
4.以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过。
5.UnionID机制的作用说明:如果开发者拥有多个移动应用、网站应用和公众帐号,可通过获取用户基本信息中的unionid来区分用户的唯一性,因为同一用户,对同一个微信开放平台下的不同应用(移动应用、网站应用和公众帐号),unionid是相同的。
需要函数工具
6.snsapi_base与snsapi_userinfo的区别:
snsapi_base只能获取access_token和openID
snsapi_userinfo可以获取更详细的用户资料,比如头像、昵称、性别等
1.function https_request($url, $data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
2.public function user_info(){
// 回调地址为全域名
$url = urlencode("http://jsph.lision.cn/index.php?g=wechat&m=Index&a=user_info");
// 公众号的id和secret
$appid = ‘xxxxxxxxx‘;
$appsecret = ‘xxxxxxxxx‘;
//开启session
session_start();
// 获取code码,用于和微信服务器申请token。此处授权登录需要用户端操作
if(!isset($_GET[‘code‘]) && !isset($_SESSION[‘code‘])){
echo
‘<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=‘.$appid.‘&redirect_uri=‘.$url.‘&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"><font style="font-size:30">授权</font></a>‘;
exit;
}
// 依据code码去获取openid和access_token,自己的后台服务器直接向微信服务器申请即可
if (isset($_GET[‘code‘]) && !isset($_SESSION[‘token‘])){
$_SESSION[‘code‘] = $_GET[‘code‘];
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$_GET[‘code‘]."&grant_type=authorization_code";
$res = https_request($url);
$res =(json_decode($res, true));
$_SESSION[‘token‘] = $res;
}
// 依据申请到的access_token和openid,申请Userinfo信息。
if (isset($_SESSION[‘token‘][‘access_token‘])){
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$_SESSION[‘token‘][‘access_token‘]."&openid=".$_SESSION[‘token‘][‘openid‘]."&lang=zh_CN";
$res = https_request($url);
$res = json_decode($res, true);
//将用户信息存储到session中
$_SESSION[‘userinfo‘] = $res;
}
//打印用户信息
print_r($_SESSION);
}
二、获取微信菜单
1.创建菜单(若是修改菜单需要先删除以前的菜单再重新获取新菜单)
2.获取菜单
3.删除菜单
4.显示菜单
public function menu(){
header("Content-type: text/html; charset=utf-8");
$data = ‘{
"button":[
{
"type":"view",
"name":"链接",
"url":"http://jsph.lision.cn/index.php?g=wechat&m=index&a=info"
},
{
"name":"按钮",
"sub_button":[
{
"type":"view",
"name":"当前订单",
"url":"http://jsph.lision.cn/index.php?g=wechat&m=index&a=current"
},
{
"type":"view",
"name":"历史订单",
"url":"http://jsph.lision.cn/index.php?g=wechat&m=index&a=history"
}]
},
{
"type":"click",
"name":"联系我们",
"key":"V1001_GOOD"
}]
}‘;
// 公众号的id和secret
$appid = ‘xxxxxxxxx‘;
$appsecret = ‘xxxxxxxxx‘;
$token = session("token");
if($token){
$auth = new WechatAuth($appid, $appsecret, $token);
$access_token = $token;
} else {
$auth = new WechatAuth($appid, $appsecret);
$token = $auth->getAccessToken();

session(array(‘expire‘ => $token[‘expires_in‘]));
session("token", $token[‘access_token‘]);
$access_token = $token[‘access_token‘];
}
return self::createMenu($data,$access_token);
}
三、自动回复
在微信公众平台配置服务器时的地址例如http://swxt.lision.cn/portal/index/wechat
那么关注的方法就要写在wechat里面,如不这样配置关注无法自动回复
所需方法如下
public function wechat($id = ‘‘){
//调试
try{
$appid = self::APPID; //AppID(应用ID)
$token = self::TOKEN; //微信后台填写的TOKEN
$crypt = self::CRYPT; //消息加密KEY(EncodingAESKey)

/* 加载微信SDK */
$wechat = new Wechat($token, $appid, $crypt);

/* 获取请求信息 */
$data = $wechat->request();

if($data && is_array($data)){
/**
* 你可以在这里分析数据,决定要返回给用户什么样的信息
* 接受到的信息类型有10种,分别使用下面10个常量标识
* Wechat::MSG_TYPE_TEXT //文本消息
* Wechat::MSG_TYPE_IMAGE //图片消息
* Wechat::MSG_TYPE_VOICE //音频消息
* Wechat::MSG_TYPE_VIDEO //视频消息
* Wechat::MSG_TYPE_SHORTVIDEO //视频消息
* Wechat::MSG_TYPE_MUSIC //音乐消息
* Wechat::MSG_TYPE_NEWS //图文消息(推送过来的应该不存在这种类型,但是可以给用户回复该类型消息)
* Wechat::MSG_TYPE_LOCATION //位置消息
* Wechat::MSG_TYPE_LINK //连接消息
* Wechat::MSG_TYPE_EVENT //事件消息
*
* 事件消息又分为下面五种
* Wechat::MSG_EVENT_SUBSCRIBE //订阅
* Wechat::MSG_EVENT_UNSUBSCRIBE //取消订阅
* Wechat::MSG_EVENT_SCAN //二维码扫描
* Wechat::MSG_EVENT_LOCATION //报告位置
* Wechat::MSG_EVENT_CLICK //菜单点击
*/

//记录微信推送过来的数据
file_put_contents(‘./data.json‘, json_encode($data));

/* 响应当前请求(自动回复) */
//$wechat->response($content, $type);

/**
* 响应当前请求还有以下方法可以使用
* 具体参数格式说明请参考文档
*
* $wechat->replyText($text); //回复文本消息
* $wechat->replyImage($media_id); //回复图片消息
* $wechat->replyVoice($media_id); //回复音频消息
* $wechat->replyVideo($media_id, $title, $discription); //回复视频消息
* $wechat->replyMusic($title, $discription, $musicurl, $hqmusicurl, $thumb_media_id); //回复音乐消息
* $wechat->replyNews($news, $news1, $news2, $news3); //回复多条图文消息
* $wechat->replyNewsOnce($title, $discription, $url, $picurl); //回复单条图文消息
*
*/

//执行Demo
$this->demo($wechat, $data);
}
} catch(\Exception $e){
file_put_contents(‘./error.json‘, json_encode($e->getMessage()));
}
}


private function demo($wechat, $data){
switch ($data[‘MsgType‘]) {
case Wechat::MSG_TYPE_EVENT:
switch ($data[‘Event‘]) {
// 关注事件
case Wechat::MSG_EVENT_SUBSCRIBE:
$wechat->replyNewsOnce(
"合肥书文学堂",
"书文学堂 专做语文\n市府广场校区:13349295520 13339282938\n香港街校区:13339286717 63848431",
"http://swxt.lision.cn/portal/wechat/about",
"http://swxt.lision.cn/themes/simplebootx/Public/assets/images/swxt.png"
); //回复单条图文消息
break;
case Wechat::MSG_EVENT_SUBSCRIBE:
$wechat->replyText(‘欢迎您关注合肥书文学堂公众平台!‘);
break;

default:
$wechat->replyText("欢迎访问合肥书文学堂公众平台!您的事件类型:{$data[‘Event‘]},EventKey:{$data[‘EventKey‘]}");
break;
}
break;

case Wechat::MSG_TYPE_TEXT:
switch ($data[‘Content‘]) {
case ‘如何报班‘:
$wechat->replyNewsOnce(
"合肥书文学堂",
"书文学堂 专做语文\n市府广场校区:13349295520 13339282938\n香港街校区:13339286717 63848431",
"http://swxt.lision.cn/",
"http://swxt.lision.cn/themes/simplebootx/Public/assets/images/swxt.png"
); //回复单条图文消息
break;
default:
$wechat->replyText("书文学堂 专做语文\n 市府广场校区:13349295520 13339282938\n 香港街校区:13339286717 63848431");
break;
}
break;

default:
# code...
break;
}
}
四、图片上传
1.在php 页面需要获取签名在html里面配置js
$signature=$this->getSignPackage();
public function getSignPackage() {
$jsapiTicket = $this->getJsApiTicket();
// 注意 URL 一定要动态获取,不能 hardcode.
$protocol = (!empty($_SERVER[‘HTTPS‘]) && $_SERVER[‘HTTPS‘] !== ‘off‘ || $_SERVER[‘SERVER_PORT‘] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$timestamp = time();
$nonceStr = $this->createNonceStr();
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
$signature = sha1($string);
$signPackage = array(
"appId" => self::APPID,
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $signature,
"rawString" => $string
);
return $signPackage;
}
private function getJsApiTicket() {
// jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("jsapi_ticket.json"));
if ($data->expire_time < time()) {
$accessToken = $this->getAccessToken();
// 如果是企业号用以下 URL 获取 ticket
// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
$res = json_decode($this->httpGet($url));
$ticket = $res->ticket;
if ($ticket) {
$data->expire_time = time() + 7000;
$data->jsapi_ticket = $ticket;
$fp = fopen("jsapi_ticket.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$ticket = $data->jsapi_ticket;
}

return $ticket;
}
private function createNonceStr($length = 16) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
private function getAccessToken() {
// 公众号的id和secret
$appid = ‘xxxxxxxxx‘;
$appsecret = ‘xxxxxxxxx‘;
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("access_token.json"));
if ($data->expire_time < time()) {
// 如果是企业号用以下URL获取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$appSecret";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appSecret}";
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$fp = fopen("access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
2.html页面需要引入js
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
3.在html页面对引入的js使用方法
<script>
1.配置(页面中即使有多个地方需要图片上传也只需要配置一次)
wx.config({
// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
debug: false,
appId:‘{$signature.appId}‘, // 必填,公众号的唯一标识
timestamp:‘{$signature.timestamp}‘, // 必填,生成签名的时间戳
nonceStr: ‘{$signature.nonceStr}‘, // 必填,生成签名的随机串
signature:‘{$signature.signature}‘,// 必填,签名,见附录1
jsApiList: [‘chooseImage‘,‘previewImage‘,‘uploadImage‘,‘downloadImage‘] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
2.点击对象id var choose=document.getElementById(‘choose‘);
3. 需要注意如果有多个位置需要图片上传则需要重新定义一个images
var images={
localId:[],
serverId:[],
}
4.
wx.ready(function(){
var total=5;/*限制上传的数量,最多9个*/
var sum=0;/*每次上传的数量*/
var upsum=0;/*已上传的总数*/
choose1.onclick=function(){
wx.chooseImage({
count:1,/*默认为9*/
success:function(res){
images1.localId=res.localIds;/*保存到images*/
sum=images1.localId.length;
if((upsum+sum)>total){
var last=total-upsum;
alert(‘你还可以选择:‘+last+‘张‘);
return false;
}
var count=res.localIds.length+upsum;
for(j=upsum;j<count;j++){
if(j==0){
//hrml页面预览图片的id=“ImgPr1”
$("#ImgPr1").attr(‘src‘,res.localIds[0]);
}else{
//页面中多张图片预览图片的div的class=“imageitem”,页面中若有多个位置图片上传则class不同
$new=$(".imageitem").last().clone(true);
$new.find(‘img‘).attr(‘src‘,res.localIds[j-upsum]);
$new.insertAfter($(".imageitem").last());
}
}
upsum=upsum+sum;
/*上传图片到微信服务器*/
var i=0;len=images1.localId.length;
wxupload();
function wxupload(){
wx.uploadImage({
localId: images1.localId[i], // 需要上传的图片的本地ID,由chooseImage接口获得
//isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
i++;
//将上传成功后的serverId保存到serverid
images1.serverId.push(res.serverId);
if(i < len){
wxupload();
}
}

});
}
/*上传图片*/
}
});
}
});
5.
/*验证失败时执行的函数*/
wx.error(function(res){
alert(res.errMsg);
});
6.获取媒体id
//不同的位置图片长传此处不同(serverId,images对应前面定义的images)
var serverId = images.serverId;
//多张图片循环获取将其以字符串的形式存储起来
var str3=“”;
for (var i = 0; i < serverId.length; i++) {
str3 += ‘img=‘ + serverId[i];
};
</script>
4.在php页面需要加入的代码
<?php
1.获取之前传过来的媒体id,多个为字符串
$media_id=“********”;
//获取access_token(即使有多个在此值都是相同的,仅需获取一次即可)
$access_token=$this->get_ak();
2.获取access_token的函数
public function get_ak() {
return $this->getAccessToken();
}
private function getAccessToken() {
// 公众号的id和secret
$appid = ‘xxxxxxxxx‘;
$appsecret = ‘xxxxxxxxx‘;
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("access_token.json"));
if ($data->expire_time < time()) {
// 如果是企业号用以下URL获取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$appSecret";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appSecret}";
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$fp = fopen("access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
private function httpGet($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
3.$url1 = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";
4.获取图片的地址
$fileInfo=$this->getmedia($access_token,$media_id,‘img‘);//img为存入的地址
5.多张图片需要对图片进行分割
$media_zxbg=explode(‘img=‘, $media_id);
$media_id_zxbg=array();
for($j=0;$j<count($media_zxbg);$j++){
if(!empty($media_zxbg[$j])){
array_push($media_id_zxbg, $media_zxbg[$j]);
}
}
for($i=0;$i<count($media_id_zxbg);$i++){
$serverId3=$media_id_zxbg[$i];
$myresult3=$this->getmedia($access_token,$serverId3,‘img‘);
if(empty($myresult3)){
$msgdata[‘msg‘]="图片上传失败,请重新上传!";
} else {
$lbimg[$i][‘img‘]=$myresult3;
$str3.=$lbimg[$i][‘img‘].",";
}
}
6. 获取图片地址
public function getmedia($access_token,$media_id,$foldername){
header("Content-Type: text/html; charset=UTF-8");
$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
if (!file_exists("./uploads/".$foldername)) {//判断目录是否存在,不存在则重新创建
mkdir("./uploads/".$foldername, 0777, true);//0777为设置图片存入的目录权限
}
$targetName = ‘./Uploads/‘.$foldername.‘/‘.date(‘YmdHis‘).rand(1000,9999).‘.jpg‘;
$ch = curl_init($url); // 初始化
$fp = fopen($targetName, ‘wb‘); // 打开写入
curl_setopt($ch, CURLOPT_FILE, $fp); // 设置输出文件的位置,值是一个资源类型
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
return $targetName;
}
?>
注:正常情况下access_token有效期为7200秒
接口授权,网页授权域名需要配置,

 

微信笔记

标签:nsf   get   html   判断   ...   div   创建   func   mkdir   

原文地址:http://www.cnblogs.com/wjw-/p/7753813.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!