Ejemplo n.º 1
0
 /**
  * get sign package
  * @return array
  */
 public function getSignPackage($channelId = null)
 {
     /*
     $channelId = '54d9c155e4b0abe717853ee1';
     if (!empty($channelId)) {
         $sign = Yii::$app->wechatSdk->getSignPackage($channelId);
         return $sign;
     }
     */
     // 注意 URL 一定要动态获取,不能 hardcode.
     $url = $this->refererUrl;
     if (empty($url)) {
         $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://";
         $url = "{$protocol}{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
         $this->refererUrl = $url;
     }
     $jsapiTicket = $this->_getJsApiTicket();
     LogUtil::error(['message' => 'get jsapiTicket with old method', 'jsapiTicket' => $jsapiTicket], 'weixin');
     $timestamp = time();
     $nonceStr = StringUtil::rndString(16, StringUtil::ALL_DIGITS_LETTERS);
     // 这里参数的顺序要按照 key 值 ASCII 码升序排序
     $string = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
     $signature = sha1($string);
     $signPackage = array("appId" => $this->appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "signature" => $signature, "url" => $url);
     LogUtil::error(['message' => 'get signPackage with old method', 'signPackage' => json_encode($signPackage)], 'weixin');
     return $signPackage;
 }
Ejemplo n.º 2
0
 public function actionIndex()
 {
     $conversationId = $this->getQuery('conversationId');
     if (empty($conversationId)) {
         throw new BadRequestHttpException("Missing conversationId");
     }
     $query = ChatMessage::find();
     if ($orderBy = $this->getQuery('orderBy', 'createdAt')) {
         if (StringUtil::isJson($orderBy)) {
             $orderBy = Json::decode($orderBy, true);
             foreach ($orderBy as $key => $value) {
                 if ($value === 'asc' || $value === 'ASC') {
                     $orderBy[$key] = SORT_ASC;
                 } else {
                     $orderBy[$key] = SORT_DESC;
                 }
             }
         } else {
             $orderBy = [$orderBy => SORT_DESC];
         }
         $query->orderBy($orderBy);
     }
     $query->where(['isDeleted' => false, 'conversationId' => new \MongoId($this->getQuery('conversationId'))]);
     return new ActiveDataProvider(['query' => $query]);
 }
Ejemplo n.º 3
0
 /**
  * Create a new user
  *
  * <b>Request Type</b>: POST<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/management/user<br/><br/>
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for billing account to create a new user
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     email: string, the user email, required<br/>
  *     role: string, the user role, required<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     ack: integer, mark the create result, 0 means create successfully, 1 means create fail<br/>
  *     data: array, json array to describe the user created<br/>
  *     <br/><br/>
  *
  * <b>Request Example:</b><br/>
  * <pre>
  * {
  *     "email" : "*****@*****.**",
  *     "role" : "admin"
  * }
  * </pre>
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *    'ack' : 1,
  *    'data': {"msg": "您当前已成功发送验证邮件到sarazhang@augmentum.com.cn邮箱中", "user": {name:"Devin Jin", avatar:"path/to/avatar", email:"*****@*****.**", isActivated:false}}
  * }
  * </pre>
  */
 public function actionCreate()
 {
     $params = $this->getParams();
     if (empty($params['email'])) {
         throw new InvalidParameterException(['email' => Yii::t('common', 'email_is_required')]);
     }
     $params['email'] = mb_strtolower($params['email']);
     if (!StringUtil::isEmail($params['email'])) {
         throw new InvalidParameterException(['email' => Yii::t('helpDesk', 'email_format_wrong')]);
     }
     $user = User::getByEmail($params['email']);
     if (!empty($user)) {
         throw new InvalidParameterException(['email' => Yii::t('helpDesk', 'email_has_used')]);
     }
     $user = new User();
     $user->email = $params['email'];
     $user->role = $params['role'];
     $user->avatar = Yii::$app->params['defaultAvatar'];
     $user->isActivated = User::NOT_ACTIVATED;
     $user->accountId = $this->getAccountId();
     if ($user->save()) {
         $currentUser = $this->getUser();
         $link = Yii::$app->request->hostInfo . '/site/invite/code?type=2';
         //type=2 means invite user account
         $result = EmailUtil::sendInviteEmail($user, $currentUser->name, $link, self::SUBJECT);
         if ($result) {
             return ['user' => $user];
         } else {
             throw new ServerErrorHttpException("validation save fail");
         }
     }
     throw new ServerErrorHttpException("create user fail");
 }
Ejemplo n.º 4
0
 public function actionIndex()
 {
     $codeId = (string) new \MongoId();
     $code = StringUtil::rndString(4, 1);
     $builder = new CaptchaBuilder($code);
     $builder->build(160, 50);
     $cache = Yii::$app->cache;
     $duration = Yii::$app->params['img_captcha_availab_time'];
     $cache->set($codeId, $code, $duration);
     return ['message' => 'OK', 'data' => $builder->inline(), 'codeId' => $codeId];
 }
Ejemplo n.º 5
0
 /**
  * create a default category for reservation
  * @return array
  * @param $name, string
  * @param $propertyName, string
  */
 public function createDefaultReservationCategory($name, $propertyName = 'price')
 {
     $condition = ['name' => $name, 'accountId' => $this->accountId];
     $category = ModelProductCategory::findOne($condition);
     if (empty($category)) {
         $category = new ModelProductCategory();
         $data = ['name' => $name, 'accountId' => $this->accountId, 'properties' => [['name' => $propertyName, 'type' => 'input', 'defaultValue' => '', 'isRequired' => 'true', 'order' => 1, 'propertyId' => 'wm' . $propertyName, 'id' => StringUtil::uuid()]]];
         $category->load($data, '');
         $category->save();
     }
     return $category;
 }
