params['w'] . '/wx-open/callback';
$merchantId = $open['merchantId'];
//如果平台没有对应的商家,先去创建第一个商家并做关联
if (empty($merchantId)) {
$url = Yii::$app->params['w'] . '/wx-open/callback-create-first-merchant';
}
echo "授权";
}
public function actionCheckMerchantName()
{
$get = Yii::$app->request->get();
$merchantName = isset($get['merchantName']) ? $get['merchantName'] : '';
$m = xhMerchantService::getByMerchantName($merchantName);
if (!empty($m)) {
util::failInfo('公众号名称已经使用');
}
util::successInfo();
}
/**
* 下载微信里的图片到服务器
*/
public function actionDownloadWxImg()
{
$get = Yii::$app->request->get();
$mediaId = isset($get['mediaId']) ? $get['mediaId'] : '';
$imgList = weixinUtil::downloadmediaIdImg($this->merchant, $mediaId);
if (!empty($imgList)) {
util::successInfo('操作成功', 'A0001', $imgList);
}
util::failInfo();
}
/**
* 创建第一个商家
*/
public function actionCallbackCreateFirstMerchant()
{
$get = Yii::$app->request->get();
if (isset($get['auth_code']) == false) {
util::stop('公众号授权回调未成功');
}
$code = $get['auth_code'];
//使用授权码换取公众号的接口调用凭据和授权信息
$authorize = weixinUtil::getAuthorizer($code);
if (isset($authorize['authorization_info']) == false) {
util::stop('未换取公众号的接口调用凭据和授权信息');
}
$info = $authorize['authorization_info'];
$authorizeAppId = $info['authorizer_appid'];
$authorize_access_token = $info['authorizer_access_token'];
$expires_in = $info['expires_in'];//7200
$authorize_refresh_token = $info['authorizer_refresh_token'];
//获取授权方的公众号帐号基本信息
$authorizeDetailInfo = weixinUtil::getAuthorizerInfo($authorizeAppId);
if (isset($authorizeDetailInfo['authorizer_info']) == false) {
util::stop('没有获取到公众号帐号基本信息');
}
$authorize_info = $authorizeDetailInfo['authorizer_info'];
$nick_name = $authorize_info['nick_name'];
$head_img = $authorize_info['head_img'];
$service_type_info = $authorize_info['service_type_info'];
if ($service_type_info['id'] != 2) {
util::stop('公众号不是服务号');
}
$verify_type_info = $authorize_info['verify_type_info'];
if ($verify_type_info['id'] != 0) {
util::stop('公众号还没有认证哦');
}
$user_name = $authorize_info['user_name'];
$alias = $authorize_info['alias'];
$qrCodeUrl = $authorize_info['qrcode_url'];
$business_info = $authorize_info['business_info'];
$open_pay = $business_info['open_pay'];
$merchant = xhMerchantService::getByAppId($authorizeAppId);
$wxAccessTokenTime = date("Y-m-d H:i:s", (time() + $expires_in - 100));//安全起见,将过期时间设置得比微信里还短100秒
if (!empty($merchant)) {
util::stop('此公众号已经授权过了');
}
//引导生成商家
$date = date("Y-m-d H:i:s");
$trainDemo = configDict::getConfig('trainDemo');
//$logo = xhMerchantService::logoSave($head_img, $authorizeAppId);
$logo = '';
$appData['logo'] = $logo;
//保存公众号二维码
//$wxQrCodeUrl = xhMerchantService::qrCodeSave($qrCodeUrl, $authorizeAppId);
$wxQrCodeUrl = '';
$appData['wxQrcodeUrl'] = $wxQrCodeUrl;
$appData['wxAppId'] = $authorizeAppId;
$appData['wxUserName'] = $user_name;
$appData['wxAliasName'] = $alias;
$appData['wxAccessToken'] = $authorize_access_token;
$appData['wxAccessTokenTime'] = $wxAccessTokenTime;
$appData['wxRefreshToken'] = $authorize_refresh_token;
$appData['accountStyle'] = 0;//认证服务号
$appData['status'] = 0;//待审核
$appData['createTime'] = $date;
$appData['updateTime'] = $date;
$appData['shopLat'] = (string)0;
$appData['shopLong'] = (string)0;
$appData['shopPrecision'] = (string)0;
$appData['account'] = $trainDemo['platform']['account'];
$appData['adminId'] = 0;
$appData['wxToken'] = stringUtil::buildWxToken(0);
$appData['shopPhotoList'] = '';
$appData['merchantName'] = $nick_name;
$appData['shopProvince'] = '福建';
$appData['shopCity'] = '厦门';
$appData['shopDist'] = '思明区';
$appData['alipayAccount'] = 'shishaohua8879@sina.com';
$appData['alipayAccountName'] = '石少华';
$appData['agentLevel'] = 1;//默认设置为代理商
$merchant = xhMerchantService::applyCreateMerchant($appData);
$wxOpenId = configDict::getConfig('openId');
$merchantId = $merchant['id'];
$account = $merchant['id'];
$createTime = date("Y-m-d H:i:s");
$orderId = 'A' . stringUtil::buildOrderNo();
$orderData = ['id' => $orderId, 'userId' => 0, 'applyName' => $nick_name, 'email' => '',
'createTime' => $createTime, 'accountId' => 0, 'inviteCode' => '', 'merchantId' => $merchantId, 'invitedMerchantId' => $merchantId,
'prePrice' => 0, 'actPrice' => 0, 'deadline' => time() + 2592000, 'inviteCodeStatus' => 0, 'payStatus' => 1,
];
xhWxOpenService::updateById($wxOpenId, ['merchantId' => $merchantId]);
//xhApplyOrderService::add($orderData);//保存订单信息
//xhWxMenuService::applyInit($merchant);//初始化微信菜单
//$openMerchant = xhWxOpenService::getMerchant();
//$openMerchantAccount = $openMerchant['id'];
//将新生成的商家account加密传到后台绑定管理员,密钥有效期5分钟
//$newAccount = urlencode(stringUtil::authcode($account, 'ENCODE', 300));
echo 'ok';
}
public function actionCallback()
{
$get = Yii::$app->request->get();
if (isset($get['auth_code']) == false) {
util::stop('公众号授权回调未成功');
}
$code = $get['auth_code'];
//使用授权码换取公众号的接口调用凭据和授权信息
$authorize = weixinUtil::getAuthorizer($code);
if (isset($authorize['authorization_info']) == false) {
util::stop('未换取公众号的接口调用凭据和授权信息');
}
$info = $authorize['authorization_info'];
$authorizeAppId = $info['authorizer_appid'];
$authorize_access_token = $info['authorizer_access_token'];
$expires_in = $info['expires_in'];//7200
$authorize_refresh_token = $info['authorizer_refresh_token'];
//获取授权方的基本信息
$authorizeDetailInfo = weixinUtil::getAuthorizerInfo($authorizeAppId);
if (isset($authorizeDetailInfo['authorizer_info']) == false) {
util::stop('没有获取到公众号帐号基本信息');
}
$authorize_info = $authorizeDetailInfo['authorizer_info'];
$nick_name = $authorize_info['nick_name'];
$head_img = $authorize_info['head_img'];
$service_type_info = $authorize_info['service_type_info'];
if ($service_type_info['id'] != 2) {
util::stop('公众号不是服务号,appId:' . $authorizeAppId . ' refresh:' . $authorize_refresh_token);
}
$verify_type_info = $authorize_info['verify_type_info'];
if ($verify_type_info['id'] != 0) {
util::stop('公众号还没有认证哦');
}
$user_name = $authorize_info['user_name'];
$alias = $authorize_info['alias'];
$qrCodeUrl = $authorize_info['qrcode_url'];
$business_info = $authorize_info['business_info'];
$open_pay = $business_info['open_pay'];
$accessTokenTime = date("Y-m-d H:i:s", (time() + $expires_in - 100));//安全起见,将过期时间设置得比微信里还短100秒
//小程序
if (isset($authorize_info['MiniProgramInfo']) && !empty($authorize_info['MiniProgramInfo'])) {
$merchant = xhMerchantService::getByCondition(['miniAppId' => $authorizeAppId]);
if (empty($merchant)) {
Yii::info('没有小程序信息 appId:' . $authorizeAppId);
util::stop('没有小程序信息 appId:' . $authorizeAppId);
}
$merchantId = $merchant['id'];
xhMerchantExtendService::updateByMerchantId($merchantId, ['miniAccessToken' => $authorize_access_token, 'miniAccessTokenTime' => $accessTokenTime, 'miniRefreshToken' => $authorize_refresh_token]);
Yii::info('小程序信息更新成功:' . json_encode($authorize_info));
util::stop("小程序信息更新成功");
} else {
$merchant = xhMerchantService::getByAppId($authorizeAppId);
Yii::info('appId:' . $authorizeAppId);
$set = xhSetMealService::getRandOne();
if (empty($set)) {
util::stop('没有套餐信息');
}
if (empty($merchant)) {
util::stop('这个商家没有生成过基本信息。appid:' . $authorizeAppId);
}
if (empty($merchant)) {
echo '新建商家能力暂时关闭';
Yii::$app->end();
//没有生成商家,引导进去设置
$session = Yii::$app->session;
$session['wxAppId'] = $authorizeAppId;
$session['wxUserName'] = $user_name;
$session['wxAliasName'] = $alias;
$session['wxAccessToken'] = $authorize_access_token;
$session['wxAccessTokenTime'] = $accessTokenTime;
$session['wxRefreshToken'] = $authorize_refresh_token;
$session['logo'] = $head_img;
$session['wxQrcodeUrl'] = $qrCodeUrl;
$session['allowGenerateMerchant'] = 'ok';//经过授权流程,允许允许生成商家
$trainDemo = configDict::getConfig('trainDemo');
$demoName = $trainDemo['merchant']['name'];//培训演示的公众号
return $this->renderPartial('callback', ['merchantName' => $nick_name, 'set' => $set, 'demoName' => $demoName]);
}
$cData = [];
$cData['wxAccessToken'] = $authorize_access_token;
$cData['wxAccessTokenTime'] = $accessTokenTime;
$cData['wxRefreshToken'] = $authorize_refresh_token;
//审核通过
$cData['status'] = 1;
$merchantId = $merchant['id'];
xhMerchantService::updateById($merchantId, $cData);
}
echo $authorizeAppId . ' ';
exit('ok');
$price = $set['price'];
$now = time();
$apply = xhApplyOrderService::getByMerchantId($merchantId);
if (empty($apply)) {
return $this->renderPartial('hint', ['msg' => '没有申请记录']);
}
$orderId = $apply['id'];
$price = $apply['actPrice'];
$openMerchant = xhWxOpenService::getMerchant();
$openMerchantAccount = $openMerchant['id'];
$account = $merchant['id'];
//将新生成的商家account加密传到后台绑定管理员,密钥有效期5分钟
$newAccount = urlencode(stringUtil::authcode($account, 'ENCODE', 300));
if ($apply['payStatus'] == 1) {
if (empty($merchant['adminId'])) {
$this->redirect(Yii::$app->params['adminUrl'] . '/admin/generate?account=' . $openMerchantAccount . '&newAccount=' . $newAccount);
util::end();
}
return $this->renderPartial('hint', ['msg' => '恭喜!您已申请成功。']);
}
if ($price > 0) {
$this->redirect(Yii::$app->params['openUrl'] . '/pay/apply?orderId=' . $apply['id']);
util::end();
} else {
$inviteCode = $order['inviteCode'];
$now = time();
if (!empty($inviteCode)) {
$invite = xhInviteService::getByCode($inviteCode);
if (empty($invite)) {
return $this->renderPartial('hint', ['msg' => '邀请码不存在']);
}
if ($invite['takeStatus'] == 1) {//邀请码未使用,并且没有过期
return $this->renderPartial('hint', ['msg' => '邀请码已经使用,请联系客服']);
}
$inviteDeadline = $invite['deadline'];
if ($now > $inviteDeadline) {
return $this->renderPartial('hint', ['msg' => '邀请码已经过期,请联系客服']);
}
xhInviteService::updateByCode($inviteCode, ['takeStatus' => 1, 'inviteUseTo' => 0, 'targetId' => $orderId, 'invitedMerchantId' => $merchantId]);
}
$updateData = ['inviteCodeStatus' => 1, 'payStatus' => 1, 'payWay' => 0, 'invitedMerchantId' => $merchantId];
xhApplyOrderService::updateById($orderId, $updateData);
$this->redirect(Yii::$app->params['adminUrl'] . '/admin/generate?account=' . $openMerchantAccount . '&newAccount=' . $newAccount);
util::end();
}
}
public function actionResult()
{
$get = Yii::$app->request->get();
$id = isset($get['id']) ? $get['id'] : 0;
$merchant = xhMerchantService::getById($id);
$status = configDict::getConfig('merchantStatusName');
$orMechantId = configDict::getConfig('merchantId');
$originalMerchant = xhMerchantService::getById($orMechantId);
return $this->renderPartial('result', ['originalMerchant' => $originalMerchant, 'merchant' => $merchant, 'status' => $status]);
}
/**
* 商家申请入驻
*/
public function actionAddMerchant()
{
$post = Yii::$app->request->post();
$session = Yii::$app->session;
if (isset($session['allowGenerateMerchant']) == false) {
//util::failInfo('没有经过授权的操作');
}
unset($post['_csrf']);
if (isset($session['wxAppId']) == false || empty($session['wxAppId'])) {
util::failInfo('公众号appId不存在');
}
$wxAppId = $session['wxAppId'];
if (isset($session['logo'])) {
$logo = xhMerchantService::logoSave($session['logo'], $wxAppId);
$post['logo'] = $logo;
}
if (isset($session['wxQrcodeUrl'])) {
$wxQrCodeUrl = xhMerchantService::qrCodeSave($session['wxQrcodeUrl'], $wxAppId);
$post['wxQrcodeUrl'] = $wxQrCodeUrl;
}
$date = date("Y-m-d H:i:s");
$inviteCode = isset($post['inviteCode']) ? $post['inviteCode'] : '';
$accountStyle = configDict::getConfig('accountStyle');
$merchantStatus = configDict::getConfig('merchantStatus');
$serviceAccount = $accountStyle['serviceAccount'];//认证服务号
$checking = $merchantStatus['checking'];//审核中
$merchantName = !empty($post['merchantName']) ? $post['merchantName'] : '';
$exists = xhMerchantService::getByMerchantName($merchantName);
if (!empty($exists)) {
util::failInfo('花店名称已经存在了');
}
$post['wxAppId'] = $wxAppId;
$post['wxUserName'] = $session['wxUserName'];
$post['wxAliasName'] = $session['wxAliasName'];
$post['wxAccessToken'] = $session['wxAccessToken'];
$post['wxAccessTokenTime'] = $session['wxAccessTokenTime'];
$post['wxRefreshToken'] = $session['wxRefreshToken'];
$post['accountStyle'] = $serviceAccount;//认证服务号
$post['status'] = $checking;//待审
$post['createTime'] = $date;
$post['updateTime'] = $date;
$post['shopLat'] = isset($post['shopLat']) ? (string)$post['shopLat'] : (string)0;
$post['shopLong'] = isset($post['shopLong']) ? (string)$post['shopLong'] : (string)0;
$post['shopPrecision'] = isset($post['shopPrecision']) ? (string)$post['shopPrecision'] : (string)0;
$account = stringUtil::buildOrderNo(0);
$trainDemo = configDict::getConfig('trainDemo');
$demoName = $trainDemo['merchant']['name'];//培训演示的公众号
if (isset($post['merchantName']) && $post['merchantName'] == $demoName) {
$account = $trainDemo['merchant']['account'];
}
$post['account'] = $account;
$post['adminId'] = 0;
$post['wxToken'] = stringUtil::buildWxToken(0);
$shopPhotoListString = json_encode(["outdoor" => $post['shopImg'], 'indoor' => $post['shopImg2']]);//将门店照片组合成json
$post['shopPhotoList'] = $shopPhotoListString;
$merchant = xhMerchantService::applyCreateMerchant($post);
$id = $merchant['id'];
$account = $merchant['id'];
unset($session['allowGenerateMerchant']);
xhWxMenuService::applyInit($merchant);
$set = xhSetMealService::getRandOne();
$price = $set['price'];
$actPrice = $price;
$mainMerchantId = 0;
$now = time();
$orderDeadline = 0;
if (!empty($inviteCode)) {
$invite = xhInviteService::getByCode($inviteCode);
if (empty($invite)) {
util::failInfo('邀请码不存在');
}
if ($invite['takeStatus'] == 1) {//邀请码未使用,并且没有过期
util::failInfo('邀请码已经使用');
}
$inviteDeadline = $invite['deadline'];
if ($now > $inviteDeadline) {
util::failInfo('邀请码已经过期');
}
$mainMerchantId = isset($invite['merchantId']) ? $invite['merchantId'] : 0;
$actPrice = stringUtil::calcSub($set['price'], $invite['save']);//扣除邀请码里的钱
}
$toPay = $actPrice <= 0 ? 'no' : 'yes';//是否需要付款
$inviteCodeStatus = $actPrice <= 0 ? 1 : 0;//邀请码是否已使用
$payStatus = $actPrice <= 0 ? 1 : 0;//付款是否成功
$createTime = date("Y-m-d H:i:s");
$orderId = 'A' . stringUtil::buildOrderNo($id);
$orderData = ['id' => $orderId, 'userId' => $this->userId, 'applyName' => $merchantName, 'email' => '',
'createTime' => $createTime, 'accountId' => 0, 'inviteCode' => $inviteCode, 'merchantId' => $mainMerchantId, 'invitedMerchantId' => $id,
'prePrice' => $price, 'actPrice' => $actPrice, 'deadline' => $orderDeadline, 'inviteCodeStatus' => (int)$inviteCodeStatus, 'payStatus' => $payStatus,
];
xhApplyOrderService::add($orderData);//保存订单信息
if ($actPrice <= 0 && !empty($inviteCode)) {
xhInviteService::updateByCode($inviteCode, ['targetId' => $orderId, 'takeStatus' => 1, 'invitedMerchantId' => $id, 'inviteUseTo' => 0]);
}
$openMerchant = xhWxOpenService::getMerchant();
$openMerchantAccount = $openMerchant['id'];
$newAccount = urlencode(stringUtil::authcode($account, 'ENCODE', 300));
util::successInfo('提交成功', 'A0001', ['account' => $openMerchantAccount, 'newAccount' => $newAccount, 'toPay' => $toPay, 'orderId' => $orderId, 'actPrice' => $actPrice]);
}
public function actionCheckInviteCode()
{
$get = Yii::$app->request->get();
$code = isset($get['code']) ? $get['code'] : '';
$invite = xhInviteService::getByCode($code);
if (empty($invite)) {
util::failInfo('邀请码错误');
}
$now = time();
if ($now > $invite['deadline']) {
util::failInfo('邀请码已经失效');
}
if (!empty($invite['takeStatus'])) {
util::failInfo('邀请码已经使用');
}
util::successInfo('操作成功', 'A0001', $invite);
}
public function actionSelect()
{
$isWeixin = util::isWeixin();
if ($isWeixin == false) {
return $this->renderPartial('notWeixin');
}
return $this->renderPartial('select');
}
public function actionApi()
{
$openData = file_get_contents('php://input');
if (isset ($openData) == false || empty($openData)) {
util::stop('has no post data');
}
$weixinSecret = Yii::getAlias("@vendor/weixinSecret");
require_once($weixinSecret . '/wxBizMsgCrypt.php');
$get = Yii::$app->request->get();
$encryptMsg = $openData;
$openId = configDict::getConfig('openId');
$open = xhWxOpenService::getById($openId);
$encodingAesKey = $open['aesKey'];
$token = $open['token'];
$appId = $open['appId'];
$signature = isset($get['signature']) ? $get['signature'] : '';
$timestamp = isset($get['timestamp']) ? $get['timestamp'] : '';
$nonce = isset($get['nonce']) ? $get['nonce'] : '';
$encrypt_type = isset($get['encrypt_type']) ? $get['encrypt_type'] : '';
$msg_signature = isset($get['msg_signature']) ? $get['msg_signature'] : '';
$xml_tree = new \DOMDocument();
$xml_tree->loadXML($encryptMsg);
$array_e = $xml_tree->getElementsByTagName('Encrypt');
$encrypt = $array_e->item(0)->nodeValue;
$format = "";
$from_xml = sprintf($format, $encrypt);
$formString = '1:' . $token . ' 2:' . $encodingAesKey . ' 3:' . $appId . ' 4:' . $msg_signature . ' 5:' . $timestamp . ' 6:' . $nonce . ' 7:' . $from_xml;
Yii::warning("formString:" . $formString);
//第三方收到公众号平台发送的消息
$pc = new \WXBizMsgCrypt($token, $encodingAesKey, $appId);
$msg = '';//解密后的消息
$errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $from_xml, $msg);
if ($errCode != 0) {
Yii::warning("解密未成功,错误代码:" . $errCode);
Yii::$app->end();
}
$postObj = simplexml_load_string($msg, 'SimpleXMLElement', LIBXML_NOCDATA);
$infoType = $postObj->InfoType;
switch ($infoType) {
//推送 componentVerifyTicket
case 'component_verify_ticket':
$componentVerifyTicket = $postObj->ComponentVerifyTicket;
if (!empty($componentVerifyTicket)) {
$oData = [];
$oData['verifyTicket'] = (string)$componentVerifyTicket;
$oData['verifyTicketTime'] = date("Y-m-d H:i:s", $timestamp + 600);//每10分钟(600秒)推一次
xhWxOpenService::updateById($openId, $oData);
Yii::warning("component_verify_ticket:" . (string)$componentVerifyTicket);
util::stop('success');
}
break;
//取消授权通知
case 'unauthorized':
$AppId = $postObj->AppId;
$authorizeAppid = $postObj->AuthorizerAppid;
$merchant = xhMerchantService::getByAppId($authorizeAppid);
if (!empty($merchant)) {
$merchantId = $merchant['id'];
xhMerchantService::updateById($merchantId, ['status' => 5]);//自主冻结
}
break;
//授权成功通知
case 'authorized':
$AppId = $postObj->AppId;//第三方平台appid
$CreateTime = $postObj->CreateTime;//公众号
$authorizeAppid = $postObj->AuthorizerAppid;//授权码,可用于换取公众号的接口调用凭据,详细见上面的说明
$AuthorizationCode = $postObj->AuthorizationCode;
$AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;//授权码过期时间
break;
//授权更新通知
case 'updateauthorized':
$AppId = $postObj->AppId;
$CreateTime = $postObj->CreateTime;
$authorizeAppid = $postObj->AuthorizerAppid;
$AuthorizationCode = $postObj->AuthorizationCode;
$AuthorizationCodeExpiredTime = $postObj->AuthorizationCodeExpiredTime;
$authorize = weixinUtil::getAuthorizer($AuthorizationCode);
if (isset($authorize['authorization_info']) == false) {
$msg = '授权回调获取到auth_code,但未换取公众号的接口调用凭据和授权信息!!';
Yii::warning($msg, __METHOD__);
Yii::$app->end();
}
$info = $authorize['authorization_info'];
$authorizeAppId = $info['authorizer_appid'];
$authorize_access_token = $info['authorizer_access_token'];
$expires_in = $info['expires_in'];//7200
$authorize_refresh_token = $info['authorizer_refresh_token'];
$merchant = xhMerchantService::getByAppId($authorizeAppId);
if (empty($merchant)) {
return false;
}
$merchantId = $merchant['id'];
$wxData = [];
$wxData['wxAccessToken'] = $authorize_access_token;
$wxData['wxRefreshToken'] = $authorize_refresh_token;
$wxData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100));
$wxData['status'] = 1;
xhMerchantService::updateById($merchantId, $wxData);
break;
default:
}
Yii::warning("---wx open data end--- \n");
}
}