Laravel 5 微信小程式獲取『使用者資訊』擴充套件
阿新 • • 發佈:2018-12-27
小程式API介面
安裝
執行以下命令安裝最新穩定版本:
composer require iwanli/wxxcx
或者新增如下資訊到你的 composer.json
檔案中 :
"iwanli/wxxcx": "^1.0",
然後註冊服務提供者到 Laravel中 具體位置:/config/app.php
中的 providers
陣列:
Iwanli\Wxxcx\WxxcxServiceProvider::class,
釋出配置檔案:
php artisan vendor:publish --tag=wxxcx
命令完成後,會新增一個wxxcx.php
配置檔案到您的配置資料夾 如 : /config/wxxcx.php
。
生成配置檔案後,將小程式的 AppID
AppSecret
填寫到 /config/wxxcx.php
檔案中在Laravel 5控制器中使用 (示例)
...
use Iwanli\Wxxcx\Wxxcx;
class WxxcxController extends Controller
{
protected $wxxcx;
function __construct(Wxxcx $wxxcx)
{
$this->wxxcx = $wxxcx;
}
/**
* 小程式登入獲取使用者資訊
* @author 晚黎
* @date 2017-05-27T14:37:08+0800
* @return [type] [description]
*/
public function getWxUserInfo()
{
//code 在小程式端使用 wx.login 獲取
$code = request('code', '');
//encryptedData 和 iv 在小程式端使用 wx.getUserInfo 獲取
$encryptedData = request('encryptedData', '');
$iv = request('iv', '');
//根據 code 獲取使用者 session_key 等資訊, 返回使用者openid 和 session_key
$userInfo = $this->wxxcx->getLoginInfo($code);
//獲取解密後的使用者資訊
return $this->wxxcx->getUserInfo($encryptedData, $iv);
}
}
使用者資訊返回格式:
{
"openId": "xxxx",
"nickName": "晚黎",
"gender": 1,
"language": "zh_CN",
"city": "",
"province": "Shanghai",
"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(){
...
}
})
如有bug,請在 Issues 中反饋,非常感謝!