Ejemplo n.º 6
0
 /**
  * Generate a html page with content and upload to qiniu
  * @param  string $fileContent The file content
  * @param  string $fileName The html page name
  * @param  bool   $isAllowedOverwrite
  * @return string Html file url
  * @throws ServerErrorHttpException
  */
 public function generateQiniuFile($fileContent, $isAllowedOverwrite = false, $fileName = null)
 {
     if (empty($fileName)) {
         $fileName = StringUtil::uuid() . '.html';
     }
     $file = $this->generateHtml($fileContent, $fileName);
     $result = Yii::$app->qiniu->upload($file, $fileName, $isAllowedOverwrite);
     unlink($file);
     if (!empty($result['key'])) {
         return $this->qiniuUrl . $result['key'];
     } else {
         throw new ServerErrorHttpException(\Yii::t('common', 'upload_fail'));
     }
 }
Ejemplo n.º 7
0
 public static function sendInviteEmail($user, $accountName, $link, $subject, $template = 'invitation')
 {
     $validation = new Validation();
     $validation->userId = $user->_id;
     $validation->code = StringUtil::uuid();
     $validation->expire = new \MongoDate(strtotime('+7 day'));
     if ($validation->save()) {
         $mail = Yii::$app->mail;
         $vars = ['name' => $accountName, 'email' => $user->email, 'host' => Yii::$app->request->hostInfo, 'link' => str_replace('code', $validation->code, $link)];
         $mail->setView('//mail/' . $template, $vars, '//layouts/email');
         $mail->sendMail($user->email, $subject);
         return true;
     }
     return false;
 }
Ejemplo n.º 8
0
 public function actionIndex()
 {
     $accountId = $this->getAccountId();
     $currentHelpdeskId = $this->getUserId();
     $query = HelpDesk::find();
     $clientOpenId = $this->getQuery('clientOpenId');
     if ($orderBy = $this->getQuery('orderBy')) {
         if (StringUtil::isJson($orderBy)) {
             $orderBy = Json::decode($orderBy, true);
             foreach ($orderBy as $key => $value) {
                 if ($value === 'asc' || $value === 'ASC') {
                     $orderBy[$key] = SORT_ASC;
                 } else {
                     $orderBy[$key] = SORT_DESC;
                 }
             }
         } else {
             $orderBy = [$orderBy => SORT_DESC];
         }
         $query->orderBy($orderBy);
     }
     $allHelpdesks = $query->where(['accountId' => $accountId, 'isDeleted' => false, 'isActivated' => true, 'isEnabled' => true])->andWhere(['not in', '_id', [$currentHelpdeskId]])->orderBy(['clientCount' => SORT_ASC])->all();
     $result = [];
     if ($allHelpdesks) {
         foreach ($allHelpdesks as $helpdesk) {
             array_push($result, $helpdesk->toArray());
         }
     }
     $lastChatConversation = ChatConversation::getLastChatByClient($clientOpenId, $currentHelpdeskId, $accountId);
     if ($lastChatConversation) {
         $lastServeHelpdeskId = (string) $lastChatConversation->desk['id'];
         if (!empty($result)) {
             $allOnlineHelpdesks = [];
             foreach ($result as $index => $item) {
                 if ($item['isOnline'] && $item['id'] === $lastServeHelpdeskId) {
                     $item['isLastChat'] = true;
                     array_unshift($allOnlineHelpdesks, $item);
                 } else {
                     if ($item['isOnline']) {
                         array_push($allOnlineHelpdesks, $item);
                     }
                 }
             }
             $result = $allOnlineHelpdesks;
         }
     }
     return $result;
 }
Ejemplo n.º 9
0
 /**
  * Request the service with basic auth
  * @param string $url requested url
  * @param string $method requested method
  * @param string $params requested parameters
  */
 private function _requestService($url, $method, $params = NULL)
 {
     //format header and params for post and put
     if (in_array($method, [self::METHOD_POST, self::METHOD_PUT])) {
         $method = $method . 'Json';
         $params = Json::encode($params);
     }
     $resultJson = Yii::$app->curl->{$method}($url, $params);
     $logUrl = strtoupper($method) . ' ' . $url;
     $logTarget = 'webhook';
     LogUtil::info(['url' => $logUrl, 'response' => $resultJson, 'params' => $params], $logTarget);
     if (StringUtil::isJson($resultJson)) {
         return Json::decode($resultJson, true);
     } else {
         LogUtil::error(['url' => $logUrl, 'response' => $resultJson, 'params' => $params], $logTarget);
     }
 }
Ejemplo n.º 10
0
 /**
  * when crate a staff successful,and send sms fail,we need to delete the staff
  */
 public function actionCreate()
 {
     $params = $this->getParams();
     if (empty($params['phone']) || empty($params['channel']['channelId']) || empty($params['badge']) || empty($params['storeId'])) {
         throw new BadRequestHttpException('params missing');
     }
     $accountId = $this->getAccountId();
     $params['accountId'] = $accountId;
     $existsEmpID = Staff::checkUnique($params['badge'], $accountId);
     if ($existsEmpID) {
         throw new InvalidParameterException(['badge' => Yii::t("store", "badge_exists")]);
     }
     $storeId = $params['storeId'];
     $params['storeId'] = new \MongoId($storeId);
     if (false === Staff::checkPhone($params['storeId'], $params['phone'])) {
         throw new InvalidParameterException(['phone' => Yii::t("store", 'phone_exists')]);
     }
     $data = Staff::setQrcodeParam($params['channel']['channelId']);
     $params = array_merge($params, $data);
     $params['salt'] = StringUtil::rndString(6, 1);
     $staff = new Staff();
     $staff->load($params, '');
     $result = 'success';
     if ($staff->save()) {
         if (!empty($params['useWebhook'])) {
             $eventData = ['type' => Webhook::EVENT_STAFF_CREATED, 'store_id' => $storeId, 'staff_id' => (string) $staff->_id, 'phone' => $params['phone'], 'badge' => $params['badge'], 'channel' => ['id' => $params['channel']['channelId'], 'name' => $params['channel']['channelName'], 'type' => $params['channel']['channelType']], 'origin' => Member::PORTAL, 'account_id' => (string) $accountId, 'created_at' => MongodbUtil::MongoDate2String($staff->createdAt, \DateTime::ATOM)];
             Yii::$app->webhook->triggerEvent($eventData);
         } else {
             //send mobile message
             $template = Staff::getMobileTemplate($accountId);
             $status = MessageUtil::sendMobileMessage($params['phone'], $template);
             if (false === $status) {
                 $result = 'fail';
                 //delete the staff
                 Staff::getCollection()->remove(['_id' => $staff->_id]);
                 LogUtil::error(['message' => 'Faild to send message', 'template' => $template, 'params' => $params], 'staff');
             }
         }
     } else {
         throw new ServerErrorHttpException(Yii::t('store', 'fail_to_create'));
     }
     return ['result' => $result];
 }
