Commit c5046fdb authored by jianghaiming's avatar jianghaiming

update:set

parent f2728bcd
...@@ -19,5 +19,5 @@ class Code ...@@ -19,5 +19,5 @@ class Code
const DISTRIBUTOR = 130000; const DISTRIBUTOR = 130000;
const DISTRIBUTION = 140000; const DISTRIBUTION = 140000;
const MARKETING = 150000; const MARKETING = 150000;
const USUR = 160000;
} }
\ No newline at end of file
<?php
namespace App\Exception\custom;
use App\Exception\BaseException;
class UserException extends BaseException
{
protected $base_code = Code::USUR;
protected $cus = [
0 => 'code 无效',
1 => '获取openid失败',
2 => '登陆失败',
3 => 'encryptedData 不能为空',
4 => 'iv 不能为空',
5 => '用户信息不存在',
6 => '解密失败 不存在',
7 => '手机号获取失败',
8 => '绑定手机号失败',
];
}
\ No newline at end of file
<?php
namespace App\Models\user\mysql;
use Api\PhpUtils\Mysql\MysqlBase;
/**
* Class Shop
* 用户微信绑定
* @package App\Models\goods\mysql
*/
class UserWechatBind extends MysqlBase
{
const TABLE_NAME = 'user_wechat_bind';
const CONFIG_INDEX = 'marketing';
const PRIMARY_KEY = 'wechat_id';
const STATUS_ONLINE = 1;// 上线
const STATUS_OFFLINE = 2;// 下线
public static function getRecord($where, $columns = [])
{
if (empty($columns)) {
$columns = '*';
}
return self::get($columns, $where);
}
public static function getRecordMaster($where, $columns = [])
{
if (empty($columns)) {
$columns = '*';
}
return self::selectMaster($columns, $where);
}
public static function save($data, $where = [])
{
if (empty($where)) {
return self::insert($data);
}
return self::update($data, $where);
}
public static function deleteRecord($where)
{
return self::delete($where);
}
}
\ No newline at end of file
<?php
use App\Base\Base;
use App\Services\user\UserService;
use Api\PhpUtils\Validate\Validate;
use App\Exception\custom\UserException;
use \Validate\CheckIsDistributorValidate;
class UserController extends Base
{
public function wechat_loginAction()
{
$params = $this->params;
$user = UserService::wechatLogin($params);
$userInfo['result'] = $user;
$this->success($userInfo);
}
public function bind_phoneAction()
{
$params = $this->params;
$user = UserService::bindPhone($params);
$userInfo['result'] = $user;
$this->success($userInfo);
}
}
\ No newline at end of file
<?php
namespace App\Services\user;
use App\Models\user\mysql\UserWechatBind;
use Api\PhpUtils\Http\Request;
use App\Services\user\Weixin\WxBizDataCrypt;;
use App\Exception\BaseException;
use App\Exception\custom\UserException;
use Api\PhpUtils\Validate\Validate;
use Api\PhpServices\Idgen\Idgen;
use Api\PhpUtils\Redis\RedisUtil;
use Api\PhpServices\JwUser\JwUser;
class UserService
{
private $code;
private $grant_type = 'authorization_code';
private $loginUrl = 'https://api.weixin.qq.com/sns/jscode2session';
public static function wechatLogin($params)
{
$code = !empty($params['code']) ? $params['code'] : '';//小程序授权code
$openid = !empty($params['openid']) ? $params['openid'] : '';//小程序授权code
if (empty($code) && empty($openid)) {
throw new UserException(['cus' => 0]);
}
//需要授权微信
if (empty($openid)) {
$appid = \Yaf\Registry::get('config')->wechat->appid;
$secret = \Yaf\Registry::get('config')->wechat->secret;
$grant_type = 'authorization_code';
$loginUrl = 'https://api.weixin.qq.com/sns/jscode2session';
//请求接口,获取用户openid
$params = [
'appid' => $appid,
'secret' => $secret,
'js_code' => $code,
'grant_type' => $grant_type,
];
$response = (new Request())->post($loginUrl, $params);
if ($response['code'] == 0) {
$response = $response['response'];
}
if (empty($response) || array_key_exists('errcode', $response)) {
//throw new \Exception('获取openid失败:' . $response['errcode']);
throw new UserException(['cus' => 1]);
}
//检查系统是已注册
$openid = !empty($response['openid']) ? $response['openid'] : '';
}
$user = UserWechatBind::getRecord(['openid' => $openid]);
//如果系统不存在,用户信息,则注册新用户
if (empty($user) && !empty($response)) {
$insert = [
'openid' => $response['openid'],
'session_key' => $response['session_key'], //默认7200有效期
];
$newWechatId = UserWechatBind::save($insert);
if (!$newWechatId) {
throw new UserException(['cus' => 2]);
}
$user['wechat_id'] = $newWechatId;
$user['openid'] = $response['openid'];
$user['session_key'] = $response['session_key'];
}else{
if (empty($user)) {
throw new UserException(['cus' => 2]);
}
}
$user['third_session'] = self::generate3rdSession($openid);
return $user;
}
public static function bindPhone($params)
{
$openid = !empty($params['openid']) ? $params['openid'] : '';
$encryptedData = !empty($params['encryptedData']) ? urldecode($params['encryptedData']) : '';
$iv = !empty($params['iv']) ? urldecode($params['iv']) : '';
$appid = \Yaf\Registry::get('config')->wechat->appid;
if (!$encryptedData) {
throw new UserException(['cus' => 3]);
}
if (!$iv) {
throw new UserException(['cus' => 4]);
}
$userInfo = UserWechatBind::getRecord(['openid' => $openid]);
$sessionKey = !empty($userInfo['session_key']) ? $userInfo['session_key'] : '';
$openid = isset($userInfo['wechat_openid']) && $userInfo['wechat_openid'] ? $userInfo['wechat_openid'] : '';
if (empty($userInfo) || !$sessionKey || !$openid) {
throw new UserException(['cus' => 5]);
}
//解密
$decryptData = [];
$wXBizDataCrypt = new WxBizDataCrypt($appid, $sessionKey);
$errCode = $wXBizDataCrypt->decryptData($encryptedData, $iv, $decryptData);
if ($errCode) {
throw new UserException(['cus' => 6]);
}
// 手机号解密成功
if (empty($decryptData['phoneNumber'])) {
throw new UserException(['cus' => 7]);
}
$phoneNumber = strval($decryptData['phoneNumber']);
$jwUser = (new JwUser ())->getUserInfo(['mobile' => $phoneNumber]);
$userId = '';
if (!empty($jwUser['data'])) {
$data = $jwUser['data'];
$userId = !empty($data['userId']) ? $data['userId'] : '';
}
//进行绑定
$update = [
'phone' => $phoneNumber,
"update_time" => date("Y-m-d H:i:s"),
'user_id' => $userId,
];
$bindStatus = UserWechatBind::save($update,['wechat_id' => $userInfo['wechat_id']]);
if (!$bindStatus) {
throw new UserException(['cus' => 8]);
}
return $userInfo;
}
private static function generate3rdSession($openid) {
return md5(mt_rand() . $openid);
}
}
\ No newline at end of file
<?php
namespace App\Services\user\Weixin;
/**
* 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;
}
?>
\ No newline at end of file
<?php
namespace App\Services\user\Weixin\Weixin;
use App\Libraries\Http;
/**
* Created by PhpStorm.
* User: shixing
* Date: 2018/9/12
* Time: 10:48
*/
class Weixin
{
private $appId;
private $appSecret;
public function __construct()
{
$config = config('weixin');
$this->appId = $config['appid'];
$this->appSecret = $config['secret'];
}
/**
* 获取accessToken
* @return mixed
*/
public function getAccessToken()
{
$appid = $this->appId;
$appsecret = $this->appSecret;
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
$output = $this->curl($url);
$jsoninfo = json_decode($output, true);
$accessToken = $jsoninfo["access_token"];
return $accessToken;
}
/**
* 发送请求
* @param $url
* @param null $data
* @return mixed
*/
public function curl($url,$data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
// $error = curl_error($curl);
return $output;
}
public function getCode()
{
header("content-type:text/html;charset=utf-8");
$code = $_GET["code"];//预定义的 $_GET 变量用于收集来自 method="get" 的表单中的值。
if (isset($_GET['code'])){//判断code是否存在
$userinfo = getUserInfo($code);
$xinxi = $userinfo['nickname'];//获取nickname对应的值,即用户名
}else{
echo "NO CODE";
}
}
public function getUserInfo($code)
{
$appid = "wxa6d4e8d3f4468cfc";
$appsecret = "61d7c6f5cd3c81da729f8e10b57845f7";
// $appid = $this->appId;
// $appsecret = $this->appSecret;
//Get access_token
$access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
$access_token_json = https_request($access_token_url);//自定义函数
$access_token_array = json_decode($access_token_json,true);//对 JSON 格式的字符串进行解码,转换为 PHP 变量,自带函数
//获取access_token
$access_token = $access_token_array['access_token'];//获取access_token对应的值
//获取openid
$openid = $access_token_array['openid'];//获取openid对应的值
//Get user info
$userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
$userinfo_json = https_request($userinfo_url);
$userinfo_array = json_decode($userinfo_json,ture);
return $userinfo_array;
}
}
\ No newline at end of file
<?php
namespace App\Services\user\Weixin;
use App\Services\user\Weixin\ErrorCode;
use Api\PhpUtils\Log\FileLog;
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;
}
FileLog::info("goods_response_data_encryptedData", print_r($encryptedData, 1));//测试使用
FileLog::info("goods_response_data_iv", print_r($iv, 1));//测试使用
$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;//test
}
//$data = $result;
$data = $result ? json_decode($result, true) : $result;
return ErrorCode::$OK;
}
}
<?php
include_once "WxBizDataCrypt.php";
$appid = 'wx4f4bc4dec97d474b';
$sessionKey = 'tiihtNczf5v6AKRyjwEUhQ==';
$encryptedData="CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM
QmRzooG2xrDcvSnxIMXFufNstNGTyaGS
9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+
3hVbJSRgv+4lGOETKUQz6OYStslQ142d
NCuabNPGBzlooOmB231qMM85d2/fV6Ch
evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6
/1Xx1COxFvrc2d7UL/lmHInNlxuacJXw
u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn
/Hz7saL8xz+W//FRAUid1OksQaQx4CMs
8LOddcQhULW4ucetDf96JcR3g0gfRK4P
C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB
6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns
/8wR2SiRS7MNACwTyrGvt9ts8p12PKFd
lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV
oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG
20f0a04COwfneQAGGwd5oa+T8yO5hzuy
Db/XcxxmK01EpqOyuxINew==";
$iv = 'r7BXXKkLb8qrSNn05n0qiA==';
$pc = new WXBizDataCrypt($appid, $sessionKey);
$errCode = $pc->decryptData($encryptedData, $iv, $data );
if ($errCode == 0) {
print($data . "\n");
} else {
print($errCode . "\n");
}
<?php
namespace App\Http\Controllers\User\Weixin;
use App\Http\Controllers\User\Weixin\ErrorCode;
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;
}
requestLog($encryptedData);
requestLog($iv);
requestLog($this->sessionKey);
$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;//test
}
//$data = $result;
$data = $result ? json_decode($result, true) : $result;
return ErrorCode::$OK;
}
}
\ No newline at end of file
...@@ -3,7 +3,7 @@ application.directory = APP_PATH ...@@ -3,7 +3,7 @@ application.directory = APP_PATH
application.bootstrap = APP_PATH "/Bootstrap.php" application.bootstrap = APP_PATH "/Bootstrap.php"
application.library = APP_PATH"/library" application.library = APP_PATH"/library"
application.library.namespace = "" application.library.namespace = ""
application.modules="Index,Test,Goods,Shop,Marketing,Tcc" application.modules="Index,Test,Goods,Shop,Marketing,Tcc,User"
appid = "goods" appid = "goods"
;AES密钥 ;AES密钥
...@@ -16,6 +16,12 @@ aes.switch = true ...@@ -16,6 +16,12 @@ aes.switch = true
idgen.partner = "bp" idgen.partner = "bp"
idgen.key = "5cfdb867e96374c7883b31d6928cc4cb" idgen.key = "5cfdb867e96374c7883b31d6928cc4cb"
wechat.appid = "wx49abba5d05fe49f21111111";
wechat.secret = "701afd9262e034e9ff92a6a44f85362611111111";
[exception] [exception]
debug = false debug = false
exception.user.code = -1 exception.user.code = -1
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment