The official encryption and decryption SDK of the mini program is already very clear, but it has been changed to Laravel style, which is just like a bricklayer. As for reinventing the wheel, I found that other people's extensions had code errors when decrypting user information, and there was no mention of the need to install a Laravel Curl extension. I had to write a 0.0 myself based on their source code, without relying on other extensions, just install and use it directly.
The encryption function
mcrypt_module_open()
of PHP7.1 has been abandoned due to obsolescence. People using PHP7.1 version please install version 2.0 code
Execute the following command to install the latest stable version:
PHP < 7.1
composer require iwanli/wxxcx=1. *
PHP > 7.1
composer require iwanli/wxxcx=2. *
Or add the following information to your composer.json
file:
PHP < 7.1
"iwanli/wxxcx" : " ^1.0 "
PHP > 7.1
" iwanli/wxxcx " : " ^2.0 "
Then register the service provider to the specific location in Laravel: providers
array in /config/app.php
:
Iwanli Wxxcx WxxcxServiceProvider::class,
Publish configuration file:
php artisan vendor:publish --tag=wxxcx
After the command is completed, a wxxcx.php
configuration file will be added to your configuration folder such as: /config/wxxcx.php
.
After generating the configuration file, fill in AppID
and AppSecret
of the mini program into the /config/wxxcx.php
file
. . .
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 );
}
}
User information return format:
{
"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"
}
}
//调用登录接口
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 ( ) {
...
}
} )
If there are any bugs, please report them in Issues, thank you very much!