Ejemplo n.º 11
0
 /**
  * Push open message by target
  * @param Array $taget
  * @param string $message
  * @throws ApiDataException
  */
 public function pushMessage($taget, $badge, $extra, $message)
 {
     $url = $this->domain . '/v2/open/messages';
     $content['ttl'] = \Yii::$app->params['PUSH_MESSAGE_MAX_SAVE_TIME'];
     $content['extra'] = $extra;
     if ($message !== null) {
         $content['alert'] = $message;
         $content['apns'] = ['badge' => $badge, 'sound' => 'default', 'content-available' => 1];
     } else {
         $content['apns'] = ['content-available' => 1];
     }
     $params = ['content' => $content, 'target' => ['tokens' => $taget], 'trigger' => ['now' => true]];
     $resultJson = $this->requestService($url, self::METHOD_POST, $params, true);
     LogUtil::info(['url' => $url, 'params' => $params, 'result' => $resultJson], 'helpdesk');
     if (StringUtil::isJson($resultJson)) {
         $result = Json::decode($resultJson, true);
     } else {
         throw new ApiDataException($url, $resultJson, $params, 'helpdesk');
     }
     if (empty($result['nid'])) {
         throw new ApiDataException($url, $result, $params, 'helpdesk');
     }
 }
Ejemplo n.º 12
0
 public static function refund($accountId, $refundInfo)
 {
     $refund = new self();
     $refundNumber = StringUtil::getUniqueCode('refund', 'T');
     $refund->transactionId = empty($refundInfo['transactionId']) ? '' : $refundInfo['transactionId'];
     $refund->refundNumber = $refundNumber;
     $refund->accountId = $accountId;
     $refund->orderNumber = $refundInfo['orderNumber'];
     $refund->expectedAmount = $refundInfo['expectedAmount'];
     $refund->realAmount = $refundInfo['realAmount'];
     $refund->admin = $refundInfo['admin'];
     $refund->user = $refundInfo['user'];
     $refund->refundMode = $refundInfo['refundMode'];
     $refund->refundAt = empty($refundInfo['refundAt']) ? new MongoDate() : new MongoDate(TimeUtil::ms2sTime($refundInfo['refundAt']));
     $comments = empty($refundInfo['comments']) ? '' : $refundInfo['comments'];
     $refund->comments = $comments;
     $refund->subject = $refundInfo['subject'];
     return $refund->Save();
 }
Ejemplo n.º 13
0
 /**
  * Search product by conditions
  * @param Array $params
  * @param string $accountId
  * @return product info
  */
 public static function search($params, $accountId)
 {
     $query = self::find();
     $comma = ',';
     $condition = ['accountId' => $accountId, 'isDeleted' => StoreGoods::NOT_DELETED];
     if (!empty($params['categoryIds'])) {
         $categorys = explode($comma, $params['categoryIds']);
         $categoryIds = [];
         foreach ($categorys as $category) {
             $categoryIds[] = new \MongoId($category);
         }
         $categorys = ['$in' => $categoryIds];
         $condition['categoryId'] = $categorys;
     }
     if (array_key_exists('searchKey', $params) && '' != $params['searchKey']) {
         $key = $params['searchKey'];
         $key = StringUtil::regStrFormat(trim($key));
         $keyReg = new \MongoRegex("/{$key}/i");
         $search = ['$or' => [['productName' => $keyReg], ['sku' => $keyReg]]];
         $condition = array_merge($condition, $search);
     }
     if (!empty($params['status'])) {
         $condition['status'] = $params['status'];
     }
     if (!empty($params['storeId'])) {
         $condition['storeId'] = $params['storeId'];
     }
     if (isset($params['saleTimeFrom']) && $params['saleTimeFrom'] !== '') {
         $condition['onSaleTime']['$gte'] = new \MongoDate(TimeUtil::ms2sTime($params['saleTimeFrom']));
     }
     if (isset($params['saleTimeTo']) && $params['saleTimeTo'] !== '') {
         $condition['onSaleTime']['$lte'] = new \MongoDate(TimeUtil::ms2sTime($params['saleTimeTo']));
     }
     if (isset($params['priceFrom']) && $params['priceFrom'] !== '') {
         $condition['price']['$gte'] = floatval($params['priceFrom']);
     }
     if (isset($params['priceTo']) && $params['priceTo'] !== '') {
         $condition['price']['$lte'] = floatval($params['priceTo']);
     }
     $query->orderBy(self::normalizeOrderBy($params));
     $query->where($condition);
     $searchQuery = ['query' => $query];
     return new ActiveDataProvider($searchQuery);
 }
