1:config 文件下新建一个文件wechat.php,将个人id和秘钥写入配置文件
网址: https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
<?php return [ //
接口调用请求说明
https请求方式:
'access_token_url' => 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
'appid' => 'wx2d4d05519f4b82d4',
'appsecret' => '48eedda6630c3776474c719cf1d672ac' ];
2:封装:新建一个目录services 下建一个WechatService.php
<?php namespace app\services; use think\Log; class WechatService { protected static $_token_key = 'wxdev:wechat:token'; /* * 微信公众号获取access_token * */ public static function getToken() { $accessToken = cache(self::$_token_key); if (!$accessToken) { $accessTokenUrl = sprintf(config('wechat.access_token_url'), config('wechat.appid'), config('wechat.appsecret')); $accessTokenArr = json_decode(file_get_contents($accessTokenUrl),true); if (isset($accessTokenArr['errcode'])) { // 记录日记 Log::info($accessTokenArr['errmsg']); return false; } else { $accessToken = $accessTokenArr['access_token']; cache(self::$_token_key, $accessToken, $accessTokenArr['expires_in'] - 200); } } return $accessToken; } }
3:本地域名测试,获取access_token,需要access_token 调用即可
/* * 获取access_token * */ public function getToken(){ $accessToken=WechatService::getToken(); echo $accessToken; }