微信登录部分,小程序
HannibalSWX opened this issue · comments
你好,你这个扩展里面不支持小程序登录啊
我看了下微信登录类内部提供的地址和小程序的授权地址是不一样的
小程序不需要这么麻烦
<?php
/**
* Author: Coeus <r.anerg@gmail.com>
* Date: 2019-05-04
* Time: 11:58
*/
namespace App\Http\Controllers\Sns;
use GuzzleHttp\Client;
class MiniProgram
{
/**
* 接口获取微信小程序的session key
*
* @param $name
*
* @return bool|string|null
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function getSessionKey($name)
{
$code = request()->get('code', '');
$configKey = 'sns.' . $name . '.' . config('site.site_code') . '_mp';
$config = config($configKey);
$url = 'https://api.weixin.qq.com/sns/jscode2session';
$params = [
'appid' => $config['app_id'],
'secret' => $config['app_secret'],
'js_code' => $code,
'grant_type' => 'authorization_code'
];
$client = new Client();
$response = $client->request('GET', $url, [ 'query' => $params ]);
$rsp = json_decode($response->getBody()->getContents(), true);
return $rsp ? base64_decode($rsp['session_key']) : NULL;
}
/**
* 获取解密后的数据
*
* @param $key
*
* @return mixed
*/
public function getDecryptData($key)
{
$encryptedData = base64_decode(request()->get('encryptedData'));
$iv = base64_decode(request()->get('iv'));
$data = openssl_decrypt($encryptedData, 'AES-128-CBC', $key, true, $iv);
return json_decode($data, true);
}
/**
* 返回格式化后的用户数据
*
* @param $data
*
* @return array
*/
public function snsUserInfo($data)
{
$userinfo = [
'openid' => $data['openId'],
'unionid' => isset($data['unionId']) ? $data['unionId'] : '',
'channel' => 'weixin_mp',
'nick' => $data['nickName'],
'gender' => $this->getGender($data['gender']),
'avatar' => $data['avatarUrl'],
];
return $userinfo;
}
/**
* 格式化性别
*
* @param string $gender
*
* @return string
*/
private function getGender($gender)
{
$return = NULL;
switch ($gender) {
case 1:
$return = 'm';
break;
case 2:
$return = 'f';
break;
default:
$return = 'n';
}
return $return;
}
}
具体使用,参考我的代码
/**
* 小程序登陆
*
* @param User $UserRepository
* @param MiniProgram $miniProgram
* @param $name
*
* @return json
* @throws GuzzleException
*/
public function handleMpCallback(User $UserRepository, MiniProgram $miniProgram, $name)
{
$key = $miniProgram->getSessionKey($name);
$data = $miniProgram->getDecryptData($key);
if ($data) {
$snsInfo = $miniProgram->snsUserInfo($data);
$user = $UserRepository->fromSns($snsInfo);
$visible = [ 'id', 'nick', 'avatar', 'api_token' ];
return prettyJson([ 'code' => 200, 'data' => $user->setVisible($visible)->toArray() ]);
} else {
return response()->json([ 'error' => 'Can not decrypt data' ], 500);
}
}