tp框架:
控制器方法:
public function index()
{
$ticket = $this-> wx_get_jsapi_ticket();
$timestamp =time();
$nonceStr = $this->getRandCode();
// var_dump($ticket);
// var_dump($nonceStr);exit;
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // url 最好是动态获取
//按照微信的要求排序拼接组合
$signature = sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s",$ticket, $nonceStr, $timestamp, $url);
// echo $signature."<br />";
$signature= sha1($signature); // $signature 这就是微信签名
$this->assign('timestamp',$timestamp);
$this->assign('noncestr',$nonceStr);
$this->assign('signature',$signature);
$this->display();
}
public function wx_get_token() {
$token = S('access_token');
if (!$token)
{
$appid=''; // 微信appid
$appsecret=''; //微信appsecret
$res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret);
$res = json_decode($res, true);
$token = $res['access_token'];
S('access_token', $token, 3600);
}
return $token;
}
function wx_get_jsapi_ticket(){
$ticket = "";
do{
$ticket = S('wx_ticket');
if (!empty($ticket)) {
break;
}
$token = S('access_token');
if (empty($token)){
$this->wx_get_token();
}
$token = S('access_token');
if (empty($token)) {
// logErr("get access token error.");
break;
}
$url2 = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi",$token);
$res = file_get_contents($url2);
$res = json_decode($res, true);
$ticket = $res['ticket'];
S('wx_ticket', $ticket, 3600);
}while(0);
return $ticket;
}
function getRandCode( $length = 16 ) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$tmpstr ='';
for ( $i = 0; $i < $length; $i++ )
{
$tmpstr .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
return $tmpstr;
}
index.html中的写法
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"> </script>
<script>
wx.config({
debug: false, // 调试的bug的
appId: "",
timestamp: '{$timestamp}',
nonceStr: '{$noncestr}',
signature: '{$signature}',
jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 功能列表,我们要使用JS-SDK的什么功能
});
wx.ready(function(){
// 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
wx.onMenuShareTimeline({
title: '1111111', // 分享标题
link: "11111", //分享的url,以http或https开头
imgUrl: "1111", // 分享图标
});
// 获取“分享给朋友”按钮点击状态及自定义分享内容接口
wx.onMenuShareAppMessage({
title: '1111统', // 分享标题
desc: "1111111", // 分享描述
link: "11111", //分享的url,以http或https开头
imgUrl: "1111111", // 分享图标
type: 'link', // 分享类型,music、video或link,不填默认为link
});
});
wx.error(function (res) {
alert(res.errMsg);//错误提示
});
</script>