微信laravel小程序教程 (laravel5.7微信小程序api开发)

微信小程序用户信息 API 接口

用户登录:wx.login

获取用户信息:wx.getUserInfo

执行以下命令安装扩展:

composer require iwanli/wxxcx

注册服务提供者到 Laravel 中 /config/app.php 的 providers 数组

Iwanli\Wxxcx\WxxcxServiceProvider::class,

发布配置文件

php artisan vendor:publish --tag=wxxcx

生成/config/wxxcx.php配置文件后,将小程序的 AppID 和 AppSecret 填写到 /config/wxxcx.php 文件中

为方便管理将配置信息存放在.env文件中

修改wxxcx.php 文件如下:

return [

/**

* 小程序APPID

*/

'appid' => env('WECHAT_MINI_PROGRAM_APPID', ''),

/**

* 小程序Secret

*/

'secret' => env('WECHAT_MINI_PROGRAM_SECRET', ''),

/**

* 小程序登录凭证 code 获取 session_key 和 openid 地址,不需要改动

*/

'code2session_url' => "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",

];

在 Laravel 5 控制器中使用 (示例)

......

use Iwanli\Wxxcx\Wxxcx;

use Iwanli\Wxxcx\WXBizDataCrypt;

{

protected $wxxcx;

function __construct(Wxxcx $wxxcx)

{

$this->wxxcx = $wxxcx;

}

/**

* 小程序登录获取用户信息

*/

public function getWxUserInfo(Request $request)

{

//code 在小程序端使用 wx.login 获取

$code = $request->get('code');

//encryptedData 和 iv 在小程序端使用 wx.getUserInfo 获取

$encryptedData = $request->get('encryptedData');

$iv = $request->get('iv');

// 根据 code 获取用户 openid, session_key

$loginInfo = $this->wxxcx->getLoginInfo($code);

// 获取解密后的用户信息

$userInfo = $this->wxxcx->getUserInfo($encryptedData, $iv);

return $userInfo;

}

......

}

用户信息返回格式:

{ "openId": "xxxx", "nickName": "统天科技", "gender": 1, "language": "zh_CN", "city": "", "province": "GuangZhou", "country": "CN", "avatarUrl": "http://wx.qlogo.cn/mmopen/xxxx", "watermark": { "timestamp": 1495867603, "appid": "your appid" }}

小程序端获取 code、iv、encryptedData 向服务端发送请求示例代码:

//调用登录接口

wx.login({ success: function (response) { var code = response.code wx.getUserInfo({ success: function (resp) { wx.request({ url: 'your domain', data: { code: code, iv: resp.iv, encryptedData: resp.encryptedData }, success: function (res) { console.log(res.data) } }) } }) }, fail:function(){ ... }

})