Wechat.php 8.5 KB
Newer Older
G
微信  
gongfuxiang 已提交
1 2 3 4
<?php
// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
D
devil_gong 已提交
5
// | Copyright (c) 2011~2019 http://shopxo.net All rights reserved.
G
微信  
gongfuxiang 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------
namespace base;

/**
 * 微信驱动
 * @author   Devil
 * @blog    http://gong.gg/
 * @version 1.0.0
 * @date    2018-06-28
 * @desc    支持所有文件存储到硬盘
 */
class Wechat
{
    // appid
    private $_appid;

    // appsecret
    private $_appsecret;

    /**
     * [__construct 构造方法]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2017-12-30T18:04:05+0800
     * @param   [string]     $app_id         [应用appid]
     * @param   [string]     $app_secret     [应用密钥]
     */
    public function __construct($app_id, $app_secret)
    {
        $this->_appid       = $app_id;
        $this->_appsecret   = $app_secret;
    }

    /**
     * [DecryptData 检验数据的真实性,并且获取解密后的明文]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2017-12-30T18:20:53+0800
     * @param    [string]  $encrypted_data     [加密的用户数据]
     * @param    [string]  $iv                 [与用户数据一同返回的初始向量]
     * @param    [string]  $openid             [解密后的原文]
     * @return   [array|string]                [成功返回用户信息数组, 失败返回错误信息]
     */
    public function DecryptData($encrypted_data, $iv, $openid)
    {
        // 登录授权session
        $login_key = 'wechat_user_login_'.$openid;
D
devil 已提交
59
        $session_data = cache($login_key);
D
devil 已提交
60
        if(empty($session_data))
G
微信  
gongfuxiang 已提交
61 62 63
        {
            return 'session key不存在';
        }
D
devil_gong 已提交
64 65

        // iv长度
G
微信  
gongfuxiang 已提交
66 67 68 69
        if(strlen($iv) != 24)
        {
            return 'iv长度错误';
        }
D
devil_gong 已提交
70 71 72 73 74 75

        // 加密函数
        if(!function_exists('openssl_decrypt'))
        {
            return 'openssl不支持';
        }
G
微信  
gongfuxiang 已提交
76

D
devil_gong 已提交
77
        $result = openssl_decrypt(base64_decode($encrypted_data), "AES-128-CBC", base64_decode($session_data['session_key']), 1, base64_decode($iv));
G
微信  
gongfuxiang 已提交
78 79 80
        $data = json_decode($result, true);
        if($data == NULL)
        {
D
devil_gong 已提交
81
            return '请重试!';
G
微信  
gongfuxiang 已提交
82
        }
D
devil_gong 已提交
83
        if($data['watermark']['appid'] != $this->_appid)
G
微信  
gongfuxiang 已提交
84 85 86 87 88 89
        {
            return 'appid不匹配';
        }

        // 缓存存储
        $data_key = 'wechat_user_info_'.$openid;
D
devil 已提交
90
        cache($data_key, $data);
G
微信  
gongfuxiang 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

        return $data;
    }

    /**
     * [GetAuthSessionKey 根据授权code获取 session_key 和 openid]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2017-12-30T18:20:53+0800
     * @param    [string]     $authcode       [用户授权码]
     * @return   [string|boolean]             [失败false, 成功返回appid|]
     */
    public function GetAuthSessionKey($authcode)
    {
        // 请求获取session_key
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->_appid.'&secret='.$this->_appsecret.'&js_code='.$authcode.'&grant_type=authorization_code';
        $result = $this->HttpRequestGet($url);
        if(!empty($result['openid']))
        {
D
devil_gong 已提交
111
            // 缓存SessionKey
G
微信  
gongfuxiang 已提交
112 113 114
            $key = 'wechat_user_login_'.$result['openid'];

            // 缓存存储
D
devil 已提交
115
            cache($key, $result);
G
微信  
gongfuxiang 已提交
116 117 118 119 120 121 122 123 124 125 126
            return $result['openid'];
        }
        return false;
    }