Ejemplo n.º 14
0
 /**
  * Generate account access key and sercet key
  */
 public function generateKey()
 {
     $this->accessKey = StringUtil::rndString(10);
     $this->secretKey = StringUtil::rndString(40);
     $this->keyCreatedAt = new \MongoDate();
 }
Ejemplo n.º 15
0
 public static function getSearchCondition($accountId, $params)
 {
     $condition = ['accountId' => $accountId, 'status' => self::STATUS_PAID, 'payMode' => self::PAY_MODE_WECHAT];
     if (!empty($params['searchKey'])) {
         $searchKey = StringUtil::regStrFormat($params['searchKey']);
         $searchKey = new MongoRegex("/{$searchKey}/i");
         $condition['transactionId'] = $searchKey;
     }
     if (!empty($params['startTime'])) {
         $condition['paymentTime']['$gte'] = new MongoDate(TimeUtil::ms2sTime($params['startTime']));
     }
     if (!empty($params['endTime'])) {
         $condition['paymentTime']['$lt'] = new MongoDate(TimeUtil::ms2sTime($params['endTime']));
     }
     return $condition;
 }
Ejemplo n.º 16
0
 /**
  * Update a store qrcode
  *
  * <b>Request Type</b>: PUT<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/offlinestore/qrcode/update<br/><br/>
  * <b>Response Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for update a store qrcode
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     storeId: string<br/>
  *     msgType: TEXT or NEWS<br/>
  *     content: string|array If msgType is TEXT, it's a string. If msgType is NEWS, it's an array<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     array, json array to querie qrcode detail information<br/>
  *     <br/><br/>
  *
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *     wechat: {
  *         "id": "5473ffe7db7c7c2f0bee5c71",
  *         "accountId": "5473ffe7db7c7c2f0bee5c71",
  *         "replyMessage": {
  *             "msgType": "NEWS",
  *             "articles": [
  *                 {
  *                     "title": "没有",
  *                     "description": "",
  *                     "url": "http://vincenthou.qiniudn.com/94b6e2756acb030f6f76f690.jpg",
  *                     "content": "<p>哈哈哈哈</p>"
  *                  }
  *              ]
  *          },
  *          "sceneId": 1,
  *          "name": "这只是一个测试",
  *          "type": "EVENT",
  *          "description": "招聘一些人才为公司,以备用",
  *          "ticket": "gQFh8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL3BrampCdVBtVlprc25JVDFHR1RQAAIErHaXVAMEAAAAAA==",
  *          "scanCount": 0,
  *          "subscribeCount": 0,
  *          "createTime": 1421113098304,
  *          "imageUrl": "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFh8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL3BrampCdVBtVlprc25JVDFHR1RQAAIErHaXVAMEAAAAAA=="
  *      },
  *      weibo: {
  *          "id": "5473ffe7db7c7c2f0bee5c71",
  *          "accountId": "5473ffe7db7c7c2f0bee5c71",
  *          "replyMessage": {
  *              "msgType": "NEWS",
  *              "articles": [
  *                  {
  *                      "title": "没有",
  *                      "description": "",
  *                      "url": "http://vincenthou.qiniudn.com/94b6e2756acb030f6f76f690.jpg",
  *                      "content": "<p>哈哈哈哈</p>"
  *                  }
  *             ]
  *          },
  *          "sceneId": 1,
  *          "name": "这只是一个测试",
  *          "type": "EVENT",
  *          "description": "招聘一些人才为公司,以备用",
  *          "ticket": "gQFh8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL3BrampCdVBtVlprc25JVDFHR1RQAAIErHaXVAMEAAAAAA==",
  *          "scanCount": 0,
  *          "subscribeCount": 0,
  *          "createTime": 1421113098304,
  *          "imageUrl": "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFh8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL3BrampCdVBtVlprc25JVDFHR1RQAAIErHaXVAMEAAAAAA=="
  *      }
  * }
  * </pre>
  */
 public function actionUpdate()
 {
     $qrcode = $this->getParams();
     if (empty($qrcode['storeId'])) {
         throw new BadRequestHttpException(Yii::t('common', 'parameters_missing'));
     }
     $result = ['wechat' => [], 'weibo' => []];
     $storeId = new \MongoId($qrcode['storeId']);
     $store = Store::findByPk($storeId);
     $qrcode['name'] = $store->branchName . StringUtil::uuid();
     $qrcode['type'] = self::QRCODE_TYPE_STORE;
     unset($qrcode['storeId']);
     if (!empty($store->wechat['channelId'])) {
         $wechatId = $store->wechat['channelId'];
         $qrcodeId = $store->wechat['qrcodeId'];
         $result['wechat'] = Yii::$app->weConnect->updateQrcode($wechatId, $qrcodeId, $qrcode);
     }
     if (!empty($store->weibo['channelId'])) {
         $weiboId = $store->weibo['channelId'];
         $qrcodeId = $store->weibo['qrcodeId'];
         $result['weibo'] = Yii::$app->weConnect->updateQrcode($weiboId, $qrcodeId, $qrcode);
     }
     return $result;
 }
Ejemplo n.º 17
0
 /**
  * Send to preview mass message
  *
  * <b>Request Type</b>: POST<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/channel/mass-message/preview<br/><br/>
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for sending to preview mass message.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     channelId: string<br/>
  *     msgType: TEXT or MPNEWS<br/>
  *     content: string, if TEXT<br/>
  *     content.articles, if MPNEWS<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     msg: string, if query fail, it contains the error message<br/>
  *     <br/><br/>
  *
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *   "qrcode": "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQG/7joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xLzFFZ2xZcG5taVpudzh2U0wzbWJQAAIEekd1VQMECAcAAA==",
  *   "expireTime": 1800
  * }
  * </pre>
  */
 public function actionPreview()
 {
     $qrcode = $this->getParams();
     $channelId = $this->getChannelId();
     $qrcode['name'] = StringUtil::uuid();
     $qrcode['type'] = 'PREVIEW';
     $qrcode['temporary'] = true;
     $qrcode['expireSeconds'] = static::TEMP_QRCODE_EXPIRE;
     unset($qrcode['channelId']);
     $result = Yii::$app->weConnect->createQrcode($channelId, $qrcode);
     if ($result && isset($result['imageUrl'])) {
         return ['qrcode' => $result['imageUrl'], 'expireTime' => static::TEMP_QRCODE_EXPIRE];
     } else {
         throw new ServerErrorHttpException('Create mass message fail.');
     }
 }
