- 我们知道code是要小程序向微信服务器请求的一个code码,使用的是wx.login接口。在小程序调用我们Token模型中的getToken接口时,并传入一个code码参数,之后我们的getToken接口接收该code参数后再携带code参数调用微信的接口来获取openid和session_key。我们将该微信接口地址写入配置文件中。
- 在config目录下,创建wechat.php配置文件,写入小程序相关配置信息
<?php
return [
'app_id' => '填你自己的小程序ID',
'app_secret' =>'填你自己的小程序secret',
'login_url' =>'https://api.weixin.qq.com/sns/jscode2session?'.
"appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
];
- 编写UserToken类
<?php
namespace app\api\service;
class UserToken extends Token
{
protected $code;
protected $wxAppID;
protected $wxAppSecret;
protected $wxLoginUrl;
public function __construct($code)
{
$this->code = $code;
$this->wxAppID = config('wechat.app_id');
$this->wxAppSecret = config('wechat.app_secret');
$this->wxLoginUrl = sprintf(config('wechat.login_url'), $this->wxAppID, $this->wxAppSecret, $this->code, $this->code);
}
}
- 编写UserToken类的get方法,我们需要使用php去curl发起http请求,很多地方都会用到,所以我们编写一个公共函数(commen.php文件)。这里抛出的Exception我们用TP5内置的,因为该错误不需要返回给客户端,只供服务端使用。大部分都是经验性的编码,参考即可。
function curl_get($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$res = curl_exec($ch);
curl_close($ch);;
return $res;
}
- UserToken类的get方法
public function get()
{
$result = curl_get($this->wxLoginUrl);
$wxResult = json_decode($result, true);
if (empty($wxResult)) {
throw new Exception('获取session_key及openID时异常,微信内部错误');
} else {
$fail = array_key_exists('errcode', $wxResult);
if ($fail) {
}
}
}