需求
先说需求,就是一个常规的html页面,在微信浏览器展示,页面上需要展示用户的头像和昵称,这里就需要用到网页授权。然后可以把页面分享到朋友圈或好友,需要自定义分享内容
微信授权
创建一个index.php文件,作为网页的要展示的页面
<?php
header("Content-type: text/html; charset=utf-8");
$appid = '66666';
$secret = '77777';
//微信授权成功后,会请求该页面,并带有code参数
$code = $_GET['code']?:'';
$userinfo = [];
if($code){
//使用code凭证,获取access_toekn和用户openid
$code_json = file_get_contents('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code');
$code_res = json_decode($code_json,true);
//使用access_toen和openid获取用户的基本信息
//然后,下面的html页面,可以根据userinfo的值,来展示用户的头像和昵称
if(isset($code_res['access_token'])){
$user_json = file_get_contents('https://api.weixin.qq.com/sns/userinfo?access_token='.$code_res['access_token'].'&openid='.$code_res['openid'].'&lang=zh_CN');
$userinfo = json_decode($user_json,true);
}
}
?>
//下面是html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="content-type" content="text/html" />
<title>hell world</title>
</head>
<body>
<input type="button" value="点击获取授权" onclick="get_root();" />
<script>
function get_root(){
//微信授权后的回调地址,这里设置为本页面。回调地址的域名必须在微信公众号中设置为安全域名
var local = 'http://www.mine.com//index.php';
//微信授权地址
var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=66666&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
window.location.href = url;
}
</script>
</body>
</html>
微信授权的流程比简单,不再赘述
分享
首先,创建一个share.php页面,用来获取JSSDK的配置信息
<?php
header("Content-type: text/html; charset=utf-8");
$appid = '66666';
$secret = '777777';
//获取缓存数据
$file_cache_str = file_get_contents('cache.txt');
$file_cache = [];
if($file_cache_str){
$file_cache = json_decode($file_cache_str,true);
}
//获取access_token凭证
if($file_cache && isset($file_cache['access_token']) && $file_cache['access_token']['time'] > time()){
$access_token = $file_cache['access_token']['value'];
}else{
$token_json = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
$token_info = json_decode($token_json,true);
$access_token = $token_info['access_token'];
$file_cache['access_token'] = ['value'=>$access_token,'time'=>time()+7000];
$res = file_put_contents('cache.txt',json_encode($file_cache));
//var_dump($res);exit;
}
//使用access_token获取jsapi_ticket凭证
if($file_cache && isset($file_cache['jsapi_ticket']) && $file_cache['jsapi_ticket']['time'] > time()){
$jsapi_ticket = $file_cache['jsapi_ticket']['value'];
}else{
$ticket_json =file_get_contents('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi');
$ticket_info = json_decode($ticket_json,true);
$jsapi_ticket = $ticket_info['ticket'];
$file_cache['jsapi_ticket'] = ['value'=>$jsapi_ticket,'time'=>time()+7000];
file_put_contents('cache.txt',json_encode($file_cache));
}
//获取时间戳
$time = time();
//设置随机字符串
$rand_str = 'Wm3WZYTPz0fdfggerrtqq';
//获取分享页面完整的url地址
$host = $_POST['host'];
//获取签名字符串
$str = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$rand_str.'×tamp='.$time.'&url='.$host;
$signature = sha1($str);
//返回配置数据
$data = [
'appId' => $appid,
'timestamp' => $time,
'nonceStr' => $rand_str,
'signature' => $signature
];
echo json_encode($data);
然后我们在index.php页面设置分享代码
先看看我一开始的踩坑的代码
<?php
............................
?>
//下面是html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="content-type" content="text/html" />
<!--引用微信JS库-->
<script type=" text/javascript " src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<title>hell world</title>
</head>
<body>
<input type="button" value="点击获取授权" onclick="get_root();" />
<script>
function get_root(){
.....................
}
</script>
<script>
$(function(){
$.post('share.php',{host:location.href.split('#')[0]},function(res){
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: res.appId, // 必填,公众号的唯一标识
timestamp: res.timestamp, // 必填,生成签名的时间戳
nonceStr: res.nonceStr, // 必填,生成签名的随机串
signature: res.signature,// 必填,签名
jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'] // 必填,需要使用的JS接口列表
});
var share_data = {
title: '你好吗世界', // 分享标题
desc: '我们不能改变世界,但可以改变我们的世界', // 分享描述
link: 'http://www.mine.com/index.php', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: 'http://www.mine.com/share_img.jpg', // 分享图标
success: function () {
}
};
wx.ready(function () { //需在用户可能点击分享按钮前就先调用
wx.onMenuShareAppMessage(share_data);
wx.onMenuShareTimeline(share_data);
});
},'json')
})
</script>
</body>
</html>
代码看着是没问题的,开启debug后,也会弹出config:ok的提示。在pc端的微信浏览器分享给朋友时,是正常的,标题,描述和图片都显示。但是用手机分享是,不起作用。
网上搜了很长时间,有的说授权也不能作为分享页,需要二次跳转;有的说分享链接有问题。反正都一一试过,还是不行。
查看官方文档,说是onMenuShareAppMessage和onMenuShareTimeline即将废弃,要用updateAppMessageShareData和updateTimelineShareData替代。试了下,还是不起作用。
最后发现,是微信js文件版本的问题,要使用最新的updateAppMessageShareData和updateTimelineShareData,必须使用weixin-1.4.0.js
至于为什么上面的代码在微信pc端的浏览器可以使用,在手机上不行。估计应该是PC端的浏览器还是使用的老版本,而手机端的微信已经是最新版本,不再支持
以下为正确代码
<?php
............................
?>
//下面是html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="content-type" content="text/html" />
<!--引用微信JS库-->
<script type=" text/javascript " src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<title>hell world</title>
</head>
<body>
<input type="button" value="点击获取授权" onclick="get_root();" />
<script>
function get_root(){
.....................
}
</script>
<script>
$(function(){
$.post('share.php',{host:location.href.split('#')[0]},function(res){
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: res.appId, // 必填,公众号的唯一标识
timestamp: res.timestamp, // 必填,生成签名的时间戳
nonceStr: res.nonceStr, // 必填,生成签名的随机串
signature: res.signature,// 必填,签名
jsApiList: ['updateAppMessageShareData','updateTimelineShareData'] // 必填,需要使用的JS接口列表
});
var share_data = {
title: '你好吗世界', // 分享标题
desc: '我们不能改变世界,但可以改变我们的世界', // 分享描述
link: 'http://www.mine.com/index.php', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrl: 'http://www.mine.com/share_img.jpg', // 分享图标
success: function () {
}
};
wx.ready(function () { //需在用户可能点击分享按钮前就先调用
//新版分享方法
wx.updateAppMessageShareData(share_data);
wx.updateTimelineShareData(share_data);
});
},'json')
})
</script>
</body>
</html>