Ejemplo n.º 18
0
 /**
  * Search product by conditions
  * @param Array $params
  * @param string $accountId
  * @return product info
  */
 public static function search($params, $accountId)
 {
     $query = Goods::find();
     $comma = ',';
     $condition = ['accountId' => $accountId, 'isDeleted' => Goods::NOT_DELETED];
     if (!empty($params['category'])) {
         $categorys = explode($comma, $params['category']);
         $categoryIds = [];
         foreach ($categorys as $category) {
             $categoryIds[] = new MongoId($category);
         }
         $categorys = ['$in' => $categoryIds];
         $condition = array_merge($condition, ['categoryId' => $categorys]);
     }
     if (array_key_exists('searchKey', $params) && '' != $params['searchKey']) {
         $key = $params['searchKey'];
         $key = StringUtil::regStrFormat(trim($key));
         $keyReg = new \MongoRegex("/{$key}/i");
         $search = ['$or' => [['productName' => $keyReg], ['sku' => $keyReg]]];
         $condition = array_merge($condition, $search);
     }
     if (!empty($params['notSoldOut'])) {
         $condition['total'] = ['$ne' => 0];
     }
     if (!empty($params['status'])) {
         $condition = self::createStatusCondition($params['status'], $condition);
     }
     $query->orderBy(self::normalizeOrderBy($params));
     $query->where($condition);
     $searchQuery = ['query' => $query];
     if (isset($params['isAll']) && $params['isAll']) {
         $searchQuery = array_merge($searchQuery, ['pagination' => ['pageSize' => 99999]]);
     }
     return new ActiveDataProvider($searchQuery);
 }
Ejemplo n.º 19
0
 /**
  * search coupon
  */
 public static function search($params)
 {
     $query = Coupon::find();
     $condition = ['accountId' => $params['accountId'], 'isDeleted' => self::NOT_DELETED];
     if (!empty($params['title'])) {
         $key = $params['title'];
         $key = StringUtil::regStrFormat(trim($key));
         $keyReg = new MongoRegex("/{$key}/i");
         $search = ['title' => $keyReg];
         $condition = array_merge($condition, $search);
         unset($search);
     }
     if (!empty($params['unexpired'])) {
         $time = new MongoDate(strtotime(TimeUtil::msTime2String($params['unexpired'], 'Y-m-d')));
         $search = ['$or' => [['time.type' => self::COUPON_ABSOLUTE_TIME, 'time.endTime' => ['$gte' => $time]], ['time.type' => self::COUPON_RELATIVE_TIME]]];
         $condition = array_merge($condition, $search);
         unset($search, $time);
     }
     $query->orderBy(self::normalizeOrderBy($params));
     $query->where($condition);
     $unlimited = Yii::$app->request->get('unlimited', false);
     if ($unlimited) {
         return ['items' => $query->all()];
     }
     return new ActiveDataProvider(['query' => $query]);
 }
Ejemplo n.º 20
0
 /**
  * Search for coupon recieved, redeemed,deleted records.
  * @param array $params The search condition
  * @param string $accountId
  * @return array The couponLog list for recieved, redeemed,deleted records
  */
 public static function search($params, $accountId)
 {
     $condition = ['accountId' => $accountId, 'status' => $params['status']];
     $query = CouponLog::find();
     if (!empty($params['startTime'])) {
         $startTime = MongodbUtil::msTimetamp2MongoDate($params['startTime']);
         $condition['operationTime']['$gte'] = $startTime;
     }
     if (!empty($params['endTime'])) {
         $endTime = MongodbUtil::msTimetamp2MongoDate($params['endTime']);
         $condition['operationTime']['$lte'] = $endTime;
     }
     if (!empty($params['searchKey'])) {
         $key = $params['searchKey'];
         $key = StringUtil::regStrFormat(trim($key));
         $keyReg = new \MongoRegex("/{$key}/i");
         $condition['$or'] = [['member.name' => $keyReg], ['member.phone' => $keyReg], ['title' => $keyReg]];
     }
     if (empty($params['orderBy'])) {
         $orderBy = ['operationTime' => SORT_DESC];
     } else {
         switch ($params['orderBy']) {
             case 'asc':
                 $orderBy = ['operationTime' => SORT_ASC];
                 break;
             default:
                 $orderBy = ['operationTime' => SORT_DESC];
                 break;
         }
     }
     $query = $query->where($condition)->orderBy($orderBy);
     $searchQuery = ['query' => $query];
     return new ActiveDataProvider($searchQuery);
 }
Ejemplo n.º 21
0
 public static function createForWechat($accountId)
 {
     $account = Account::findByPk($accountId);
     if (empty($account)) {
         throw new Exception("Illegal accountId");
     }
     $expire = 3600 * 24 * 10000;
     //never expired
     $token = new Token();
     $token->accessToken = StringUtil::uuid();
     $token->expireTime = new \MongoDate(time() + $expire);
     $token->userId = '';
     $token->accountId = $account['_id'];
     $token->language = self::DEFAULT_LANGUAGE;
     $token->enabledMods = ['chat'];
     $token->role = User::ROLE_WECONNECT;
     if ($token->save()) {
         return $token;
     }
     throw new Exception("Faile to create token for database problems");
 }
