access_token = !empty($merchant) ? self::getAuthorizerAccessToken($merchant) : ''; } //获取用户基本信息 public static function userInfo($openId, $merchant, $isOpen = 0) { $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$accessToken&openid=$openId"; $curl = new curl\Curl(); $result = $curl->get($url); $result = Json::decode($result); Yii::info('get user Info' . json_encode($result)); if (isset($result['errcode']) == false) { $result['nickName'] = isset($result['nickname']) ? $result['nickname'] : ''; return $result; } return []; } //创建开放平台帐号 public static function createOpenAccount($appId, $merchant, $isOpen = 0) { $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/cgi-bin/open/create?access_token=" . $accessToken; $curl = new curl\Curl(); $data = ['appid' => $appId]; $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } //绑定到开放平台 public static function bindOpenAccount($appId, $openAppId, $merchant, $isMiniProgram, $isOpen = 0) { if ($isMiniProgram) { $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen); } else { $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen); } $url = 'https://api.weixin.qq.com/cgi-bin/open/bind?access_token=' . $accessToken; $curl = new curl\Curl(); $data = ['appid' => $appId, 'open_appid' => $openAppId]; $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } //获取公众号、小程序绑定的开放平台帐号 public static function getOpenAccount($appId, $merchant, $isMiniProgram, $isOpen = 0) { if ($isMiniProgram) { $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen); } else { $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen); } Yii::info('获取access token:' . $accessToken); $url = "https://api.weixin.qq.com/cgi-bin/open/get?access_token=" . $accessToken; $curl = new curl\Curl(); $data = ['appid' => $appId]; $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } //解绑公众号绑定的平台 ssh 2019.9.15 public static function unbindAccount($merchant, $isOpen = 0) { $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/cgi-bin/open/unbind?access_token=" . $accessToken; $curl = new curl\Curl(); $openAppId = $merchant['openAppId']; $appId = $merchant['wxAppId']; $data = ['appid' => $appId, 'open_appid' => $openAppId]; $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } //解绑小程序绑定的平台 ssh 2019.9.15 public static function unbindMiniProgram($merchant, $isOpen = 0) { $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/cgi-bin/open/unbind?access_token=" . $accessToken; $curl = new curl\Curl(); $openAppId = $merchant['openAppId']; $appId = $merchant['miniAppId']; $data = ['appid' => $appId, 'open_appid' => $openAppId]; $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } public static function getSubscribeUserList($merchant, $nextOpenId = '') { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$accessToken&next_openid=$nextOpenId"; $curl = new curl\Curl(); $result = $curl->get($url); return Json::decode($result); } public static function batchGetUserInfo($merchant, $openIdList) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" . $accessToken; $format = []; foreach ($openIdList as $val) { $format[] = ['openid' => $val, 'lang' => "zh-CN"]; } $newOpenIdList = ["user_list" => $format]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($newOpenIdList))->post($url); $result = Json::decode($result); return $result; } //查询所有分组 public static function groupList($accessToken) { $url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=$accessToken"; $curl = new curl\Curl(); $result = $curl->get($url); $result = Json::decode($result); if (isset($result['errcode'])) { return null; } else { return $result; } } /** * 提交自定义菜单到微信平台 */ public static function userMenuToWeiXin($menu, $merchant, $isOpen) { $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen); $jsonData = urldecode(json_encode($menu, JSON_UNESCAPED_UNICODE)); $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $accessToken; $curl = new curl\Curl(); $response = $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url); return $response; } /** * 上传图片多媒体文件 */ public static function uploadImgMedia($merchant, $fullFile) { $access_token = self::getAuthorizerAccessToken($merchant); $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" . $access_token . "&type=image"; $curl = curl_init(); if (class_exists('\CURLFile')) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件 $data = array('media' => new \CURLFile($fullFile)); } else { $data = array('media' => file_get_contents($fullFile)); } if (class_exists('\CURLFile')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); } else { if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false); } } curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); $result = curl_exec($curl); curl_close($curl); return json_decode($result); } /** * 上传视频文件 */ public function uploadVideoMedia($merchant, $fullFile) { $access_token = self::getAuthorizerAccessToken($merchant); $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" . $access_token . "&type=video"; $curl = curl_init(); if (class_exists('\CURLFile')) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件 $data = array('media' => new \CURLFile($fullFile)); } else { $data = array('media' => file_get_contents($fullFile)); } if (class_exists('\CURLFile')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); } else { if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false); } } curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); $result = curl_exec($curl); curl_close($curl); return json_decode($result); } /** * 下载多媒体文件 */ public static function uploadMedia($media_id, $access_token) { $url = 'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=' . $access_token . '&media_id=' . $media_id; $result = CurlUtil::httpsGet($url); if (isset($result['errcode'])) { return false; } else { return $result; } } /** * 获取素材总数 * 图片和图文消息素材(包括单图文和多图文)的总数上限为5000,其他素材的总数上限为1000 */ public function getMaterialCount($merchant) { $token = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token={$token}"; $curl = new curl\Curl(); $response = $curl->get($url); return $response; } /** * 获取素材列表 图文列表 * $data = ['type' => 'image','offset' => 0,'count' => 100]; * type:news image video voice */ public function batchgetMaterial($merchant, $data) { $token = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={$token}"; $curl = new curl\Curl(); $response = $curl->setOption(CURLOPT_POSTFIELDS, json_encode($data))->post($url); return json_decode($response, true); } /** * 解除绑定删除自定义菜单 */ public static function menuDelete($merchant) { $token = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=$token"; $curl = new curl\Curl(); $response = $curl->get($url); return $response; } //微信api不支持中文转义的json结构 static function json_encode($arr) { if (count($arr) == 0) return "[]"; $parts = array(); $is_list = false; //Find out if the given array is a numerical array $keys = array_keys($arr); $max_length = count($arr) - 1; if (($keys [0] === 0) && ($keys [$max_length] === $max_length)) { //See if the first key is 0 and last key is length - 1 $is_list = true; for ($i = 0; $i < count($keys); $i++) { //See if each key correspondes to its position if ($i != $keys [$i]) { //A key fails at position check. $is_list = false; //It is an associative array. break; } } } foreach ($arr as $key => $value) { if (is_array($value)) { //Custom handling for arrays if ($is_list) $parts [] = self::json_encode($value); /* :RECURSION: */ else $parts [] = '"' . $key . '":' . self::json_encode($value); /* :RECURSION: */ } else { $str = ''; if (!$is_list) $str = '"' . $key . '":'; //Custom handling for multiple data types if (!is_string($value) && is_numeric($value) && $value < 2000000000) $str .= $value; //Numbers elseif ($value === false) $str .= 'false'; //The booleans elseif ($value === true) $str .= 'true'; else $str .= '"' . addslashes($value) . '"'; //All other things $parts [] = $str; } } $json = implode(',', $parts); if ($is_list) return '[' . $json . ']'; //Return numerical JSON return '{' . $json . '}'; //Return associative JSON } /** * 创建临时二维码 ssh 2019.9.4 */ public static function qrcodeCreate($merchant, $sceneId, $expireSeconds = null) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$accessToken"; //有效期默认一天 $expireSeconds = isset($expireSeconds) ? $expireSeconds : 86400; $post = array('expire_seconds' => $expireSeconds, 'action_name' => 'QR_STR_SCENE', "action_info" => array('scene' => array('scene_str' => $sceneId))); $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } /** * 创建永久二维码 */ public static function qrcodePermanentCreate($merchant, $sceneId) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$accessToken"; $post = array('action_name' => 'QR_LIMIT_STR_SCENE', "action_info" => array('scene' => array('scene_str' => $sceneId))); $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } /** * 微信授权获取code */ public static function getCode($urlEncode, $merchant, $scope, $isOpen = 1) { $host = Yii::$app->request->getHostInfo(); $REDIRECT_URI = $host . '/auth/get-user-info?url=' . $urlEncode . '&authScope=' . $scope; Yii::info($REDIRECT_URI); $appId = $merchant['wxAppId']; $open = []; if ($isOpen == 1) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]); } if ($isOpen == 2) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]); } if ($isOpen == 3) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]); } if (empty($open)) { util::fail('没有找到平台'); } $component_app_id = $open['appId']; $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appId . "&redirect_uri=" . urlencode($REDIRECT_URI) . "&response_type=code&scope=" . $scope . "&state=1&component_appid={$component_app_id}#wechat_redirect"; header("Location:" . $url); //如果这里没有exit(),在apache服务器下无法实现跳转 exit(); } /** * 获取openId */ public static function getOpenId($code, $merchant, $isOpen = 1) { $appId = $merchant['wxAppId']; $open = []; if ($isOpen == 1) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]); } if ($isOpen == 2) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]); } if ($isOpen == 3) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]); } if (empty($open)) { util::fail('没有找到平台'); } $component_app_id = $open['appId']; $componentAccessToken = wxUtil::getComponentAccessToken($open); $url = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid={$appId}&code={$code}&grant_type=authorization_code&component_appid={$component_app_id}&component_access_token={$componentAccessToken}"; $curl = new curl\Curl(); $result = $curl->get($url); $data = Json::decode($result); if (isset($data['openid']) == false) { Yii::warning('error:' . json_encode($data) . ' code:' . $code, __METHOD__); return false; } return $data; } /** * 授权获取自己的信息 */ public function authGetUserInfo($openid, $access_token) { $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid"; $curl = new curl\Curl(); $result = $curl->get($url); $data = Json::decode($result); $data['nickName'] = isset($data['nickname']) ? $data['nickname'] : ''; return $data; } /** * 自动获取自己的信息(公众号的粉丝才能获取) */ public static function autoGetUserInfo($openid, $merchant) { $access_token = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN"; $curl = new curl\Curl(); $result = $curl->get($url); $data = Json::decode($result); return $data; } /** * 网址接入验证 */ public static function signatureValidation() { $signature = $_GET['signature']; $timestamp = $_GET['timestamp']; $nonce = $_GET['nonce']; $account = $_GET['account']; $merchant = xhMerchantService::getByAccount($account); if ($merchant) { $token = $merchant['wxToken']; // 3个数值组成数组验证 $tmpArr = array( $token, $timestamp, $nonce ); // 字典排序 sort($tmpArr, SORT_STRING); $tmpStr = implode($tmpArr); // sha1加密 $tmpStr = sha1($tmpStr); if ($signature == $tmpStr) { return true; } else { return false; } } else { return false; } } //客服接口发消息 public static function sendMiniMsg($content, $merchant, $openId, $isOpen = 0) { $token = self::getAuthorizerAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}"; $data = ['touser' => $openId, 'msgtype' => 'text', 'text' => ['content' => $content]]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } //客服接口发消息 public static function sendMsg($content, $merchant, $openId, $isOpen = 0) { $token = self::getAuthorizerAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}"; $data = ['touser' => $openId, 'msgtype' => 'text', 'text' => ['content' => $content]]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } public static function sendImgMsg($mediaId, $merchant, $openId) { $token = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}"; $data = ['touser' => $openId, 'msgtype' => 'image', 'image' => ['media_id' => $mediaId]]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } public static function sendVideoMsg($mediaId, $merchant, $openId) { $token = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$token}"; $data = ['touser' => $openId, 'msgtype' => 'video', 'video' => ['media_id' => $mediaId, 'thumb_media_id' => $mediaId, 'title' => '因爱而生', 'description' => "情定原生,爱在今生;\n坐标:浙江,绍兴上虞;\n看到过一句话:“一个城市不过是几条巷道上,几间房子和几个人的组合。如果没有了这些,一个城市如同陨落,只剩下悲凉的记忆;”\n万事万物持续流变,珍爱的东西尤其不可能一直存在,如朝霞,如春花,如爱情;\n无论什么时候,不管天气好坏,都能拿出某些个让人喜欢的东西。", ]]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } /** * 消息模板,发送任务通知 */ public static function sendTaskInform($data, $merchant, $isOpen = 0) { $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}"; $data = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE)); $curl = new curl\Curl(); $response = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url); Yii::info('发送模板消息返回:' . $response); $arr = json_decode($response); return $arr; } public static function sendTaskInform2($data, $merchant, $isOpen = 0) { $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}"; $data = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE)); $curl = new curl\Curl(); $response = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url); Yii::info('发送模板消息返回:' . $response); $arr = json_decode($response); return $arr; } /** * 创建模板消息 */ public static function tMessageCreate($merchant, $shortTemplateId, $isOpen = 0) { $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={$accessToken}"; $post = array('template_id_short' => $shortTemplateId); $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } /** * 删除模板消息 */ public static function delTMessage($merchant, $templateId, $isOpen) { $accessToken = self::getAuthorizerAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token={$accessToken}"; $post = array('template_id' => $templateId); $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } /** * 取所有模板消息 */ public function getAllTMessage($merchant) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={$accessToken}"; $curl = new curl\Curl(); $result = $curl->get($url); $result = Json::decode($result); return $result; } /** * 设置模板消息的行业 */ public function setTMIndustry($merchant, $industry_id1, $industry_id2) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token={$accessToken}"; $post = array('industry_id1' => $industry_id1, 'industry_id2' => $industry_id2); $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } /** * 获取公众号的accessToken 公众号调用凭据 */ public static function getAuthorizerAccessToken($merchant, $isOpen = 0) { $sjId = $merchant['id']; $open = []; if ($isOpen == 1) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]); } if ($isOpen == 2) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]); } if ($isOpen == 3) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]); } if (empty($open)) { util::fail('没有找到平台信息'); } $component_app_id = $open['appId']; $componentAccessToken = wxUtil::getComponentAccessToken($open); $appId = $merchant['wxAppId']; $wxAccessToken = $merchant['wxAccessToken']; $wxAccessTokenTime = $merchant['wxAccessTokenTime']; $authorize_refresh_token = $merchant['wxRefreshToken']; $now = time(); if ($now > strtotime($wxAccessTokenTime)) { $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$componentAccessToken}"; $data = ['component_appid' => $component_app_id, 'authorizer_appid' => $appId, 'authorizer_refresh_token' => $authorize_refresh_token]; $curl = new curl\Curl(); $curl->setOption(CURLOPT_SSL_VERIFYPEER, false); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); Yii::info('通过refresh_token获取access_token返回:' . $result); $result = Json::decode($result); if (isset($result['authorizer_access_token'])) { $wxAccessToken = $result['authorizer_access_token']; $expires_in = $result['expires_in']; $authorize_refresh_token = $result['authorizer_refresh_token']; $uData['wxRefreshToken'] = $authorize_refresh_token;; $uData['wxAccessToken'] = $wxAccessToken; $uData['wxAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100)); if (in_array($isOpen, [1, 2, 3])) { //零售、供货商和商城 $wxBaseId = $open['wxBaseId'] ?? 0; if (!empty($wxBaseId)) { WxBaseService::updateById($wxBaseId, $uData); } } else { //其它 xhMerchantService::updateById($sjId, $uData); } } else { noticeUtil::push("access_token已经失效,并且通过refresh_token没有获取到新的token isOpen:{$isOpen}。返回:" . json_encode($result), '15280215347'); } } Yii::info('获取componentAccessToken 成功:' . $componentAccessToken); return $wxAccessToken; } /** * 获取小程序的accessToken */ public static function getMiniProgramAccessToken($merchant, $isOpen = 0) { $sjId = isset($merchant['id']) ? $merchant['id'] : 0; $open = []; if ($isOpen == 1) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]); } elseif ($isOpen == 2) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]); } elseif ($isOpen == 3) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]); } else { util::fail('没有找到平台'); } $component_app_id = $open['appId']; $componentAccessToken = wxUtil::getComponentAccessToken($open); $appId = $merchant['miniAppId']; if ($isOpen == 1) { $miniAccessToken = $merchant['miniAccessToken']; $miniAccessTokenTime = $merchant['miniAccessTokenTime']; $miniRefreshToken = $merchant['miniRefreshToken']; } elseif ($isOpen == 2) { $miniAccessToken = $merchant['miniAccessToken']; $miniAccessTokenTime = $merchant['miniAccessTokenTime']; $miniRefreshToken = $merchant['miniRefreshToken']; } elseif ($isOpen == 3) { $miniAccessToken = $merchant['miniAccessToken']; $miniAccessTokenTime = $merchant['miniAccessTokenTime']; $miniRefreshToken = $merchant['miniRefreshToken']; } else { $extend = xhMerchantExtendService::getBySjId($sjId); $miniAccessToken = $extend['miniAccessToken']; $miniAccessTokenTime = $extend['miniAccessTokenTime']; $miniRefreshToken = $extend['miniRefreshToken']; } $now = time(); Yii::info("当前时间:{$now} 小程序accessToken过期时间:" . strtotime($miniAccessTokenTime) . " merchant:" . json_encode($merchant)); if ($now > strtotime($miniAccessTokenTime)) { $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$componentAccessToken}"; $data = ['component_appid' => $component_app_id, 'authorizer_appid' => $appId, 'authorizer_refresh_token' => $miniRefreshToken]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); Yii::info('重新获取mini accesstoken:' . json_encode($result)); if (isset($result['authorizer_access_token'])) { $expires_in = $result['expires_in']; $miniAccessToken = $result['authorizer_access_token']; $uData['miniRefreshToken'] = $result['authorizer_refresh_token']; $uData['miniAccessToken'] = $miniAccessToken; $uData['miniAccessTokenTime'] = date("Y-m-d H:i:s", (time() + $expires_in - 100)); if ($isOpen == 1) { $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0; if (!empty($wxMiniBaseId)) { WxMiniBaseService::updateById($wxMiniBaseId, $uData); } } elseif ($isOpen == 2) { $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0; if (!empty($wxMiniBaseId)) { WxMiniBaseService::updateById($wxMiniBaseId, $uData); } } elseif ($isOpen == 3) { $wxMiniBaseId = isset($open['wxMiniBaseId']) ? $open['wxMiniBaseId'] : 0; if (!empty($wxMiniBaseId)) { WxMiniBaseService::updateById($wxMiniBaseId, $uData); } } else { xhMerchantExtendService::updateBySjId($sjId, $uData); } return $miniAccessToken; } Yii::info('accessToken失效:sjId:' . $sjId); } Yii::info('有效小程序 accesstoken:' . $miniAccessToken); return $miniAccessToken; } public static function saveWeixinImg($userId, $url, $class = 0) { $className = [ '0' => 'weixinUserAvatar',//微信头像 '1' => 'weixinUserImg',//微信公众号二维码 '2' => 'weixinMpQrcode', '3' => 'weixinMpAvatar', ]; $folder = Yii::getAlias('@webroot') . '/../../images'; $pre = '/' . $className[$class] . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/'; if (!file_exists($folder . $pre)) mkdir($folder . $pre, 0777, true); $randString = stringUtil::buildOrderNo(); $name = md5($userId . $randString) . '.jpg'; $fullFileName = $folder . $pre . $name; $fileName = $pre . $name; $curl = new curl\Curl(); $result = $curl->get($url); $fp2 = @fopen($fullFileName, 'a');//文件大小 fwrite($fp2, $result); fclose($fp2); return $fileName; } /** * 下载学员作品图片 */ public static function downloadStudentWorksImg($merchant, $mediaId, $savePathType = 'wxUserImg') { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id={$mediaId}"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出。 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $body = curl_exec($ch); $httpinfo = curl_getinfo($ch); curl_close($ch); preg_match('/\w\/(\w+)/i', $httpinfo["content_type"], $extmatches);//求出文件格式 $fileExt = $extmatches[1]; $imgSavePath = dict::getDict('imgSavePath'); $comImgSavePath = $imgSavePath[$savePathType]; $folder = Yii::getAlias('@webroot') . '/../../images'; $pre = '/' . $comImgSavePath . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/'; if (!file_exists($folder . $pre)) { mkdir($folder . $pre, 0777, true); } $randString = stringUtil::buildOrderNo(); $fullFileName = $folder . $pre . $randString . '.jpg'; $fileName = $pre . $randString . '.jpg'; $fp2 = @fopen($fullFileName, 'a');//文件大小 fwrite($fp2, $body); fclose($fp2); $srcImg = $fullFileName; $dstImg300 = $folder . $pre . $randString . "_300.jpg";//生成300px缩略图,不保存到数据库 util::img2thumb($srcImg, $dstImg300, $width = 300, 0, 0, 0); $dstImg100 = $folder . $pre . $randString . "_100.jpg";//生成50px缩略图,不保存到数据库 util::img2thumb($srcImg, $dstImg100, $width = 100, 0, 0, 0); return $fileName; } /** * 获取media_id里的图片保存到服务器 */ public static function downloadmediaIdImg($merchant, $mediaId, $savePathType = 'wxUserImg') { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id={$mediaId}"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出。 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $body = curl_exec($ch); $httpinfo = curl_getinfo($ch); curl_close($ch); preg_match('/\w\/(\w+)/i', $httpinfo["content_type"], $extmatches);//求出文件格式 $fileExt = $extmatches[1]; $imgSavePath = dict::getDict('imgSavePath'); $comImgSavePath = $imgSavePath[$savePathType]; $folder = Yii::getAlias('@webroot') . '/../../images'; $pre = '/' . $comImgSavePath . '/' . date('Y') . '/' . date('m') . '/' . date("d") . '/'; if (!file_exists($folder . $pre)) { mkdir($folder . $pre, 0777, true); } $randString = stringUtil::buildOrderNo(); $fullFileName = $folder . $pre . $randString . '.jpg'; $fileName = $pre . $randString . '.jpg'; $fp2 = @fopen($fullFileName, 'a');//文件大小 fwrite($fp2, $body); fclose($fp2); $srcImg = $fullFileName; $mediumImg = $pre . $randString . "_200.jpg"; $dstImg200 = $folder . $mediumImg;//生成200px缩略图,不保存到数据库 util::img2thumb($srcImg, $dstImg200, $width = 200, 0, 0, 0); $smallImg = $pre . $randString . "_50.jpg"; $dstImg50 = $folder . $smallImg;//生成50px缩略图,不保存到数据库 util::img2thumb($srcImg, $dstImg50, $width = 50, 0, 0, 0); return ['large' => $fileName, 'medium' => $mediumImg, 'small' => $smallImg]; } public static function createTag($merchant, $name) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token={$accessToken}"; $post = ['tag' => ['name' => $name]]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } public static function delTag($merchant, $id) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token={$accessToken}"; $post = ['tag' => ['id' => $id]]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } public static function modTag($merchant, $id, $name) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token={$accessToken}"; $post = ['tag' => ['id' => $id, 'name' => $name]]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } /** * 获取商家所有标签 */ public static function getTag($merchant) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token={$accessToken}"; $curl = new curl\Curl(); $result = $curl->get($url); $result = Json::decode($result); return $result; } public function getUserTag($tagId, $nextOpenId = '') { $url = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=" . $this->access_token; $post = ['tagid' => $tagId, 'next_openid' => $nextOpenId]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } /** * 批量为用户打标签 */ public static function membersBatchTag($merchant, $openIdList, $tagId) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={$accessToken}"; $post = ['openid_list' => $openIdList, 'tagid' => $tagId]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } /** * 批量取消用户标签 */ public static function membersCancelTag($merchant, $openIdList, $tagId) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token={$accessToken}"; $post = ['openid_list' => $openIdList, 'tagid' => $tagId]; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($post))->post($url); $result = Json::decode($result); return $result; } /** * 新增临时素材 */ public static function uploadTempMedia($merchant, $imgUrl, $type = 'image') { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$accessToken}&type=" . $type; $postData = ['media' => '@' . $imgUrl]; $ch = curl_init(); curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); $result = Json::decode($response); return $result; } /** * 获取临时素材 */ public static function getTempMaterial($merchant, $mediaId) { $accessToken = self::getAuthorizerAccessToken($merchant); $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id=" . $mediaId; $fileInfo = self::getTempMaterialInfo($url); if (empty($fileInfo) || isset($fileInfo['errcode'])) { $msg = '未错误哦~'; return ['code' => 'A0002', 'msg' => $msg]; } $fileName = substr(md5($mediaId), -4) . stringUtil::buildOrderNo() . '.amr'; $preFolder = Yii::getAlias('@webroot') . '/../../images'; $folder = '/weixinChatVoice/' . date('Y') . '/' . date('m') . '/' . date("d") . '/'; if (!file_exists($preFolder . $folder)) mkdir($preFolder . $folder, 0777, true); $saveFile = $preFolder . $folder . $fileName; if (file_exists($saveFile) == false) { self::readTempMaterial($saveFile, $fileInfo["body"]); } return ['code' => 'A0001', 'msg' => 'success', 'data' => ['url' => $folder . $fileName]]; } /** * 获取临时素材的头信息等 */ public static function getTempMaterialInfo($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_NOBODY, 0);//只取body头 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $package = curl_exec($ch); $httpinfo = curl_getinfo($ch); curl_close($ch); $imageAll = ['header' => $httpinfo, 'body' => $package]; return $imageAll; } /** * 读取临时素材的资源 */ function readTempMaterial($filename, $fileContent) { $localFile = fopen($filename, 'w'); if (false !== $localFile) { if (false !== fwrite($localFile, $fileContent)) { fclose($localFile); } } } /** * 创建门店 */ public function createStore($info) { $jsonData = urldecode(json_encode($info, JSON_UNESCAPED_UNICODE)); $url = "http://api.weixin.qq.com/cgi-bin/poi/addpoi?access_token=" . $this->access_token; $curl = new curl\Curl(); return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url); } /** * 查询门店信息 */ public function getStoreInfo($poi_id) { $data = ['poi_id' => $poi_id]; $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE)); $url = "http://api.weixin.qq.com/cgi-bin/poi/getpoi?access_token=" . $this->access_token; $curl = new curl\Curl(); return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url); } /** * 查询门店列表 */ public function getStoreList($begin = 0, $count = 20) { $data = ["begin" => $begin, "limit" => $count]; $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE)); $url = "http://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=" . $this->access_token; $curl = new curl\Curl(); return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url); } /** * 查询门店列表 -- 重复 可删除 */ function getShopList($data) { $url = "https://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=" . $this->access_token; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } /** * 修改门店服务信息 */ public function updateStore(array $buffer) { $jsonData = urldecode(json_encode($buffer, JSON_UNESCAPED_UNICODE)); $url = "http://api.weixin.qq.com/cgi-bin/poi/updatepoi?access_token=" . $this->access_token; $curl = new curl\Curl(); return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url); } /** * 删除门店 */ public function delStore($poi_id) { $data = ['poi_id' => $poi_id]; $jsonData = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE)); $url = "http://api.weixin.qq.com/cgi-bin/poi/delpoi?access_token=" . $this->access_token; $curl = new curl\Curl(); return $curl->setOption(CURLOPT_POSTFIELDS, $jsonData)->post($url); } /** * 门店类目表 */ public function storeTypeList() { $url = "http://api.weixin.qq.com/cgi-bin/poi/getwxcategory?access_token=" . $this->access_token; $curl = new curl\Curl(); return $curl->get($url); } /******************************* wifi *************************************/ /** * 获取wifi门店列表 */ function getShopWifiList($pageindex = 1, $pagesize = 10) { $data = ["pageindex" => $pageindex, "pagesize" => $pagesize]; $url = "https://api.weixin.qq.com/bizwifi/shop/list?access_token=" . $this->access_token; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } /** * 添加密码型设备 */ function addPasswordDevice($shopId, $ssid, $pwd) { $data = ["shop_id" => $shopId, "ssid" => $ssid, "password" => $pwd]; $url = "https://api.weixin.qq.com/bizwifi/device/add?access_token=" . $this->access_token; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } /** * 修改门店Wi-Fi(修改门店网络信息) */ function updateDevice($shopId, $oldSsid, $ssid, $pwd = '') { $data = ["shop_id" => $shopId, "old_ssid" => $oldSsid, "ssid" => $ssid]; if (!empty($pwd)) { $data["password"] = $pwd; } $url = "https://api.weixin.qq.com/bizwifi/shop/update?access_token=" . $this->access_token; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } /** * 删除密码型设备 */ function delPasswordDevice($bssid) { $data = ["bssid" => $bssid]; $url = "https://api.weixin.qq.com/bizwifi/device/delete?access_token=" . $this->access_token; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } /** * 查询门店Wi-Fi信息 */ function getShopWifi($shopId) { $data = ["shop_id" => $shopId]; $url = "https://api.weixin.qq.com/bizwifi/shop/get?access_token=" . $this->access_token; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } /** * 获取物料二维码 */ function getWifiQrCode($shopId, $ssid, $img_id) { //$data = ["shop_id" => 429620, "ssid" => "WX567", "img_id" => $img_id]; $data = ["shop_id" => $shopId, "ssid" => $ssid, "img_id" => $img_id]; $url = "https://api.weixin.qq.com/bizwifi/qrcode/get?access_token=" . $this->access_token; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); return $result; } function getWifiUrl() { $url = "https://api.weixin.qq.com/bizwifi/account/get_connecturl?access_token=" . $this->access_token; $curl = new curl\Curl(); $result = $curl->get($url); $result = Json::decode($result); return $result; } function generateShortUrl($longUrl) { $data = ["action" => "long2short", "long_url" => $longUrl,]; $url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" . $this->access_token; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); if (isset($result['errcode']) && $result['errcode'] == 0) { return ['code' => 'A0001', 'data' => ['shortUrl' => $result['short_url']]]; } return ['code' => 'A0002', 'data' => []]; } //长链接转短链接 ssh 2019.9.26 public static function urlLongToShort($longUrl, $merchant) { $accessToken = self::getMiniProgramAccessToken($merchant); $data = ["action" => "long2short", "long_url" => $longUrl,]; $url = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" . $accessToken; $curl = new curl\Curl(); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $result = Json::decode($result); $url = ''; if (isset($result['errcode']) && $result['errcode'] == 0) { $url = $result['short_url']; } return ['url' => $url]; } /** * 拉取门店所有的设备信息 */ public function getShopWifiListAll() { $startPage = 1; $list = []; while (true) { $reList = $this->getShopWifiList($startPage, 20); if ($startPage <= $reList['data']['pagecount']) { $list = array_merge($list, $reList['data']['records']); ++$startPage; } else { break; } } return $list; } /** * 通过 poi_id 从Wi-Fi门店列表中 获取 shopId */ public function getShopId($poiId, $list = []) { if (empty($list)) { $list = $this->getShopWifiListAll(); } foreach ($list as $shop) { if ($shop['poi_id'] == $poiId) return (string)$shop['shop_id']; } return false; } //设置小程序服务器域名 public static function setDomain($merchant, $isOpen = 0) { $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/wxa/modify_domain?access_token=" . $accessToken; $curl = new curl\Curl(); //零售 $currentHost = Yii::$app->params['hdHost']; $imgHost = Yii::$app->params['hdImgHost']; if ($isOpen == 2) { //供货商 $currentHost = Yii::$app->params['ghsHost']; $imgHost = Yii::$app->params['ghsImgHost']; } if ($isOpen == 3) { //供货商 $currentHost = Yii::$app->params['mallHost']; $imgHost = Yii::$app->params['mallImgHost']; } //api地址 //如果不是https则换成https $has = strpos($currentHost, 'https'); if ($has === false) { $currentHost = str_replace('http', 'https', $currentHost); } //图片地址 $imgHas = strpos($imgHost, 'https'); if ($imgHas === false) { $imgHost = str_replace('http', 'https', $imgHost); } $imgHost = rtrim($imgHost, '/'); $socket = str_replace("https", "", $currentHost); $socket = str_replace("http", "", $socket); $data = [ "action" => "set", "requestdomain" => [$currentHost, $imgHost], "wsrequestdomain" => ['wss' . $socket], "uploaddomain" => [$currentHost, $imgHost], "downloaddomain" => [$currentHost, $imgHost], ]; print_r($data); $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $respond = Json::decode($result); print_r($respond); } //设置业务域名 public static function setWebViewDomain($merchant, $isOpen = 0) { $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen); $url = "https://api.weixin.qq.com/wxa/setwebviewdomain?access_token=" . $accessToken; $curl = new curl\Curl(); //零售 $currentHost = Yii::$app->params['hdHost']; if ($isOpen == 2) { //供货商 $currentHost = Yii::$app->params['ghsHost']; } if ($isOpen == 3) { //供货商 $currentHost = Yii::$app->params['mallHost']; } $has = strpos($currentHost, 'https'); //如果不是https则换成https if ($has === false) { $currentHost = str_replace('http', 'https', $currentHost); } $data = [ "action" => "set", "webviewdomain" => [$currentHost], ]; $result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url); $respond = Json::decode($result); print_r($respond); } //为授权的小程序帐号上传小程序代码 public static function miniCommit($merchant, $templateId, $isOpen = 0) { $accessToken = self::getMiniProgramAccessToken($merchant, $isOpen); $url = 'https://api.weixin.qq.com/wxa/commit?access_token=' . $accessToken; $curl = new curl\Curl(); $apiUrl = Yii::$app->params['mallHost']; if ($isOpen == 1) { $apiUrl = Yii::$app->params['hdHost']; } elseif ($isOpen == 2) { $apiUrl = Yii::$app->params['ghsHost']; } elseif ($isOpen == 3) { $apiUrl = Yii::$app->params['mallHost']; } $imgUrl = imgUtil::getPrefix(); //如果不是https则换成https $has = strpos($apiUrl, 'https'); if ($has === false) { $apiUrl = str_replace('http', 'https', $apiUrl); } $open = []; if ($isOpen == 1) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'hd')]); } if ($isOpen == 2) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'ghs')]); } if ($isOpen == 3) { $open = \biz\wx\classes\WxOpenClass::getByCondition(['style' => dict::getDict('ptStyle', 'mall')]); } if (empty($open)) { util::fail('没有找到平台'); } //如果不是https则换成https $has = strpos($imgUrl, 'https'); if ($has === false) { $imgUrl = str_replace('http', 'https', $imgUrl); } $account = isset($merchant['id']) ? $merchant['id'] : 0; $name = isset($merchant['name']) ? $merchant['name'] : ''; if ($isOpen == 1) { $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0; $wxBase = WxBaseClass::getById($wxBaseId); $name = isset($wxBase['name']) ? $wxBase['name'] : ''; } elseif ($isOpen == 2) { $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0; $wxBase = WxBaseClass::getById($wxBaseId); $name = isset($wxBase['name']) ? $wxBase['name'] : ''; } elseif ($isOpen == 3) { $wxBaseId = isset($open['wxBaseId']) ? $open['wxBaseId'] : 0; $wxBase = WxBaseClass::getById($wxBaseId); $name = isset($wxBase['name']) ? $wxBase['name'] : ''; } $ext = [ 'extAppid' => $merchant['miniAppId'], 'ext' => [ 'account' => $account, 'apiHost' => $apiUrl, 'socketApiHost' => str_replace("https://", "", $apiUrl), 'imgHost' => $imgUrl, 'name' => $name, ], ]; echo '
';
print_r($ext);
Yii::info("ext:" . json_encode($ext));
$extJson = json_encode($ext);
$data = [
"template_id" => $templateId,
"ext_json" => $extJson,
"user_version" => date("mdHis"),
"user_desc" => date("mdHis")
];
print_r($data);
$result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
$respond = Json::decode($result);
print_r($respond);
}
//获取体验小程序的体验二维码
public static function getExperienceQrCode($merchant, $page, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$sjId = $merchant['id'] ?? 0;
$middle = $sjId . '_' . $isOpen;
if (getenv('YII_ENV', 'local') == 'production') {
$middle .= '_production';
}
$path = urlencode($page);
$url = "https://api.weixin.qq.com/wxa/get_qrcode?access_token={$accessToken}&path=" . $path;
$curl = new curl\Curl();
$result = $curl->get($url);
$file = dirUtil::getImgDir() . 'retail/miniExperience/' . $middle . '.jpg';
file_put_contents($file, $result);
$obj = 'retail/miniExperience/' . $middle . '.jpg';
//上传oss
oss::uploadImage($obj, $file);
echo "
";
}
//获取授权小程序帐号已设置的类目
public static function getMiniCategory($merchant, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/get_category?access_token=" . $accessToken;
$curl = new curl\Curl();
$result = $curl->get($url);
$respond = Json::decode($result);
echo "";
print_r($respond);
}
//小程序加急审核 ssh 2020.4.20
public static function speedupAudit($merchant, $auditId, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/speedupaudit?access_token=" . $accessToken;
$curl = new curl\Curl();
$data = [
"auditid" => $auditId
];
$result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
$respond = Json::decode($result);
return $respond;
}
//获取小程序的第三方提交代码的页面配置
public static function getMiniPage($merchant, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/get_page?access_token=" . $accessToken;
$curl = new curl\Curl();
$result = $curl->get($url);
$respond = Json::decode($result);
echo "";
print_r($respond);
}
//将第三方提交的代码包提交审核
public static function miniSubmitAudit($merchant, $page, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/submit_audit?access_token=" . $accessToken;
$curl = new curl\Curl();
$data = [
"item_list" => [
[
"address" => $page,
"tag" => "花卉宝 花店",
"first_class" => "IT科技",
"second_class" => "软件服务提供商",
"first_id" => 210,
"second_id" => 413,
"title" => "花卉宝",
],
],
"feedback_info" => "",
"feedback_stuff" => "",
"version_desc" => "体验帐号:15280215347 密码:a.1234 。线上环境,小心操作哦,谢谢 ^_^",
];
$result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
$respond = Json::decode($result);
return $respond;
}
//查询最新一次提交的审核状态
public static function miniGetLatestAuditStatus($merchant, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=" . $accessToken;
$curl = new curl\Curl();
$result = $curl->get($url);
$respond = Json::decode($result);
echo "";
print_r($respond);
}
//发布已通过审核的小程序
public static function miniRelease($merchant, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/release?access_token=" . $accessToken;
$curl = new curl\Curl();
$result = $curl->setOption(CURLOPT_POSTFIELDS, '{}')->post($url);
$respond = Json::decode($result);
return $respond;
}
//撤回审核
public static function rollbackCheck($merchant, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/undocodeaudit?access_token=" . $accessToken;
$curl = new curl\Curl();
$result = $curl->get($url);
$respond = Json::decode($result);
echo "";
print_r($respond);
}
//回滚到上一个版本
public static function revertCodeRelease($merchant, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/revertcoderelease?access_token=" . $accessToken;
$curl = new curl\Curl();
$result = $curl->get($url);
$respond = Json::decode($result);
echo "";
print_r($respond);
}
//查询服务商的当月提审限额(quota)和加急次数
public static function queryQuota($merchant, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/queryquota?access_token=" . $accessToken;
$curl = new curl\Curl();
$result = $curl->get($url);
$respond = Json::decode($result);
echo "";
print_r($respond);
}
//申请会员的小程序码
public static function generateMemberCode($merchant, $shopId, $isOpen = 0)
{
$fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
$behind = 'retail/mimiMemberCode/';
$filePath = dirUtil::getImgDir() . $behind;
if (!file_exists($filePath)) {
mkdir($filePath, 0777, true);
}
$file = $filePath . $fileName;
if (file_exists($file)) {
return $behind . $fileName;
}
$path = 'pages/home/user?scan=1&shopId=' . $shopId;
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
$curl = new curl\Curl();
$data = [
"path" => $path,
"width" => 1000,
];
$result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
file_put_contents($file, $result);
return $behind . $fileName;
}
//隐私协议设置 ssh 20211213
//接口说明 https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/privacy_config/set_privacy_setting.html
public static function privacySetting($merchant, $isOpen = 0)
{
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/cgi-bin/component/setprivacysetting?access_token={$accessToken}";
$curl = new curl\Curl();
$data = [
"owner_setting" => [
"contact_email" => "479439056@qq.com",
"notice_method" => "弹窗",
],
"setting_list" => [
[
"privacy_key" => "UserInfo",
"privacy_text" => "用户通过帐号密码登录后台时,授权用户信息,以便下次实现自动登录后台,无需输入帐号密码"
],
[
"privacy_key" => "Location",
"privacy_text" => "查看客户订单时,可以直接通过定位进行导航"
],
[
"privacy_key" => "PhoneNumber",
"privacy_text" => "登录时,如果忘记密码,可以通过授权手机号进行登录"
],
[
"privacy_key" => "Album",
"privacy_text" => "门店管理时,方便上传和管理花材图片"
],
[
"privacy_key" => "Camera",
"privacy_text" => "门店管理时,以便通过拍照上传和管理花材图片"
],
[
"privacy_key" => "Record",
"privacy_text" => "联系下游客户时,方便与客户沟通"
],
[
"privacy_key" => "AlbumWriteOnly",
"privacy_text" => "门店管理时,方便上传花材图片"
],
[
"privacy_key" => "BlueTooth",
"privacy_text" => "门店管理时,方便通过蓝牙打印条形码"
],
],
"privacy_ver" => 2,
];
$result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
$respond = Json::decode($result);
echo "";
print_r($respond);echo '隐私设置OK';
}
//收款小程序码
public static function generateGatheringMiniCode($merchant, $shopId, $isOpen = 0)
{
$fileName = $merchant['id'] . '_' . $shopId . '_apply_member.jpg';
$behind = 'retail/gatheringMimiCode/';
$filePath = dirUtil::getImgDir() . $behind;
if (!file_exists($filePath)) {
mkdir($filePath, 0777, true);
}
$file = $filePath . $fileName;
if (file_exists($file)) {
return $behind . $fileName;
}
$path = 'pages/pay/index?scan=1&shopId=' . $shopId;
$accessToken = self::getMiniProgramAccessToken($merchant, $isOpen);
$url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
$curl = new curl\Curl();
$data = [
"path" => $path,
"width" => 1000,
];
$result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
file_put_contents($file, $result);
return $behind . $fileName;
}
//微信开放平台获取component_access_token
public static function getComponentAccessToken($open)
{
$id = $open['id'];
$componentAccessToken = $open['componentAccessToken'];
$componentAccessTokenTime = $open['componentAccessTokenTime'];
$now = time();
if ($now > strtotime($componentAccessTokenTime)) {
$appId = $open['appId'];
$appSecret = $open['appSecret'];
$verifyTicket = $open['verifyTicket'];
$data = ['component_appid' => $appId, 'component_appsecret' => $appSecret, 'component_verify_ticket' => $verifyTicket];
$url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
$curl = new curl\Curl();
$curl->setOption(CURLOPT_SSL_VERIFYPEER, false);
$result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
if (empty($result)) {
util::stop('没有取到ComponentAccessToken');
}
$result = Json::decode($result);
if (isset($result['component_access_token']) == false || empty($result['component_access_token'])) {
echo '';
print_r($result);
Yii::info('get component access token error:' . json_encode($result));
Yii::$app->end();
}
$component_access_token = $result['component_access_token'];
$expiresIn = $result['expires_in'];
$oData = [];
$oData['componentAccessToken'] = $component_access_token;
$oData['componentAccessTokenTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短
xhWxOpenService::updateById($id, $oData);
return $component_access_token;
} else {
return $componentAccessToken;
}
}
/**
* 微信开放平台获取预授权码pre_auth_code
*/
public static function getPreAuthCode($open)
{
$id = $open['id'];
$preAuthCode = $open['preAuthCode'];
$preAuthCodeTime = $open['preAuthCodeTime'];
$now = time();
if ($now > strtotime($preAuthCodeTime)) {
$token = self::getComponentAccessToken($open);
$appId = $open['appId'];
$url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
$curl = new curl\Curl();
$data = ['component_appid' => $appId];
$result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
$result = Json::decode($result);
Yii::info($result);
if (isset($result['pre_auth_code']) == false || empty($result['pre_auth_code'])) {
echo "没有取到pre_auth_code,原因:" . json_encode($result) . " appid:" . $appId . " token:" . $token;
Yii::$app->end();
}
$preAuthCode = $result['pre_auth_code'];
$expiresIn = $result['expires_in'];
$oData = [];
$oData['preAuthCode'] = $preAuthCode;
$oData['preAuthCodeTime'] = date("Y-m-d H:i:s", ($now + $expiresIn - 100));//安全起见,将过期时间设置得比微信里还短100秒
xhWxOpenService::updateById($id, $oData);
return $preAuthCode;
} else {
return $preAuthCode;
}
}
/**
* 微信开放平台使用授权码换取公众号的接口调用凭据和授权信息
*/
public static function getAuthorizer($code, $open)
{
$appId = $open['appId'];
$accessToken = self::getComponentAccessToken($open);
$url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token={$accessToken}";
$curl = new curl\Curl();
$data = ['authorization_code' => $code, 'component_appid' => $appId];
$result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
$result = Json::decode($result);
return $result;
}
//微信开放平台获取授权方的公众号帐号基本信息 ssh 2020.3.11
public static function getAuthorizerInfo($authorizeAppId, $open)
{
$appId = $open['appId'];
$accessToken = self::getComponentAccessToken($open);
$url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token={$accessToken}";
$curl = new curl\Curl();
$data = ['component_appid' => $appId, 'authorizer_appid' => $authorizeAppId];
$result = $curl->setOption(CURLOPT_POSTFIELDS, Json::encode($data))->post($url);
$result = Json::decode($result);
return $result;
}
}