<?php
/**
* desc:微信js调用类
* author:besttaowenjing@163.com
* date:2016-07-04
*/
namespace application\vendors\weixin;
class Jssdk {
private $appId;
private $appSecret;
public function __construct($appId, $appSecret) {
$this->appId = $appId;
$this->appSecret = $appSecret;
}
public function getSignPackage(){
$jsapiTicket = $this->getJsApiTicket();
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$timestamp = time();
$nonceStr = $this->createNonceStr();
$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$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(dirname(__FILE__).'/jsapi_ticket.json'));
//$data = (object)array();
if ($data->expire_time < time()) {
$accessToken = $this->getAccessToken();
$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(dirname(__FILE__)."/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(dirname(__FILE__)."/access_token.json"));
//$data = (object)array();
if ($data->expire_time < time()) {
$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));
$access_token = $res->access_token;
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$fp = fopen(dirname(__FILE__)."/access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
function httpGet($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
// curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$temp = curl_exec($ch);
curl_close($ch);
return $temp;
}
}
?>
controller
<?php
/**
* desc:h5签到相关
* author:besttaowenjing@163.com
* date:2016-06-22
*/
use application\vendors\weixin\Jssdk;
class SignController extends Controller {
private $appid = 'xxx';
private $appsecret = 'xxx';
/**
* desc:得到活动详情
*/
public function actionGet_activity() {
$request = Yii::app()->request;
$userId = intval($request->getParam('userid'));
if ($userId < 1) {
echo '验证失败';
exit;
}
$activityId = intval($request->getParam('activityid'));
if ($activityId < 1) {
echo '验证失败';
exit;
}
$criteria = new CDbCriteria;
$criteria->select = 'id, title, address, starttime, num';
$activity = Activity::model()->findbypk($activityId, $criteria);
if (empty($activity)) {
echo '您所查询的数据不存在';exit;
}
$jssdk = new Jssdk($this->appid, $this->appsecret);
$signPackage = $jssdk->getSignPackage();
$data = array();
$token = md5(microtime(true));
Yii::app()->session['signtoken'] = $token;
$data['userid'] = $userId;
$data['activity'] = $activity;
$data['token'] = $token;
$data['signPackage'] = $signPackage;
$this->renderPartial('sign', $data);
}
/**
* desc:json输出
*/
private function _showMsg($data) {
echo json_encode($data);
exit;
}
}
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
/*/初始化扫描二维码按钮,传入自定义的 node-type 属性
$(function () {
Qrcode.init($('[node-type=qr-btn]'));
});*/
var getuserurl = "<?php echo $this->createUrl('sign/get_userinfo'); ?>";/**得到用户信息*/
var signurl = "<?php echo $this->createUrl('sign/sign'); ?>";/**得到用户信息*/
var registrationurl = "<?php echo $this->createUrl('sign/registration'); ?>";/**得到用户信息*/
/**扫码*/
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: "<?php echo $signPackage["appId"]; ?>", // 必填,公众号的唯一标识
timestamp: <?php echo $signPackage["timestamp"]; ?>, // 必填,生成签名的时间戳
nonceStr: "<?php echo $signPackage["nonceStr"]; ?>", // 必填,生成签名的随机串
signature: "<?php echo $signPackage["signature"]; ?>", // 必填,签名,见附录1
jsApiList: [// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
'scanQRCode'
]
});
$(".smqd").click(function () {
wx.scanQRCode({
needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function (res) {
var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
if (result.indexOf("=") > 0) {
var arr = result.split("=");
var baomingid = arr[arr.length - 1];
} else {
var arr = result.split("/");
var baomingid = arr[arr.length - 1];
}
if (isNaN(baomingid)) {
alert("获取二维码信息失败。请输入邀请码。");
return false;
}
$.post(getuserurl, {'id': baomingid}, function (data) {
if (data.status != 300) {
$(".phone").val(data.mobile);
$(".username").val(data.realname);
$(".company").val(data.company);
$(".signupid").val(data.id);
$(".baocun").attr("data-type", 1);
$(".zhezhaoceng,.adduserceng").show();
} else {
alert(data.info)
}
}, 'json');
}
});
})
wx.error(function (res) {
alert(res);
});
希望大家多多交流。qq:274501366