Ejemplo n.º 22
0
 /**
  * create condition for search
  */
 public static function createCondition($params, $accountId)
 {
     $condition = ['accountId' => $accountId, 'isDeleted' => self::NOT_DELETED];
     //order number
     if (!empty($params['orderNumber'])) {
         $orderNumber = StringUtil::regStrFormat(trim($params['orderNumber']));
         $condition['orderNumber'] = new MongoRegex("/{$orderNumber}/i");
     }
     if (!empty($params['memberId'])) {
         $condition['consumer.id'] = $params['memberId'];
     }
     //order status
     if (!empty($params['status'])) {
         $status = explode(',', $params['status']);
         $condition['status'] = ['$in' => $status];
     }
     //store id
     if (!empty($params['storeId'])) {
         $condition['storeId'] = new \MongoId($params['storeId']);
     }
     //createdAt
     // After run new MongoDate, The time can lost accuracy, so it will plus 1 or subtract 1.
     if (!empty($params['beginCreatedAt'])) {
         $beginCreatedAt = TimeUtil::ms2sTime($params['beginCreatedAt']) - 1;
         $condition['createdAt']['$gt'] = new MongoDate($beginCreatedAt);
     }
     if (!empty($params['endCreatedAt'])) {
         $endCreatedAt = TimeUtil::ms2sTime($params['endCreatedAt']) + 1;
         $condition['createdAt']['$lt'] = new MongoDate($endCreatedAt);
     }
     //price
     if (!empty($params['minAmount'])) {
         $condition['totalPrice']['$gte'] = floatval($params['minAmount']);
     }
     if (!empty($params['maxAmount'])) {
         $condition['totalPrice']['$lte'] = floatval($params['maxAmount']);
     }
     //staff info
     if (!empty($params['staff'])) {
         $staffName = StringUtil::regStrFormat(trim($params['staff']));
         $staffName = new MongoRegex("/{$staffName}/i");
         $condition['staff.name'] = $staffName;
     }
     //member info
     if (!empty($params['member'])) {
         $member = StringUtil::regStrFormat(trim($params['member']));
         $condition['consumer.name'] = new MongoRegex("/{$member}/i");
     }
     return $condition;
 }
Ejemplo n.º 23
0
 /**
  * Send mobile captcha.
  *
  * <b>Request Type</b>: POST<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/api/mobile/send-captcha<br/><br/>
  * <b>Response Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for send mobile captcha.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     mobile: string, phone number<br/>
  *     unionId: string<br/>
  *     language: 'zh_cn' or 'en_us', This param is just for update mobile<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     message: OK or Fail
  *     data: string, if success, It is verification code<br/>
  *     <br/><br/>
  *
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *  "message": "OK",
  *  "data": "456787"
  * }
  * </pre>
  */
 public function actionSendCaptcha()
 {
     $params = $this->getParams();
     if (empty($params['type']) || empty($params['mobile']) || empty($params['codeId']) || empty($params['code'])) {
         throw new BadRequestHttpException('Missing params');
     }
     $type = $params['type'];
     $mobile = $params['mobile'];
     if (in_array($type, [self::CAPTCHA_TYPE_COMPANY_INFO, self::CAPTCHA_TYPE_EXCHANGE])) {
         $params['accountId'] = $this->getAccountId();
     } else {
         if (!in_array($type, [self::CAPTCHA_TYPE_BIND, self::CAPTCHA_TYPE_SIGNUP])) {
             throw new BadRequestHttpException('Invalid type');
         }
     }
     $this->attachBehavior('CaptchaBehavior', new CaptchaBehavior());
     $companyInfo = $this->{$type}($params);
     $company = $companyInfo['company'] === null ? self::DEFAULT_COMPANY : $companyInfo['company'];
     $accountId = $companyInfo['accountId'];
     //limit captcha send by ip
     $ip = Yii::$app->request->userIp;
     $captcha = Captcha::getByIP($ip);
     $now = time();
     if (!empty($captcha)) {
         $sendTimeInt = MongodbUtil::MongoDate2TimeStamp($captcha->createdAt);
         $nextTime = $sendTimeInt + Yii::$app->params['captcha_send_interval'];
         if ($nextTime > $now) {
             throw new InvalidParameterException(['phone' => Yii::t('common', 'send_too_frequently')]);
         } else {
             $captcha->isExpired = true;
             $captcha->save();
         }
     }
     //get random string, length = 6, charlist = '0123456789'
     $code = StringUtil::rndString(6, 0, '0123456789');
     $text = str_replace('#code#', $code, Yii::$app->params['mobile_message_text']);
     $text = str_replace('#company#', $company, $text);
     $captcha = new Captcha();
     $captcha->ip = $ip;
     $captcha->code = $code;
     $captcha->mobile = $mobile;
     $captcha->isExpired = false;
     $captcha->accountId = $accountId;
     if (MessageUtil::sendMobileMessage($mobile, $text) && $captcha->save()) {
         MessageUtil::recoreMessageCount('omni_record_message_' . $type);
         $result = ['message' => 'OK', 'data' => ''];
     } else {
         $result = ['message' => 'Error', 'data' => 'unknow error'];
     }
     return $result;
 }
