/** * 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}×tamp={$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; }
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]; }
/** * 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]; }
/** * 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]; } }
/** * 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; }
/** * Generate account access key and sercet key */ public function generateKey() { $this->accessKey = StringUtil::rndString(10); $this->secretKey = StringUtil::rndString(40); $this->keyCreatedAt = new \MongoDate(); }
/** * 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; } }
/** * create a code when user receive coupon * @param $accountId, MongoId */ public static function getCouponCode($accountId) { $code = StringUtil::rndString(12, 1); $data = MembershipDiscount::findOne(['code' => $code, 'accountId' => $accountId]); if (empty($data)) { return $code; } else { return self::getCouponCode($accountId); } }
/** *create a number of product */ public static function createSku() { $charlist = '0123456789'; $rand = StringUtil::rndString(6, 0, $charlist); $currentChar = time() . $rand; $result = Product::getSku($currentChar); if (empty($result)) { return ['number' => $currentChar]; } else { self::createNum(); } }
/** * create a user by email(generate-by-email) */ public function actionGenerateByEmail($email) { $email = mb_strtolower($email); $user = User::getByEmail($email); if (!empty($user)) { echo 'email is used' . PHP_EOL; return; } $name = Yii::$app->params['defaultName']; $accountId = Account::create('', '', $name); $attributes = ['status' => Account::STATUS_ACTIVATED, 'availableExtMods' => Yii::$app->params['extMods'], 'serviceStartAt' => new \MongoDate()]; Account::updateAll($attributes, ['_id' => $accountId]); $salt = StringUtil::rndString(6); $password = User::encryptPassword(md5(Yii::$app->params['defaultPwd']), $salt); $user = new User(); $user->email = $email; $user->accountId = $accountId; $user->name = $name; $user->role = User::ROLE_ADMIN; $user->isActivated = User::ACTIVATED; $user->avatar = Yii::$app->params['defaultAvatar']; $user->language = Yii::$app->params['defaultLanguage']; $user->salt = $salt; $user->password = $password; if (!$user->save()) { Account::deleteAll(['_id' => $accountId]); SensitiveOperation::deleteAll(['accountId' => $accountId]); MessageTemplate::deleteAll(['accountId' => $accountId]); echo 'create account fail' . PHP_EOL; } else { echo 'create account successfully' . PHP_EOL; } }
/** * get sign package * @return array */ public function getSignPackage($channelId = null) { if (empty($channelId)) { $channelId = $this->channelId; } $jsapiTicket = $this->getTicket($channelId); $appId = $this->getAppId($channelId); // 注意 URL 一定要动态获取,不能 hardcode. if (empty($this->refererUrl)) { $url = $this->refererDomain . substr(Yii::$app->request->getUrl(), 1); } else { $url = $this->refererUrl; } LogUtil::info(['message' => 'get url', 'url' => $url], 'weixin'); $timestamp = time(); $nonceStr = StringUtil::rndString(16, StringUtil::ALL_DIGITS_LETTERS); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}"; $signature = sha1($string); $signPackage = array("appId" => $appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature); LogUtil::info(['message' => 'get signPackage', 'signPackage' => json_encode($signPackage)], 'weixin'); return $signPackage; }
/** * Activate a new user * * <b>Request Type</b>: POST<br/><br/> * <b>Request Endpoint</b>:http://{server-domain}/site/update-info<br/><br/> * <b>Content-type</b>: application/json<br/><br/> * <b>Summary</b>: This api is used for a user to activate account * <br/><br/> * * <b>Request Params</b>:<br/> * name: string, the user name, required<br/> * password: string, the user password, required<br/> * id: string, the user id, required<br/> * avatar: string, the user avatar, required<br/> * code: string, the user validation code, 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 user id<br/> * <br/><br/> * * <b>Request Example:</b><br/> * <pre> * { * "name" : "sarazhang", * "password" : "45345345gdfgdf", * "id" : "643hfjht567", * "avatar" : "http://www.baidu.com/1.jpg", * "code" : "543gfdg45745sd", * * } * </pre> * <br/><br/> * * <b>Response Example</b>:<br/> * <pre> * { * 'ack' : 1, * 'data': {"id": "5345gdfg45745"} * } * </pre> */ public function actionUpdateInfo() { $data = $this->getParams(); if (empty($data['password']) || empty($data['name']) || empty($data['id']) || $data['password'] === md5('')) { throw new BadRequestHttpException(Yii::t('common', 'parameters_missing')); } $code = empty($data['code']) ? '' : $data['code']; $type = empty($data['type']) ? '' : $data['type']; $result = Validation::validateCode($code, false); if ($result == Validation::LINK_INVALID) { throw new GoneHttpException(Yii::t('common', 'link_invalid')); } else { if ($result == Validation::LINK_EXPIRED) { throw new GoneHttpException(Yii::t('common', 'link_invalid')); } } $salt = StringUtil::rndString(6); $password = User::encryptPassword($data['password'], $salt); $name = $data['name']; $avatar = $data['avatar']; $id = $data['id']; if (!empty($type) && $type == self::ACCOUNT_INVITATION) { $user = User::findOne(['_id' => $id]); $accountId = $user->accountId; if (empty(User::getByName($accountId, $name))) { $user->isActivated = User::ACTIVATED; $user->salt = $salt; $user->language = Yii::$app->language; $user->password = $password; $user->name = $name; $user->avatar = $avatar; $flag = $user->save(); } else { throw new InvalidParameterException(['name' => Yii::t('common', 'name_exist')]); } } else { if (!empty($type) && $type == self::HELPDESK_INVITATION) { $helpDesk = HelpDesk::findOne(['_id' => $id]); $accountId = $helpDesk->accountId; if (empty(HelpDesk::getByName($accountId, $name))) { $helpDesk->isActivated = User::ACTIVATED; $helpDesk->language = Yii::$app->language; $helpDesk->salt = $salt; $helpDesk->password = $password; $helpDesk->name = $name; $helpDesk->avatar = $avatar; $flag = $helpDesk->save(); } else { throw new InvalidParameterException(['name' => Yii::t('common', 'name_exist')]); } } } if ($flag) { Validation::deleteAll(['code' => $code]); return ['id' => $id, 'type' => $type]; } throw new ServerErrorHttpException('activate fail'); }