jssdk.php 接口文件
class JSSDK {
private $appId;
private $appSecret; public function __construct($appId, $appSecret) {
$this->appId = $appId;
$this->appSecret = $appSecret;
} 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" => $this->appId,
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $signature,
"rawString" => $string
);
return $signPackage;
} 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 getJsApiTicket() {
// jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("wxjs/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));
//print_r($res);
$ticket = $res->ticket;
if ($ticket) {
$data->expire_time = time() + 7000;
$data->jsapi_ticket = $ticket;
$fp = fopen("wxjs/jsapi_ticket.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$ticket = $data->jsapi_ticket;
} return $ticket;
} private function getAccessToken() {
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("wxjs/access_token.json"));
if ($data->expire_time < time()) {
//if (true) {
// 如果是企业号用以下URL获取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
$res = json_decode($this->httpGet($url));
// print_r($res);
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$fp = fopen("wxjs/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;
}
}
/*
* 微信分享 朋友、朋友圈 基础配置
*
*/
调用jssdk.php文件获取 singnPackage
function insert_share(){
$weixin_info = $GLOBALS['db']->getRow("SELECT * FROM ".$GLOBALS['ecs']->table('weixin_config'));
if($weixin_info['title'] && $weixin_info['appid'] && $weixin_info['appsecret']){
require_once "wxjs/jssdk.php"; $jssdk = new JSSDK($weixin_info['appid'], $weixin_info['appsecret']);
$signPackage = $jssdk->GetSignPackage();
if($signPackage){
//判断是否登陆
if(!empty($_SESSION['user_id'])){
$GLOBALS['smarty']->assign('is_login', '1');
}
// //判断是否微信
$is_weixin = is_weixin();
if($is_weixin){
$GLOBALS['smarty']->assign('is_weixin', '1');
} $need_cache = $GLOBALS['smarty']->caching;
$GLOBALS['smarty']->caching = false;
$GLOBALS['smarty']->assign('weixin_info', $weixin_info);
$GLOBALS['smarty']->assign('signPackage', $signPackage);
$GLOBALS['smarty']->assign ( 'is_thumbnail', $weixin_info['is_thumbnail'] );
$GLOBALS['smarty']->assign ( 'weixin_logo', $weixin_info['weixin_logo'] ); $shop_name = $weixin_info['title']; $web_url ='http://'.$_SERVER['HTTP_HOST']; if(preg_match('/goods.php/i', $_SERVER['REQUEST_URI'])){//处理商品详情页分享 $goods_id = intval($_GET['id']); $sql = "select * from ". $GLOBALS['ecs']->table('goods') ." where goods_id=".$goods_id; $row = $GLOBALS['db']->getRow($sql); $goods_price = $row['shop_price']; $sharemsg = sprintf($weixin_info['sharemsg'],$shop_name,$goods_price);//后台自定义描述 $share_tiele = $row['goods_name']; if( $weixin_info['is_thumbnail'] == 0){ $share_img = $web_url."/".$row['goods_thumb']; }else{ $share_img = $web_url."/mobile/".$weixin_info['weixin_logo']; }
}elseif(preg_match('/tuiguang.php/i', $_SERVER['REQUEST_URI']) || preg_match('/article.php/i', $_SERVER['REQUEST_URI'])){//单品推广/文章详情 $article_id = intval($_GET['id']); $sql = "select * from ". $GLOBALS['ecs']->table('article') ." where article_id=".$article_id; $row = $GLOBALS['db']->getRow($sql); if(!empty($row['description'])){ $sharemsg = $row['description'];//描述 }else{ $sharemsg = $GLOBALS['_CFG']['shop_desc'];//描述 } $share_tiele = $row['title'];//标题 if( $weixin_info['is_thumbnail'] == 0 && !empty($row['file_url'])){//缩略图 $share_img = $web_url."/mobile/".$row['file_url']; }else{ $share_img = $web_url."/mobile/".$weixin_info['weixin_logo']; } }elseif(preg_match('/article_detail.php/i', $_SERVER['REQUEST_URI'])){//文章广告植入系统 $article_id = intval($_GET['id']); $sql = "select * from ". $GLOBALS['ecs']->table('article') ." where article_id=".$article_id; $row = $GLOBALS['db']->getRow($sql); if(!empty($row['description'])){ $sharemsg = $row['description'];//描述 }else{ $sharemsg = "转发文章也能赚钱?!不信您也来试试!!";//描述 } $share_tiele = $row['title'];//标题 if( $weixin_info['is_thumbnail'] == 0 && !empty($row['file_url'])){//缩略图 $share_img = $web_url."/mobile/".$row['file_url']; }else{ $share_img = $web_url."/mobile/".$weixin_info['weixin_logo']; } }else{ $sharemsg = $_CFG['shop_desc']; $sql = "select value from ". $GLOBALS['ecs']->table('ecsmart_shop_config') ." where code= 'shop_name'"; $share_tiele = $GLOBALS['db']->getOne($sql); $sql = "select value from ". $GLOBALS['ecs']->table('ecsmart_shop_config') ." where code= 'shop_desc'"; $sharemsg = $GLOBALS['db']->getOne($sql); $share_img = $web_url."/mobile/".$weixin_info['weixin_logo']; } $user_id = $_SESSION['user_id']; $sql = "select * from ". $GLOBALS['ecs']->table('weixin_user') ." where ecuid= '$user_id'"; $ret = $GLOBALS['db']->getRow($sql); $guide_qrcode = $web_url."/mobile/".$weixin_info['guide_qrcode'];
//echo $_SESSION['user_id'].'-'.$_SESSION['show_guide_qrcode'];
if( $weixin_info['open_guide'] == 1 && $ret['isfollow'] == 0 && $_SESSION['user_id'] && empty($_SESSION['show_guide_qrcode']) ){//是否开启未关注用户引导关注二维码 $guide_qrcode = $web_url."/mobile/".$weixin_info['guide_qrcode']; $GLOBALS['smarty']->assign('open_guide', 1); $GLOBALS['smarty']->assign('guide_qrcode', $guide_qrcode);
$_SESSION['show_guide_qrcode']=1; } $GLOBALS['smarty']->assign('share_tiele', $share_tiele); $GLOBALS['smarty']->assign('share_img', $share_img); $GLOBALS['smarty']->assign('sharemsg', $sharemsg); $output = $GLOBALS['smarty']->fetch('library/share.lbi'); $GLOBALS['smarty']->caching = $need_cache; return $output;
} }
}

  

模板文件中,调用weixin的js接口
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script>
wx.config({
debug: false,
appId: '{$signPackage.appId}',
timestamp: '{$signPackage.timestamp}',
nonceStr: '{$signPackage.nonceStr}',
signature: '{$signPackage.signature}',
jsApiList: [
// 所有要调用的 API 都要加到这个列表中
'onMenuShareTimeline','onMenuShareAppMessage','getLocation','translateVoice'
]
});
wx.ready(function () { //分享到朋友圈
wx.onMenuShareTimeline({ link: window.location.href, // 分享链接
title: '{$sharemsg}', // 分享标题
imgUrl: '{$share_img}',// 分享图标
<!--{if $is_login}-->
success: function () {
console.log("weixin_share.php?act=mycheck");
$.post("weixin_share.php?act=mycheck",{'id':'1','uid':'1','show':'1','type':'pengyouquan'},function(data,status){
console.log("111111111111111111");
data= eval('(' + data + ')');
if (data.state == 1){
alert('微信分享收益提示:本次分享获得'+data.share_money+'元;'+data.share_point+'积分');
}else{
alert('微信分享收益提示:今天的奖励已赠送过啦!感谢您的分享!!');
}
});
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
<!--{/if}-->
}); //分享给朋友
wx.onMenuShareAppMessage({ title: '{$share_tiele}',//分享标题
desc: '{$sharemsg}',
link: window.location.href,
imgUrl: '{$share_img}', // 分享图标
type: '', // 分享类型,music、video或link,不填默认为link
dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
<!--{if $is_login}-->
success: function () {
// 用户确认分享后执行的回调函数 $.post("weixin_share.php?act=mycheck",{'id':'1','uid':'1','show':'1','type':'pengyou'},function(data,status){
console.log("2222222222222");
data= eval('(' + data + ')');
if (data.state == 1){
alert('微信分享收益提示:本次分享获得'+data.share_money+'元;'+data.share_point+'积分');
}else{
alert('微信分享收益提示:今天的奖励已赠送过啦!感谢您的分享!!');
} });
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
<!--{/if}-->
});
});
</script>

  

分享成功后,回调写积分文件
<?php define('IN_ECS', true);
define('ECS_ADMIN', true); require('../includes/init.php');
$is_weixin = is_weixin();
if($is_weixin && !empty($_POST['id']) && !empty($_POST['uid']) && !empty($_POST['show']) && !empty($_POST['type']) && !empty($_GET['act']) && !empty($_SESSION['user_id'])){
if($_GET['act'] == 'mycheck')
{
if($_POST['type'] == 'pengyouquan'){
$weixin_info = $db->getRow("select * from ".$ecs->table('weixin_config')." where id='1'");
$share_money = round(randomFloat_share($weixin_info['pengyouquan_money'], $weixin_info['pengyouquan_money_up']),2);
$share_point = round(randomFloat_share($weixin_info['pengyouquan_point'], $weixin_info['pengyouquan_point_up']));
if($weixin_info['appid'] && $weixin_info['appsecret'] && $weixin_info['title'] && $weixin_info['is_pengyouquan'] == '1'){
$nowtime = mktime();
//$yestime = strtotime(date('Y-m-d'));
$yestime = strtotime(date('Y-m-d', time())); $count = $db->getOne("select count(*) from ".$ecs->table('weixin_share')." where type='2' and user_id=".$_SESSION['user_id']." and create_time > '$yestime'"); if($weixin_info['is_everyday'] == '1'){ if($count <= $weixin_info['pengyouquan_times'] ){
$info = date('Y-m-d H:i:s')."微信分享朋友圈,获得".$share_money.'元,'.$share_point.'积分';
log_account_change($_SESSION['user_id'], $share_money, 0, 0, $share_point, $info);
}else{
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','1','$nowtime') ");
$state = '0';
echo json_encode(array('state'=>$state ));
exit; }
}
else
{
if($count <= $weixin_info['pengyouquan_times'] ){
$info = date('Y-m-d H:i:s')."微信分享朋友圈,获得".$share_money.'元,'.$share_point.'积分';
log_account_change($_SESSION['user_id'], $share_money, 0, 0, $share_point, $info);
}else{
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','1','$nowtime') ");
$state = '0';
echo json_encode(array('state'=>$state ));
exit; }
}
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','2','$nowtime') "); $state = '1';
echo json_encode(array('share_money'=>$share_money,'share_point'=>$share_point,'state'=>$state));
}
} if($_POST['type'] == 'pengyou'){
$weixin_info = $db->getRow("select * from ".$ecs->table('weixin_config')." where id='1'");
$share_money = round(randomFloat_share($weixin_info['pengyou_money'], $weixin_info['pengyou_money_up']),2);
$share_point = round(randomFloat_share($weixin_info['pengyou_point'], $weixin_info['pengyou_point_up']));
if($weixin_info['appid'] && $weixin_info['appsecret'] && $weixin_info['title'] && $weixin_info['is_pengyou'] == '1'){
$nowtime = mktime();
//$yestime = strtotime(date('Y-m-d'));
$yestime = strtotime(date('Y-m-d', time()));
$count = $db->getOne("select count(*) from ".$ecs->table('weixin_share')." where type='1' and user_id=".$_SESSION['user_id']." and create_time > '$yestime'");
if($weixin_info['is_everyday'] == '1'){ if($count <= $weixin_info['pengyou_times'] ){
$info = date('Y-m-d H:i:s')."微信分享给朋友,获得".$share_money.'元,'.$share_point.'积分';
log_account_change($_SESSION['user_id'], $share_money, 0, 0, $share_point, $info);
}else{
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','1','$nowtime') ");
$state = '0';
echo json_encode(array('state'=>$state ));
exit; }
}
else
{
if($count <= $weixin_info['pengyou_times'] ){
$info = date('Y-m-d H:i:s')."微信分享给朋友,获得".$share_money.'元,'.$share_point.'积分';
log_account_change($_SESSION['user_id'], $share_money, 0, 0, $share_point, $info);
}else{
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','1','$nowtime') ");
$state = '0';
echo json_encode(array('state'=>$state ));
exit; }
}
$db->query("insert into ".$ecs->table('weixin_share')." (`user_id`,`type`,`create_time`) values ('$_SESSION[user_id]','1','$nowtime') ");
$state = '1';
echo json_encode(array('share_money'=>$share_money,'share_point'=>$share_point,'state'=>$state)); }
}
}
} function is_weixin()
{
$useragent = addslashes($_SERVER['HTTP_USER_AGENT']);
if(strpos($useragent, 'MicroMessenger') === false && strpos($useragent, 'Windows Phone') === false )
{
return false;
}
else
{
return true;
}
} //生成随机数 P R I N C E Q Q 120 029 121
function randomFloat_share($min = 0, $max = 1) {
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

  

微信JS-SDK接口,分享到朋友圈”按钮点击状态及自定义分享内容接口的更多相关文章

  1. Python微信-- 分享接口(分享到朋友圈、朋友、空间)

    生成JS-SDK权限验证的签名 获取signature(签名)首先要获得 1.#获得jsapi_ticket 2.#获取当前页面的url #获取当前页面的url url="{}://{}{} ...

  2. 微信js SDK接口

    微信JS-SDK说明文档 http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html 一.微信登录功能 在进行微信OAut ...

  3. 微信公众号开发--微信JS-SDK分享到朋友圈和分享给朋友

    之前写过一篇使用微信JS-SDK来实现扫一扫功能的博客 微信公众号开发–微信JS-SDK扫一扫功能 在该博客里介绍了微信JS-SDK的基本用法,其中包括以下几个步骤 还详细介绍了通过config接口注 ...

  4. 微信js sdk上传多张图片

    微信js sdk上传多张图片,微信上传多张图片 该案例已tp3.2商城为例 直接上代码: php代码: public function ind(){ $appid="111111111111 ...

  5. 微信JS SDK Demo 官方案例[转]

    摘要: 微信JS-SDK是微信公众平台面向网页开发者提供的基于微信内的网页开发工具包. 通过使用微信JS-SDK,网页开发者可借助微信高效地使用拍照.选图.语音.位置等手机系统的能力,同时可以直接使用 ...

  6. 微信JS SDK Demo

    微信JS-SDK 分享到朋友圈 分享给朋友 分享到QQ 拍照或从手机相册中选图 识别音频并返回识别结果 使用微信内置地图查看位置原文:http://www.cnblogs.com/txw1958/p/ ...

  7. 微信JS SDK Demo 官方案例

    微信JS-SDK是微信公众平台面向网页开发者提供的基于微信内的网页开发工具包. 通过使用微信JS-SDK,网页开发者可借助微信高效地使用拍照.选图.语音.位置等手机系统的能力,同时可以直接使用微信分享 ...

  8. 微信-js sdk invalid signature签名错误 问题解决

    如果出现 invalid signature,首先可以确定的是你的签名算法有问题.建议:首先查看微信官方网站给出的解决方案,链接为: http://mp.weixin.qq.com/wiki/7/aa ...

  9. 微信开发(2):微信js sdk分享朋友圈,朋友,获取config接口注入权限验证(转)

    进行微信开发已经一阵子了,从最初的什么也不懂,到微信授权登录,分享,更改底部菜单,素材管理,等. 今天记录一下微信jssdk 的分享给朋友的功能,获取config接口注入. 官方文档走一下简单说:四步 ...

随机推荐

  1. Python巨蟒全栈开发目录

    巨蟒python全栈开发-第一阶段 基础数据类型&基础 1.什么是计算机&&python的简介(待补充) 2.while循环&&格式化输出&&运 ...

  2. HTML代码大全

    1.html的简介* 什么是html?- HyperText Markup Language:超文本标记语言,网页语言** 超文本:超出文本的范畴,使用html可以轻松实现这样操作** 标记:html ...

  3. 设计模式之Prototype模式

    通常我们会使用new 类名()的方法会去生成一个新的实例,但在开发过程中,有时候也会有"在不指定类名的前提下生成实例"的需求,那样,就只能根据现有实例来生成新的实例. 有三种情况, ...

  4. datetime 模块详解 -- 基本的日期和时间类型

    转自:https://www.cnblogs.com/fclbky/articles/4098204.html datetime 模块提供了各种类用于操作日期和时间,该模块侧重于高效率的格式化输出 在 ...

  5. MySQL数据库(二)

    事务 数据库开启事务命令 #start transaction 开启事务 #Rollback 回滚事务,即撤销指定的sql语句(只能回退insert delete update语句),回滚到上一次co ...

  6. Storm简介及使用

    一.Storm概述 网址:http://storm.apache.org/ Apache Storm是一个免费的开源分布式实时计算系统.Storm可以轻松可靠地处理无限数据流,实现Hadoop对批处理 ...

  7. 为golang程序使用pprof远程查看httpserver运行堆栈,cpu耗时等信息

    pprof是个神马玩意儿? pprof - manual page for pprof (part of gperftools) 是gperftools工具的一部分 gperftools又是啥? Th ...

  8. Object-Detection中常用的概念解析

    常用的Region Proposal Selective Search Edge Boxes Softmax-loss softmax-loss层和softmax层计算大致是相同的,softmax是一 ...

  9. DIV+CSS如何让文字垂直居中?

    在说到这个问题的时候,也许有人会问CSS中不是有vertical-align属性来设置垂直居中的吗?即使是某些浏览器不支持我只需做少许的CSS Hack技术就可以啊!所以在这里我还要啰嗦两句,CSS中 ...

  10. python高级之scrapy-redis

    目录: scrapy-redis组件 scrapy-redis配置示例 一.scrapy-redis组件 1.scrapy-redis简介: scrapy-redis是一个基于redis的scrapy ...