    /**
     * [MiniQrCodeCreate 二维码创建]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2018-01-02T19:53:10+0800
D
devil 已提交
127 128 129
     * @param    [string]  $params['page']      [页面地址]
     * @param    [string]  $params['scene']     [参数]
     * @return   [string]                       [成功返回文件流, 失败则空]
G
微信  
gongfuxiang 已提交
130 131 132
     */
    public function MiniQrCodeCreate($params)
    {
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        // 请求参数
        $p = [
            [
                'checked_type'      => 'empty',
                'key_name'          => 'page',
                'error_msg'         => 'page地址不能为空',
            ],
            [
                'checked_type'      => 'length',
                'checked_data'      => '1,32',
                'key_name'          => 'scene',
                'error_msg'         => 'scene参数 1~32 个字符之间',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if($ret !== true)
G
微信  
gongfuxiang 已提交
149
        {
150
            return DataReturn($ret, -1);
G
微信  
gongfuxiang 已提交
151 152 153 154 155 156
        }

        // 获取access_token
        $access_token = $this->GetMiniAccessToken();
        if($access_token === false)
        {
157
            return DataReturn('access_token获取失败', -1);
G
微信  
gongfuxiang 已提交
158 159
        }

160 161
        // 获取二维码
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
G
微信  
gongfuxiang 已提交
162
        $data = [
163 164 165
            'page'  => $params['page'],
            'scene' => $params['scene'],
            'width' => empty($params['width']) ? 1000 : intval($params['width']),
G
微信  
gongfuxiang 已提交
166
        ];
167 168 169 170 171 172 173 174 175 176 177 178 179
        $res = $this->HttpRequestPost($url, json_encode($data), false);
        if(!empty($res))
        {
            if(stripos($res, 'errcode') === false)
            {
                return DataReturn('获取成功', 0, $res);
            }
            $res = json_decode($res, true);
            $msg = isset($res['errmsg']) ? $res['errmsg'] : '获取二维码失败';
        } else {
            $msg = '获取二维码失败';
        }
        return DataReturn($msg, -1);
G
微信  
gongfuxiang 已提交
180 181 182 183 184 185 186 187 188
    }

    /**
     * [GetMiniAccessToken 获取access_token]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2018-01-02T19:53:42+0800
     */
D
devil 已提交
189
    public function GetMiniAccessToken()
G
微信  
gongfuxiang 已提交
190 191 192
    {
        // 缓存key
        $key = $this->_appid.'_access_token';
D
devil 已提交
193
        $result = cache($key);
D
devil 已提交
194
        if(!empty($result))
G
微信  
gongfuxiang 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208
        {
            if($result['expires_in'] > time())
            {
                return $result['access_token'];
            }
        }

        // 网络请求
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->_appid.'&secret='.$this->_appsecret;
        $result = $this->HttpRequestGet($url);
        if(!empty($result['access_token']))
        {
            // 缓存存储
            $result['expires_in'] += time();
D
devil 已提交
209
            cache($key, $result);
G
微信  
gongfuxiang 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
            return $result['access_token'];
        }
        return false;
    }

    /**
     * [HttpRequestGet get请求]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2018-01-03T19:21:38+0800
     * @param    [string]           $url [url地址]
     * @return   [array]                 [返回数据]
     */
    private function HttpRequestGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);
        return json_decode($res, true);
    }

    /**
     * [HttpRequestPost curl模拟post]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2017-09-25T09:10:46+0800
     * @param    [string]   $url        [请求地址]
     * @param    [array]    $data       [发送的post数据]
     * @param    [array]    $is_parsing [是否需要解析数据]
     * @return   [array]                [返回的数据]
     */
    private function HttpRequestPost($url, $data, $is_parsing = true)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_POST, true);

        $res = curl_exec($curl);
        if($is_parsing === true)
        {
D
devil 已提交
263
            return json_decode($res, true);
G
微信  
gongfuxiang 已提交
264 265 266 267 268 269
        }
        return $res;
    }

}
?>