curl等公共函数方法在文章的最后
Wxbizdatacrypt.php
/**
* 对微信小程序用户加密数据的解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
namespace app\api\controller;
use app\api\controller\Base;
use think\Model;
use think\Db;
use think\Cache;
include_once "ErrorCode.php";
class Wxbizdatacrypt
{
private $appid;
private $sessionKey;
/**
* 构造函数
* @param $sessionKey string 用户在小程序登录后获取的会话密钥
* @param $appid string 小程序的appid
*/
public function __construct( $appid, $sessionKey)
{
$this->sessionKey = $sessionKey;
$this->appid = $appid;
}
/**
* 检验数据的真实性,并且获取解密后的明文.
* @param $encryptedData string 加密的用户数据
* @param $iv string 与用户数据一同返回的初始向量
* @param $data string 解密后的原文
*
* @return int 成功0,失败返回对应的错误码
*/
public function decryptData( $encryptedData, $iv, &$data )
{
if (strlen($this->sessionKey) != 24) {
return ErrorCode::$IllegalAesKey;
}
$aesKey=base64_decode($this->sessionKey);
if (strlen($iv) != 24) {
return ErrorCode::$IllegalIv;
}
$aesIV=base64_decode($iv);
$aesCipher=base64_decode($encryptedData);
$result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
$dataObj=json_decode( $result );
if( $dataObj == NULL )
{
return ErrorCode::$IllegalBuffer;
}
if( $dataObj->watermark->appid != $this->appid )
{
return ErrorCode::$IllegalBuffer;
}
$data = $result;
return ErrorCode::$OK;
}
}
ErrorCode.php
<?php
namespace app\api\controller;
use app\api\controller\Base;
use think\Model;
use think\Db;
use think\Cache;
/**
* error code 说明.
* <ul>
* <li>-41001: encodingAesKey 非法</li>
* <li>-41003: aes 解密失败</li>
* <li>-41004: 解密后得到的buffer非法</li>
* <li>-41005: base64加密失败</li>
* <li>-41016: base64解密失败</li>
* </ul>
*/
class ErrorCode
{
public static $OK = 0;
public static $IllegalAesKey = -41001;
public static $IllegalIv = -41002;
public static $IllegalBuffer = -41003;
public static $DecodeBase64Error = -41004;
}
?>
本来以为php7.0 mcrypt禁用后 解码会有问题 后来发现官直接用官网给的demo 没发现有啥问题
下面这个图是获取token
下面是请求代码里小程序login返回的结果 第一个图为携带参数 这些参数在调用小程序 getuserinfo 里可以得到
第二个图为返回结果 里面结果是自定义的 为了返回给前端用
tp5的一段代码写的比较烂 返回值很随意 微信小程序登录代码如下 后端php代码如下
<?php
namespace app\api\controller;
use app\api\controller\Base;
use think\Model;
use think\Db;
use think\Cache;
//这个不需要继承
class Login
{
protected $code;
protected $wxLoginUrl;
protected $wxAppID;
protected $wxAppSecret;
protected $salt;
public function __construct()
{
$this->wxAppID = config('app_id');
$this->wxAppSecret = config('app_secret');
}
//生成token
public function getcode()
{
$code = input("post.code");
if(!$code)
{