Ejemplo n.º 24
0
 /**
  * deal with the klp data before export
  * @param $member,object
  * @param $headerKey,array
  */
 public static function preProcessKlpMemberData($member, $headerKeys)
 {
     $row = [];
     foreach ($member['properties'] as $property) {
         foreach ($headerKeys as &$headerKey) {
             //set the default value for County and Country
             $row['county'] = $row['country'] = '台灣';
             //change the value for gender
             if ($property['name'] == self::DEFAULT_PROPERTIES_GENDER) {
                 if ($property['value'] == 'male') {
                     $property['value'] = '先生';
                 } else {
                     $property['value'] = '小姐';
                 }
             }
             //modify the name,divide the name,and the result is firstName and surname
             if ($property['name'] == self::DEFAULT_PROPERTIES_NAME) {
                 list($lastName, $firstName) = StringUtil::splitName($property['value']);
                 $row['firstName'] = $firstName;
                 $row['lastName'] = $lastName;
             }
             //set the value for tel_1 and tel_2,becuse their value is equal with tel
             if ($property['name'] == self::DEFAULT_PROPERTIES_MOBILE) {
                 $row['tel_1'] = $row['tel_2'] = $property['value'];
             }
             if ($property['name'] == $headerKey) {
                 if (is_array($property['value'])) {
                     $row[$headerKey] = implode(',', $property['value']);
                 } else {
                     $row[$headerKey] = $property['value'];
                 }
             }
             //set ''
             if ($headerKey == 'tel' || $headerKey == '密碼') {
                 $row[$headerKey] = '';
             }
             //set default value;if the key value is not set,we must set the default value
             if (!isset($row[$headerKey])) {
                 $row[$headerKey] = '';
             }
         }
     }
     unset($member, $headerKeys);
     return $row;
 }
Ejemplo n.º 25
0
 /**
  * Register billing account
  *
  * <b>Request Type</b>: POST<br/><br/>
  * <b>Request Endpoint</b>:http://{server-domain}/site/register<br/><br/>
  * <b>Content-type</b>: application/json<br/><br/>
  * <b>Summary</b>: This api is used for registering user.
  * <br/><br/>
  *
  * <b>Request Params</b>:<br/>
  *     name: string, the user name<br/>
  *     email: string, the user email<br/>
  *     password: string, the user password<br/>
  *     <br/><br/>
  *
  * <b>Response Params:</b><br/>
  *     ack: integer, mark the create result, 1 means create successfully, 0 means create fail<br/>
  *     message: string, if create fail, it contains the error message<br/>
  *     data: array, json array to describe all users detail information<br/>
  *     <br/><br/>
  *
  * <b>Request Example:</b><br/>
  * <pre>
  * {
  *     "name" : "harrysun",
  *     "email" : "*****@*****.**",
  *     "password" : "abc123_"
  * }
  * </pre>
  * <br/><br/>
  *
  * <b>Response Example</b>:<br/>
  * <pre>
  * {
  *    'ack' : 1,
  *    'message': ''
  * }
  * </pre>
  */
 public function actionRegister()
 {
     $data = $this->getParams();
     $account = new Account();
     $account->save();
     $user = new User();
     $user->name = $data['name'];
     $user->email = $data['email'];
     $user->salt = StringUtil::rndString(6);
     $user->password = User::encryptPassword($data['password'], $user->salt);
     $user->accountId = $account->_id;
     $user->role = User::ROLE_ADMIN;
     $user->isActivated = User::NOT_ACTIVATED;
     $user->avatar = Yii::$app->params['defaultAvatar'];
     $user->language = 'zh_cn';
     if ($user->validate()) {
         // all inputs are valid
         if ($user->save()) {
             $validation = new Validation();
             $validation->userId = $user->_id;
             $validation->code = StringUtil::uuid();
             $validation->expire = new \MongoDate(strtotime('+1 day'));
             if ($validation->save()) {
                 $mail = Yii::$app->mail;
                 $host = Yii::$app->request->hostInfo;
                 $vars = ['name' => $user->name, 'link' => $host . '/api/old-site/activate?code=' . $validation->code, 'host' => $host];
                 $mail->setView('//mail/register', $vars, '//layouts/email');
                 $mail->sendMail($user->email, '欢迎注册WeMarketing');
                 return ["ack" => 1, "message" => 'Register success.'];
             } else {
                 return ["ack" => 0, "message" => 'Validation save fail.'];
             }
         } else {
             return ["ack" => 0, "message" => 'Register user fail.'];
         }
     } else {
         // validation failed: $errors is an array containing error messages
         $errors = $user->errors;
         //revert the accout data
         Account::deleteAll(['_id' => $account->_id]);
         return ["ack" => 0, "message" => $errors];
     }
 }
Ejemplo n.º 26
0
 /**
  * Prepares the data provider that should return the requested collection of the models.
  * @return ActiveDataProvider
  */
 protected function prepareDataProvider()
 {
     if ($this->prepareDataProvider !== null) {
         return call_user_func($this->prepareDataProvider, $this);
     }
     /* @var $modelClass \yii\db\BaseActiveRecord */
     $modelClass = $this->modelClass;
     $query = $modelClass::find();
     $token = $this->getAccessToken();
     $accountId = $this->getAccountId();
     $whereCondition = ['accountId' => $accountId];
     if (!new $modelClass() instanceof PlainModel) {
         $whereCondition['isDeleted'] = $modelClass::NOT_DELETED;
     }
     if ($orderBy = Yii::$app->request->get('orderBy', 'createdAt')) {
         if (StringUtil::isJson($orderBy)) {
             $orderBy = Json::decode($orderBy, true);
             foreach ($orderBy as $key => $value) {
                 if ($value === 'asc' || $value === 'ASC') {
                     $orderBy[$key] = SORT_ASC;
                 } else {
                     $orderBy[$key] = SORT_DESC;
                 }
             }
         } else {
             $orderBy = [$orderBy => SORT_DESC];
         }
         $query->orderBy($orderBy);
     }
     if ($where = Yii::$app->request->get('where')) {
         $keys = ['lt', 'lte', 'gt', 'gte', 'ne', 'in', 'nin', 'all'];
         $where = Json::decode($where, true);
         $newWhere = [];
         //set a default method to get whitch value in a array need to conver to mongoId
         $conver2MongoIds = [];
         if (method_exists($modelClass, 'conver2MongoId')) {
             $conver2MongoIds = $modelClass::conver2MongoId();
         }
         foreach ($where as $index => $condition) {
             if ($index == '_id' || in_array($index, $conver2MongoIds)) {
                 $condition = $this->ensureMongoId($condition);
             }
             if (is_array($condition)) {
                 $newCondition = [];
                 foreach ($condition as $key => $value) {
                     if (in_array($key, $keys)) {
                         $key = '$' . $key;
                     }
                     $newCondition[$key] = $value;
                 }
                 $condition = $newCondition;
             }
             $newWhere[$index] = $condition;
         }
         $whereCondition = array_merge($whereCondition, $newWhere);
     }
     if ($search = Yii::$app->request->get('search')) {
         $search = Json::decode($search, true);
         foreach ($search as $key => $value) {
             $value = trim($value);
             $value = StringUtil::regStrFormat($value);
             $where[$key] = new \MongoRegex("/{$value}/i");
         }
         $whereCondition = array_merge($whereCondition, $where);
     }
     $query->where($whereCondition);
     $unlimited = Yii::$app->request->get('unlimited', false);
     if ($unlimited) {
         return ['items' => $query->all()];
     }
     return new ActiveDataProvider(['query' => $query]);
 }
