tp5微信sdk之小改麦当苗儿的tp3.2微信sdk
小改麦当苗儿的tp3.2微信sdk类。使之能在tp5.0用。
由于麦当苗儿很久很久没更新了,微信发展太快导致很多接口没有,只能用下基本消息功能和一些简单功能等,不过代码对新手上路还是很有帮助的。如果需要完善的那就推荐easywechat吧。
下载麦当苗儿tp3.2微信SDK
去麦当苗儿的github下载tp3.2微信sdk(更新时间2015年8月4日)
https://github.com/Aoiujz/WechatSDK
或者直接在本站下载没修改的前的和修改后的
迁移及修改命名空间
1、在tp5的extend目录下新建com目录
2、复制/ThinkPHP/Library/Com目录的3个微信sdk文件到tp5/extend/com里
3、修改命名空间为:namespace com; 小写的com
4、删除文件Wechat.class.php中的use Com\WechatCrypt;
5、修改3个文件的文件名,统一去掉.class

代码小改
1、修改Wechat.php和WechatAuth.php两个文件中的 call_user_func(array(self, $type), $content) 为:
call_user_func(array(__CLASS__, $type), $content)
2、在 Wechat.php 构造函数,加入设置其他不变。
use think\Config;
...
public function __construct($token='', $appid = '', $key = ''){
//设置配置
$token = empty($token) ? Config::get('wechat.token'): $token;
$appid = empty($appid) ? Config::get('wechat.appid'): $appid;
$key = empty($key) ? Config::get('wechat.key'): $key;
...
}3、在 WechatAuth.php 构造函数,加入设置
use think\Cache;
use think\Config;
...
public function __construct($appid='', $secret='', $token = null){
//设置配置
$appid = empty($appid) ? Config::get('wechat.appid'): $appid;
$secret = empty($secret) ? Config::get('wechat.appsecret'): $secret;
...
}到这里可以在tp5使用了,用法可以参考他的demo。
tp5配置config.php加入:
'wechat' => [ 'appid' => 'wx58aebef2023e****', 'appsecret' => '14b6fc04530d3ffe38a1618435fa****', 'token' => 'E9E05045F594065909D2B5554A8F****', 'key' => 'q6FPCUoCQWaOiR3UUe5RfQu8A7hlJcMW4BnNyH9****' ]
示例:
<?php
namespace app\index\controller;
use com\Wechat;
use com\WechatAuth;
use think\Controller;
use think\Exception;
use think\Log;
class Index extends Controller {
public function index() {
try{
$wechat = new Wechat();
$data = $wechat->request();
if($data && is_array($data)) {
switch ($data['MsgType']) {
case Wechat::MSG_TYPE_EVENT: //事件消息
switch ($data['Event']) {
case Wechat::MSG_EVENT_SUBSCRIBE: //关注
$wechat->replyText('欢迎您关注!');
break;
case Wechat::MSG_EVENT_UNSUBSCRIBE: //取消关注
break;
...
default:
break;
}
break;
case Wechat::MSG_TYPE_TEXT: //文本消息
$wechat->replyText('欢迎您关注,这是文本回复的内容!');
break;
case Wechat::MSG_TYPE_IMAGE: //图片消息
$wechat->replyText("这是一张图片");
break;
...
default:
break;
}
}
} catch(Exception $e){
Log::error($e->getMessage());
}
}
}拓展网页授权和简化调用流程
1、在 WechatCrypt.php 的 getRandomStr()方法改修饰符为public
2、在 WechatAuth.php 注释掉getAccessToken()和getUserInfo()方法。
3、加入方法,使access_token和jsapi_ticket自动缓存。
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 = WechatCrypt::getRandomStr(16);
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$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;
}
public function getJsApiTicket(){
$jsapi_ticket = Cache::get('wx_jsapi_ticket');
if (!$jsapi_ticket) {
// 如果是企业号用以下 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";
$param = array(
'access_token' => $this->getAccessToken(),
'type' => 'jsapi'
);
$url = "{$this->apiURL}/ticket/getticket";
$ticket = self::http($url, $param);
$ticket = json_decode($ticket, true);
if(is_array($ticket)){
if(!empty($ticket['errcode']))
throw new \Exception($ticket['errcode'].' '.$ticket['errmsg']);
$jsapi_ticket = $ticket['ticket'];
//缓存jsapi_ticket
Cache::set('wx_jsapi_ticket', $jsapi_ticket, time() + $ticket['expires_in'] - 200);
} else {
throw new \Exception('获取微信jsapi_ticket失败!');
}
}
return $jsapi_ticket;
}
public function getAccessToken(){
$access_token = Cache::get('wx_access_token');
if (!$access_token) {
// 如果是企业号用以下URL获取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
$param = array(
'appid' => $this->appId,
'secret' => $this->appSecret,
'grant_type' => 'client_credential'
);
$url = "{$this->apiURL}/token";
$token = self::http($url, $param);
$token = json_decode($token, true);
if(is_array($token)){
if(!empty($token['errcode']))
throw new \Exception($token['errcode'].' '.$token['errmsg']);
$access_token = $token['access_token'];
//缓存access_token
Cache::set('wx_access_token', $access_token, time() + $token['expires_in'] - 200);
} else {
throw new \Exception('获取微信access_token失败!');
}
}
return $access_token;
}
/**
* 获取网页授权access_token,与基础支持中的access_token不同
* @return array|mixed 网页授权access_token
* @throws \Exception
*/
public function getAuthAccessToken(){
if(!isset($_GET['code']))
throw new \Exception("获取微信code失败");
$param = array(
'appid' => $this->appId,
'secret' => $this->appSecret,
'code' => $_GET['code'],
'grant_type' => 'authorization_code'
);
$url = "{$this->oauthApiURL}/oauth2/access_token";
$token = self::http($url, $param);
$token = json_decode($token, true);
if(is_array($token)){
if(!empty($token['errcode']))
throw new \Exception($token['errcode'].' '.$token['errmsg']);
return $token;
} else {
throw new \Exception('获取微信网页授权access_token失败!');
}
}
/**
* 获取网页授权用户信息
* @param string $lang
* @return mixed
*/
public function getAuthUserInfo($lang = 'zh_CN'){
//获取网页授权access_token
$token = $this->getAuthAccessToken();
//获取用户信息
$query = array(
'access_token' => $token['access_token'],
'openid' => $token['openid'],
'lang' => $lang,
);
$info = self::http("{$this->oauthApiURL}/userinfo", $query);
return json_decode($info, true);
}
/**
* 获取授权用户信息
* @param string $access_token 网页授权的access_token
* @param string $openid 用户的OpenID
* @param string $lang 指定的语言
* @return array 用户信息数据,具体参见微信文档
*/
public function getUserInfo($access_token, $openid, $lang = 'zh_CN'){
$query = array(
'access_token' => $access_token,
'openid' => $openid,
'lang' => $lang,
);
$info = self::http("{$this->oauthApiURL}/userinfo", $query);
return json_decode($info, true);
}4、修改 WechatAuth.php 注释掉private $accessToken = ''属性,并把用到该属性的地方该为getAccessToken()方法。
...
public function mediaGet($media_id){
$param = array(
'access_token' => $this->getAccessToken(),
'media_id' => $media_id
);
...
}
...
protected function api($name, $data = '', $method = 'POST', $param = '', $json = true){
$params = array('access_token' => getAccessToken());
...
}已经改完了,控制器加入以下代码调试:
//演示页面调用网页授权
public function view() {
//检查授权
$user_info = $this->checkAuth();
//用户信息
$this->assign("info", $user_info);
$auth = new WechatAuth();
//获取JS-SDK的页面必须先注入配置信息
$signPackage = $auth->getSignPackage();
$this->assign("signPackage", $signPackage);
return $this->fetch();
}
//简单写个验证授权
//实际这里按业务来确定是否来源微信、请求方法类型、数据库处理等判断和操作
private function checkAuth(){
$user_info = session('user_info');
if(!empty($user_info)){
return $user_info;
}
$auth = new WechatAuth();
//如果code为空
if(empty(input('get.code'))){
//跳转至授权
$url = $auth->getRequestCodeURL(request()->url(true));
$this->redirect($url);
}
//根据code换取网页授权access_token和获取用户信息
$user_info = $auth->getAuthUserInfo();
session("user_info", $user_info);
return $user_info;
}view.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
</head>
<body>
{:var_dump($info)}
<script>
wx.config({
debug: true,
appId: '<?php echo $signPackage["appId"];?>',
timestamp: '<?php echo $signPackage["timestamp"];?>',
nonceStr: '<?php echo $signPackage["nonceStr"];?>',
signature: '<?php echo $signPackage["signature"];?>',
jsApiList: [
// 所有要调用的 API 都要加到这个列表中
'getLocation'
]
});
wx.ready(function () {
// 在这里调用 API
//alert(1);
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
var speed = res.speed; // 速度,以米/每秒计
var accuracy = res.accuracy; // 位置精度
//alert(latitude+"-"+longitude);
}
});
});
</script>
</body>
</html>已下载:672 次
已下载:465 次
原创文章,转载请注明出处:https://www.weizhixi.com/article/61.html