Ejemplo n.º 27
0
 public function actionCheckUnique()
 {
     $query = $this->getQuery();
     $accountId = $this->getAccountId();
     if (!empty($query['email'])) {
         $email = $query['email'];
         if (!StringUtil::isEmail($email)) {
             throw new InvalidParameterException(['email' => Yii::t('helpDesk', 'email_format_wrong')]);
         }
         $helpDesk = HelpDesk::getByEmail($email);
         if (!empty($helpDesk)) {
             throw new InvalidParameterException(['email' => Yii::t('helpDesk', 'email_has_used')]);
         }
     }
     if (!empty($query['badge'])) {
         $helpDesk = HelpDesk::getByBadge($query['badge'], $accountId);
         if (!empty($helpDesk)) {
             throw new InvalidParameterException(['number' => Yii::t('helpDesk', 'badge_has_used')]);
         }
     }
     return true;
 }
Ejemplo n.º 28
0
 /**
  * Add a website into help desk setting
  *
  * <b>Request Type: </b>PUT<br/>
  * <b>Request Endpoint: </b>http://{server-domain}/api/helpdesk/setting/add-website<br/>
  * <b>Content-type: </b>Application/json<br/>
  * <b>Summary: </b>This api is for adding a website into help desk setting.<br/>
  *
  * <b>Request Example: </b>
  * <pre>
  *     {
  *          "settingId": '52d791327ae252f9149547cb',
  *          "Website"  : {
  *              "name" : '爱不宅',
  *              "url"  : 'www.ibuzhai.com'
  *          }
  *     }
  * </pre>
  */
 public function actionAddWebsite()
 {
     $checkUrl = "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";
     $website = $this->getParams('website');
     $settingId = $this->getParams('settingId');
     $accountId = $this->getAccountId();
     if (!ereg($checkUrl, $website['url'])) {
         throw new InvalidParameterException(['url' => Yii::t('helpDesk', 'url_format_wrong')]);
     }
     if (!empty($website['name']) && !empty($website['url'])) {
         $settingId = new \MongoId($settingId);
         $website = ['id' => StringUtil::uuid(), 'name' => $website['name'], 'url' => $website['url'], 'code' => HelpDeskSetting::getCode($website['url'], $accountId)];
         // Add a website into help desk setting
         $result = HelpDeskSetting::updateAll(['$push' => ['websites' => $website]], ['_id' => $settingId]);
         if ($result) {
             return $website;
         }
         throw new ServerErrorHttpException('add website fail');
     }
     throw new BadRequestHttpException('parameters missing');
 }
Ejemplo n.º 29
0
 /**
  * Returns the list of all rules of user.
  * This method must be overridden by child classes to define available attributes.
  *
  * @return array list of rules.
  */
 public function rules()
 {
     return array_merge(parent::rules(), [['code', 'default', 'value' => StringUtil::uuid()], ['toValidateAccount', 'default', 'value' => false]]);
 }
Ejemplo n.º 30
0
 /**
  * Get wehcat pay signature
  *
  * Request Method:
  *
  *     POST
  *
  * Request Parameters:
  *
  *     {
  *         "quncrmAccountId": "群脉账号ID",
  *         "params": {
  *             "key1": "value1",
  *             "key2": "value2",
  *             "key3": "value3",
  *         }
  *     }
  *
  * Response Body:
  *
  *      {
  *           "code": 200,
  *           "message": "OK",
  *           "data": {
  *               "appId": "公众账号ID",
  *               "signType": "DSA、RSA、MD5",
  *               "paySign": "signString"
  *           }
  *       }
  * @return [type] [description]
  */
 public function getWechatPaySignature($accountId, $prepayId, $appId)
 {
     $url = $this->weconnectDomain . '/weixin/pay/sign';
     $timestamp = time();
     $nonceStr = StringUtil::rndString(16, StringUtil::ALL_DIGITS_LETTERS);
     $params = ['timeStamp' => $timestamp, 'nonceStr' => $nonceStr, 'package' => "prepay_id={$prepayId}", 'appId' => $appId, 'signType' => 'MD5'];
     $data = ['quncrmAccountId' => (string) $accountId, 'params' => $params];
     LogUtil::info(['wechat signature data' => $data], 'reservation');
     $result = Yii::$app->curl->postJson($url, json_encode($data));
     $result = json_decode($result, true);
     LogUtil::info(['wechat signature result' => $result], 'reservation');
     if (!empty($result) && $result['code'] === 200 && !empty($result['data'])) {
         $params['appId'] = $result['data']['appId'];
         $params['signType'] = $result['data']['signType'];
         $params['paySign'] = $result['data']['paySign'];
         return $params;
     }
 }