PHP实现支付宝小程序发送模板消息的工具类

33次阅读

共计 43053 个字符,预计需要花费 108 分钟才能阅读完成。

背景
最近公司项目一直在围绕着支付宝做应用开发,为了能保证消息能够及时的给用户传递,因此需要开发模板消息的功能,而小程序的模板消息也是最快捷的通知方式
事先准备
1、请仔细阅读支付宝模板消息发送指引:模板消息指引 2、仔细阅读用户的授权文档,用户授权的详细的实现步骤可以见我写的另外一篇文章:《PHP 实现支付宝小程序用户授权的工具类》3、在小程序中加入模板消息的权限,如下图
4、仔细阅读支付宝发送模板消息接口文档:alipay.open.app.mini.templatemessage.send5、事先通过小程序的 form 组件收集好对一个的 formid,formid 组件文档 6、将小程序绑定到生活号上 7、配置一个模板消息编号,详细步骤:小程序 —> 模板消息,最终配置号的模板消息如下

实现流程
1、通过客户端的 form 组件,收集好 formid,并单独开一个后端接口将 formid 通过 http 请求保存到后台,最好是尽可能多的收集 formid,比如按钮的点击事件、tab 的切换上都可以增加 formid 组件 2、通过调用 alipay.open.app.mini.templatemessage.send 接口,给客户端发送模板消息,注意支付宝所有的模板消息都是基于生活号进行分发的,所以事先一定要绑定好对应的生活号
实现方法
相关常量
// 模板消息的接口方法名称
const API_METHOD_SEND_TPL_MSG = ‘alipay.open.app.mini.templatemessage.send’;
// 模板消息的结果返回节点名称
const RESPONSE_OUTER_NODE_SEND_TPL_MSG = ‘alipay_open_app_mini_templatemessage_send_response’;

入口方法
/**
* 发送小程序模板消息
* @param $formId
* @param $to 发送给用户的编号
* @param $tplId 模板编号
* @param $tplContent 模板内容
* @param $page 要跳转的页面
* @return array
*/
public static function sendAmpTplMsg($formId,$to,$tplId,$tplContent,$page = ”){
$param = self::getTplMsgBaseParam($formId,$to,$tplId,$tplContent,$page = ”);
$url = self::buildRequestUrl($param);
$response = self::getResponse($url,self::RESPONSE_OUTER_NODE_SEND_TPL_MSG);
return $response;
}
获取基础参数方法
/**
* 获取发送模板消息的接口参数
*/
protected static function getTplMsgBaseParam($formId,$to,$tplId,$tplContent,$page = ”){
$baseParam = [
‘to_user_id’ => $to,
‘form_id’ => $formId,
‘user_template_id’ => $tplId,
‘page’ => $page,
‘data’ => $tplContent,
];
$bizContent = json_encode($baseParam,JSON_UNESCAPED_UNICODE);
$busiParam = [
‘biz_content’ => $bizContent
];
$param = self::buildApiBuisinessParam($busiParam,self::API_METHOD_SEND_TPL_MSG);
return $param;
}

/**
* 构建业务参数
*/
protected static function buildApiBuisinessParam($businessParam,$apiMethod){
$pubParam = self::getApiPubParam($apiMethod);
$businessParam = array_merge($pubParam,$businessParam);
$signContent = self::getSignContent($businessParam);
error_log(‘sign_content ===========>’.$signContent);
$rsaHelper = new RsaHelper();
$sign = $rsaHelper->createSign($signContent);
error_log(‘sign ===========>’.$sign);
$businessParam[‘sign’] = $sign;
return $businessParam;
}

/**
* 公共参数
*
*/
protected static function getApiPubParam($apiMethod){
$ampBaseInfo = BusinessHelper::getAmpBaseInfo();
$param = [
‘timestamp’ => date(‘Y-m-d H:i:s’) ,
‘method’ => $apiMethod,
‘app_id’ => formatArrValue($ampBaseInfo,’appid’,config(‘param.amp.appid’)),
‘sign_type’ =>self::SIGN_TYPE_RSA2,
‘charset’ =>self::FILE_CHARSET_UTF8,
‘version’ =>self::VERSION,
];
return $param;
}

/**
* 获取签名的内容
*/
protected static function getSignContent($params) {
ksort($params);
$stringToBeSigned = “”;
$i = 0;
foreach ($params as $k => $v) {
if (!empty($v) && “@” != substr($v, 0, 1)) {
if ($i == 0) {
$stringToBeSigned .= “$k” . “=” . “$v”;
} else {
$stringToBeSigned .= “&” . “$k” . “=” . “$v”;
}
$i++;
}
}
unset ($k, $v);
return $stringToBeSigned;
}

/**
* 构建请求链接
*/
protected static function buildRequestUrl($param){
$paramStr = http_build_query($param);
return self::API_DOMAIN . $paramStr;
}

获取返回的结果值
/**
* 获取返回的数据,对返回的结果做进一步的封装和解析
*/
protected static function getResponse($url,$responseNode){
$json = curlRequest($url);
error_log(“result is =========>”.$json);
$response = json_decode($json,true);
$responseContent = formatArrValue($response,$responseNode,[]);
$errResponse = formatArrValue($response,self::RESPONSE_OUTER_NODE_ERROR_RESPONSE,[]);
if($errResponse){
return $errResponse;
}
return $responseContent;
}
返回结果
如果返回的节点 code 为 10000, 则表示消息发送
{
“alipay_open_app_mini_templatemessage_send_response”:{
“code”:”10000″,
“msg”:”Success”
}
,”sign”:”ERITJKEIJKJHKKKKKKKHJEREEEEEEEEEEE”
}

调用
$formId = ‘MjA4ODMwMjI2MjE4Mzc4MF8xNTQ2ODQ0MTUyNzU0XzA1NQ==’;
$openId = ‘2088302262183780’;
$tplId = ‘Mzc4OTk2ODU1YzM4NTI3NmY5ZjI2OTdhNGNkZDE2NGQ=’;
$content = [
‘keyword1’ => [
‘value’ => ‘ 您的朋友【】偷去了你的能量啦~’,
],
‘keyword2’ => [
‘value’ => ‘ 朋友偷能量提醒 ’,
],
‘keyword3’ => [
‘value’ => ‘ 点我查看详情 ’,
],
];
$result = AmpHelper::sendAmpTplMsg($formId,$openId,$tplId,$content,$page= ‘pages/index/index’);

效果图

附录:完整的工具类
<?php
/**
* Created by PhpStorm.
* User: Auser
* Date: 2017/7/13
* Time: 22:46
*/

namespace App\Http\Helper\Jz;

use App\Http\Helper\GuzzleHelper;
use App\Http\Helper\IdEncryptHelper;
use App\Http\Helper\LogHelper;
use App\Http\Helper\OpensslEncryptHelper;
use App\Http\Helper\TimeHelper;
use Illuminate\Support\Facades\Redis;
use phpDocumentor\Reflection\Types\Integer;
use SystemConfigService;
use WxaUserService;

class BusinessHelper{

const TOTAL_SCORE_MESURE_STEP = 100;
const WEIGHT_BASE_NUM = 1000;

const ERRCODE_SUCCESS = 200;
/**
* 生成 unionid
* @param int $uid 用户编号
* @param string $time 时间,格式为:2017-06-07
* @return string
*/
public static function generateHistoryUnionId($uid,$time){
return md5($uid.$time);
}

/**
* 获取评分比例
* {‘breakfast’:0.3,’lunch’:0.3,’supper’:0.4,’diet’:0.8,’sleep’:0.08,’weight’:0.02,’sport’:0.1}
*/
public static function getScoreEvaluationRate(){
$json = SystemconfigService::getValue(‘jz.score.evaluate.rule.rate’);
$rateData = json_decode($json,true);
return $rateData;
}

/**
* 获取睡眠时间规则
* {‘start’:’20:30:00′,’end’:’23:30:59′}
*/
public static function getSleepTimeRule($type,$time = null){
$json = SystemconfigService::getValue(‘jz.score.evaluate.rule.sleep.time’);
$data = json_decode($json,true);
$obj = [];
if($itemData = $data[$type]){
$now = time();
$time = $time ? $time : $now;
$day = date(‘Y-m-d’,$time);
// 开始时间
$start = $itemData[‘start’];
$stime = strtotime($day.’ ‘.$start);
// 结束时间段
$end = $itemData[‘end’];
$etime = strtotime($day.’ ‘.$end);
$obj = [
‘start’=>$stime,
‘end’=>$etime,
‘score’=>$itemData[‘score’],
];
}
return $obj;
}

/**
* 根据运动步数获取得分
* [{‘min’:0,’max’:5999,’score’:0},{‘min’:6000,’max’:6999,’score’:2},{‘min’:7000,’max’:7999,’score’:4},{‘min’:8000,’max’:8999,’score’:6},{‘min’:0000,’max’:9999,’score’:8},{‘min’:10000,’max’:100000,’score’:10}]
*/
public static function getSportScore($step){
$json = SystemconfigService::getValue(‘jz.score.evaluate.rule.sport.range’);
$data = json_decode($json,true);
$score = 0;
if($data){
foreach ($data as $item){
if($step>=$item[‘min’] && $step < $item[‘max’]){
$score = $item[‘score’];
break;
}
}
}
return [
‘score’ => $score* self::TOTAL_SCORE_MESURE_STEP
];
}

/**
* 获取饮水记录分数
*/
public static function getDrinkScore($cup,$drinkWaterRule = null){
$data = $drinkWaterRule?$drinkWaterRule:self::getDrinkWaterRule();
$score = 0;
if($data){
foreach ($data as $item){
if($cup>=$item[‘min’] && $cup <= $item[‘max’]){
$score = $item[‘score’];
break;
}
}
}
return [
‘score’ => $score* self::TOTAL_SCORE_MESURE_STEP
];
}

/**
* 获取睡眠打卡的评分
* @param $punchTime 睡眠打卡时间
* @return array
*/
public static function getSleepScore($punchTime){
$timeRule = self::getSleepTimeRule(‘sleep’,$punchTime);
$score = 0;
if($punchTime >= $timeRule[‘start’] && $punchTime <= $timeRule[‘end’]){
$score = $timeRule[‘score’];
}
return [
‘score’ => $score * self::TOTAL_SCORE_MESURE_STEP
];
}

/**
* 获取体重打卡的分数
* @param $punchTime 睡眠打卡时间
* @return array
*/
public static function getWeightPunchScore($punchTime){
$timeRule = self::getSleepTimeRule(‘weight’,$punchTime);
$score = 0;
if($punchTime >= $timeRule[‘start’] && $punchTime <= $timeRule[‘end’]){
$score = $timeRule[‘score’];
}
return [
‘score’ => $score * self::TOTAL_SCORE_MESURE_STEP,
];
}

/**
* 获取早起打卡的分数
* @param $punchTime 睡眠打卡时间
* @return array
*/
public static function getGetupPunchScore($punchTime){
$timeRule = self::getSleepTimeRule(‘getup’,$punchTime);
$score = 0;
if($punchTime >= $timeRule[‘start’] && $punchTime <= $timeRule[‘end’]){
$score = $timeRule[‘score’];
}
return [
‘score’ => $score * self::TOTAL_SCORE_MESURE_STEP,
];
}

/**
* 获取打卡成功后的提示鼓励西悉尼
*/
public static function getPunchSuccessHint($type,$punchTime){
$hint = ‘ 打卡成功 ’;
$types = [‘getup’,’sleep’,’weight’];
if(!in_array($type,$types)){
return $hint;
}
$itemRules = self::getItemRules($type);
if($itemRules){
foreach ($itemRules as $timeRule){
$startTime = self::formatHourTime($timeRule[‘start’]);
$endTime = self::formatHourTime($timeRule[‘end’]);
if($punchTime >= $startTime && $punchTime <= $endTime){
$hints = $timeRule[‘hint’];
$index = array_rand($hints);
$hint = $hints[$index];
break;
}
}
}
return $hint;

}

public static function canPunch($type){
$timeRule = self::getSleepTimeRule($type);
$time = time();
$flag = false;
if($time >= $timeRule[‘start’] && $time <= $timeRule[‘end’]){
$flag = true;
}
return $flag;

}

public static function getItemRules($type){
$json = SystemconfigService::getValue(‘jz.score.evaluate.rule.punch.success.hint’);
$hintRules = json_decode($json,true);
$itemRules = $hintRules[$type];
return $itemRules;
}

public static function formatHourTime($hourStr){
$today = date(‘Y-m-d’);
$timeStr = $today . ‘ ‘.$hourStr;
return strtotime($timeStr);
}

/**
* 获取规则描述部分
*/
public static function getRuleDescription(){
$json = SystemconfigService::getValue(‘jz.score.evaluate.rule.decription’);
$hintRules = json_decode($json,true);
$hintRules = $hintRules ? $hintRules : “”;
return $hintRules;
}

/**
* 获取小程序首页的咨询参数
*/
public static function getWxaHomeConsultParam(){
$json = SystemconfigService::getValue(‘jz.wxa.consult.param’);
$consultParam = json_decode($json,true);
$consultParam = $consultParam ? $consultParam : “”;
// 存储的是 %s/#/consult/page/%s 这个类型,需要进行动态的转换
$consultPage = $consultParam[‘consult_page’];
$frontendUrl = SystemconfigService::getValue(‘JZ.frontend.url’);
$currentPageIndex = $consultParam[‘current_page_index’];
$consultPage = sprintf($consultPage,$frontendUrl,$currentPageIndex);
$consultParam[‘consult_page’] = $consultPage;
// 助手的名字
$assistName = $consultParam[‘assist_name’];
$consultParam[‘text1’] = sprintf($consultParam[‘text1’],$assistName);
$uploadUrl = getUploadUrl();
$assisQrUrl = $uploadUrl . “jz/wxa/assist_qr/%s.jpg”;
$assisQrUrl = sprintf($assisQrUrl,$assistName);
$consultParam[‘assist_qr’] = $assisQrUrl;
return $consultParam;
}

/**
* 获取小程序首页的咨询参数
*/
public static function getH5HomeConsultParam(){
$json = SystemconfigService::getValue(‘jz.h5.consult.param’);
$consultParam = json_decode($json,true);
$consultParam = $consultParam ? $consultParam : “”;
// 存储的是 %s/#/consult/page/%s 这个类型,需要进行动态的转换
$consultPage = $consultParam[‘consult_page’];
$frontendUrl = SystemconfigService::getValue(‘JZ.frontend.url’);
$currentPageIndex = $consultParam[‘current_page_index’];
$consultPage = sprintf($consultPage,$frontendUrl,$currentPageIndex);
$consultParam[‘consult_page’] = $consultPage;
// 助手的名字
$assistName = $consultParam[‘assist_name’];
// 助手的名字
$assistName = $consultParam[‘assist_name’];
$consultParam[‘text1’] = sprintf($consultParam[‘text1’],$assistName);

$uploadUrl = getUploadUrl();
$assisQrUrl = $uploadUrl . “jz/wxa/assist_qr/%s.jpg”;
$assisQrUrl = sprintf($assisQrUrl,$assistName);
$consultParam[‘assist_qr’] = $assisQrUrl;
return $consultParam;
}

/**
* 构建带有业务参数的请求
* @param string $url 请求地址 形式为 http://domain/path?param=%s
* @param array $businessData 业务参数数组
* @return array
*/
public static function buildBusinessReq($url, $businessData = []){
$paramJson = json_encode($businessData);
$param = OpensslEncryptHelper::encryptWithOpenssl($paramJson);
$url = sprintf($url,$param);
$response = json_decode(curlRequest($url),true);
$result = [];
if($response[‘errcode’] == self::ERRCODE_SUCCESS){
$result = $response[‘data’];
} else {
LogHelper::warning(“ 同步测评异常 ”, $response);
}
$log = [
‘url’ => $url,
‘business_data’ => $businessData,
‘response’ => $response
];
error_log(“business api request result ========>”.json_encode($log));
return $result;
}

/**
* 获取 redis 的分页起始位置
*/
public static function getRedisOffset($page = 1,$page_size = 10){
$page = $page ? $page : 1;
$page_size = $page_size ? $page_size : 10;
$start = ($page – 1) * $page_size;
$end = $start + $page_size ;
$data = array(
‘start’ => $start,
‘end’ => $end
);
return $data;
}

/**
* 获取小程序的历史记录缓存 key
* @param $key redis 对应的 key
* @return string
*/
public static function getWxaZsetKey($key,$uid){
return getCacheKey(‘redis_key.cache_key.zset_list.’.$key).$uid;
}

/**
* 获取餐饮类型的 Mapping
* @return array
*/
public static function getMealTypeMapping(){
return [
‘breakfast’ => 1,
‘lunch’ => 2,
‘supper’ => 3,
//’breakfast_extra’ => 4,
//’lunch_extra’ => 5,
];
}

/**
* 根据餐饮的参数类型值获取参数类型
* @return array
*/
public static function getMealTypeReverseMapping(){
return [
1 => ‘breakfast’,
2 => ‘lunch’,
3 => ‘supper’,
//4 => ‘breakfast_extra’,
//5 => ‘lunch_extra’,
];
}

/**
* 获取餐类类型的 title mapping
* @return array
*/
public static function getMealTypeTitleMapping(){
return [
‘breakfast’ => ‘ 早餐 ’,
‘lunch’ => ‘ 午餐 ’,
‘supper’ => ‘ 晚餐 ’,
//’breakfast_extra’ => ‘ 早加餐 ’,
//’lunch_extra’ => ‘ 午加餐 ’,
];
}

public static function getMealTypeTitle(){
return [
1 => ‘ 早餐 ’,
2 => ‘ 午餐 ’,
3 => ‘ 晚餐 ’,
];
}

public static function getMealTypeCommentTitleMapping(){
return [
‘breakfast’ => ‘ 早餐评论:’,
‘lunch’ => ‘ 午餐评论:’,
‘supper’ => ‘ 晚餐评论:’,
‘1’ => ‘ 早餐评论:’,
‘2’ => ‘ 午餐评论:’,
‘3’ => ‘ 晚餐评论:’,
];
}

/**
* 获取餐饮类型的历史表中的字段 mapping
* @return array
*/
public static function getMealTypeHistoryColumnMapping(){
return [
‘breakfast’ => [
‘history_column’ => ‘breakfast_score’,
‘history_item_column’ => ‘breakfast_id’,
],
// ‘breakfast_extra’ => [
// ‘history_column’ => ‘breakfast_extra_score’,
// ‘history_item_column’ => ‘breakfast_extra_id’,
// ],
‘lunch’ => [
‘history_column’ => ‘lunch_score’,
‘history_item_column’ => ‘lunch_id’,
],
// ‘lunch_extra’ => [
// ‘history_column’ => ‘lunch_extra_score’,
// ‘history_item_column’ => ‘lunch_extra_id’,
// ],
‘supper’ => [
‘history_column’ => ‘supper_score’,
‘history_item_column’ => ‘supper_id’,
],
‘diet’ => [
‘history_column’ => ‘diet_score’,
‘history_item_column’ => ‘supper_id’,
],
];
}
/**
* 获取餐饮类型的历史表中的字段 mapping
* @return array
*/
public static function getSleepHistoryColumnMapping(){
return [
‘getup’ => [
‘history_column’ => ‘getup_time’,
‘history_item_column’ => ‘getup_id’,
],
‘weight’ => [
‘history_column’ => ‘body_weight’,
‘history_item_column’ => ‘weight_id’,
],
‘sleep’ => [
‘history_column’ => ‘sleep_time’,
‘history_item_column’ => ‘sleep_id’,
],
‘sport’ => [
‘history_column’ => ‘sport_step’,
‘history_item_column’ => ‘sport_id’,
],
];
}

/**
* 转换输入的日期类型的时间为时间戳
* @param $inputTime 输入的时间串,格式为 2017-07-18
* @return int
*/
public static function convertInputTime($inputTime){
$todayHour = date(‘H:i:s’);
$time = $inputTime.’ ‘.$todayHour;
return strtotime($time);
}

/**
* 获取打卡的成功的前缀
* @param type 类型
* @param $itemValue 类型值
* @return string
*/
public static function getPunchSuccessHintPrefix($type,$itemValue){
$json = SystemconfigService::getValue(‘jz.score.evaluate.rule.punch.success.prefix’);
$hintRules = json_decode($json,true);
$rule = $hintRules[$type];
return str_replace(‘_TIME_’,$itemValue,$rule);
}

/**
* 计算当存在历史记录数据时候各个项目对应的分数,此方法用户处理录入数据时候处理输入时候使用
* @param $historyData 历史记录数据
* @param $itemName 项目名称,分别有 breakfast,lunch,supper
* @param $itemValue 当 itemName 为 sleep,getup,weight 时候传入时间戳,当为 sport 时候传入步数,当为 breakfast,lunch,supper 时候传入分数
* @return Integer
*/
public static function calUpdateHistoryDataTotalScore($historyData, $itemName, $itemValue, $drinkWater = 0, $useNewDietRule = true){
if (in_array($itemName, [‘breakfast_extra’, ‘lunch_extra’])) {
return 0;
}
$measureStep = self::TOTAL_SCORE_MESURE_STEP;
$itemName = strtolower($itemName);
switch ($itemName){
case ‘breakfast’ :
$breakfastScore = $itemValue;
$lunchScore = $historyData[‘lunch_score’];
$supperScore = $historyData[‘supper_score’];
// 体重全天打卡都有用,时间段设置的也是全天
$weightScoreData = self::getExistHistoryDataWeightScore($historyData);
$stepScoreData = self::getSportScore($historyData[‘sport_step’]);
$sleepScoreData = self::getSleepScore($historyData[‘sleep_time’]);
$getupScoreData = self::getGetupPunchScore($historyData[‘getup_time’]);
$dietScore = $historyData[‘diet_score’];
$drinkScore = self::getDrinkScore($historyData[‘drink_water’]);
break;
case ‘lunch’ :
$breakfastScore = $historyData[‘breakfast_score’];
$lunchScore = $itemValue;
$supperScore = $historyData[‘supper_score’];
// 体重全天打卡都有用,时间段设置的也是全天
$weightScoreData = self::getExistHistoryDataWeightScore($historyData);
$stepScoreData = self::getSportScore($historyData[‘sport_step’]);
$sleepScoreData = self::getSleepScore($historyData[‘sleep_time’]);
$getupScoreData = self::getGetupPunchScore($historyData[‘getup_time’]);
$dietScore = $historyData[‘diet_score’];
$drinkScore = self::getDrinkScore($historyData[‘drink_water’]);
break;
case ‘supper’ :
$breakfastScore = $historyData[‘breakfast_score’];
$lunchScore = $historyData[‘lunch_score’];
$supperScore = $itemValue;
// 体重全天打卡都有用,时间段设置的也是全天
$weightScoreData = self::getExistHistoryDataWeightScore($historyData);
$stepScoreData = self::getSportScore($historyData[‘sport_step’]);
$sleepScoreData = self::getSleepScore($historyData[‘sleep_time’]);
$getupScoreData = self::getGetupPunchScore($historyData[‘getup_time’]);
$dietScore = $historyData[‘diet_score’];
$drinkWater = $drinkWater ? $drinkWater : 0;
$drinkScore = self::getDrinkScore($drinkWater);
break;
case ‘sleep’ :
$breakfastScore = $historyData[‘breakfast_score’];
$lunchScore = $historyData[‘lunch_score’];
$supperScore = $historyData[‘supper_score’];
// 体重全天打卡都有用,时间段设置的也是全天
$weightScoreData = self::getExistHistoryDataWeightScore($historyData);
$stepScoreData = self::getSportScore($historyData[‘sport_step’]);
$sleepScoreData = self::getSleepScore($itemValue);
$getupScoreData = self::getGetupPunchScore($historyData[‘getup_time’]);
$dietScore = $historyData[‘diet_score’];
$drinkScore = self::getDrinkScore($historyData[‘drink_water’]);
break;
case ‘getup’ :
$breakfastScore = $historyData[‘breakfast_score’];
$lunchScore = $historyData[‘lunch_score’];
$supperScore = $historyData[‘supper_score’];
// 体重全天打卡都有用,时间段设置的也是全天
$weightScoreData = self::getExistHistoryDataWeightScore($historyData);
$stepScoreData = self::getSportScore($historyData[‘sport_step’]);
$sleepScoreData = self::getSleepScore($historyData[‘sleep_time’]);
$getupScoreData = self::getGetupPunchScore($itemValue);
$dietScore = $historyData[‘diet_score’];
$drinkScore = self::getDrinkScore($historyData[‘drink_water’]);
break;
case ‘weight’ :
$breakfastScore = $historyData[‘breakfast_score’];
$lunchScore = $historyData[‘lunch_score’];
$supperScore = $historyData[‘supper_score’];
// 体重全天打卡都有用,时间段设置的也是全天
$weightScoreData = self::getWeightPunchScore(self::convertInputTime($historyData[‘record_time’]));
$stepScoreData = self::getSportScore($historyData[‘sport_step’]);
$sleepScoreData = self::getSleepScore($historyData[‘sleep_time’]);
$getupScoreData = self::getGetupPunchScore($historyData[‘getup_time’]);
$dietScore = $historyData[‘diet_score’];
$drinkScore = self::getDrinkScore($historyData[‘drink_water’]);
break;
case ‘sport’ :
$breakfastScore = $historyData[‘breakfast_score’];
$lunchScore = $historyData[‘lunch_score’];
$supperScore = $historyData[‘supper_score’];
// 体重全天打卡都有用,时间段设置的也是全天
$weightScoreData = self::getExistHistoryDataWeightScore($historyData);
$stepScoreData = self::getSportScore($itemValue);
$sleepScoreData = self::getSleepScore($historyData[‘sleep_time’]);
$getupScoreData = self::getGetupPunchScore($historyData[‘getup_time’]);
$dietScore = $historyData[‘diet_score’];
$drinkScore = self::getDrinkScore($historyData[‘drink_water’]);
break;
case ‘diet’ :
$breakfastScore = $historyData[‘breakfast_score’];
$lunchScore = $historyData[‘lunch_score’];
$supperScore = $historyData[‘supper_score’];
// 体重全天打卡都有用,时间段设置的也是全天
$weightScoreData = self::getExistHistoryDataWeightScore($historyData);
$stepScoreData = self::getSportScore($historyData[‘sport_step’]);
$sleepScoreData = self::getSleepScore($historyData[‘sleep_time’]);
$getupScoreData = self::getGetupPunchScore($historyData[‘getup_time’]);
$dietScore = $itemValue*100;
$drinkScore = self::getDrinkScore($historyData[‘drink_water’]);
break;

}
//{‘breakfast’:0.3,’lunch’:0.3,’supper’:0.4,’diet’:0.8,’sleep’:0.08,’weight’:0.02,’sport’:0.1}
$rates = self::getScoreEvaluationRate();
// 餐饮评分 由早中晚餐乘以各自的比例之后获取相应的
$threeTimeMealScore = ($breakfastScore * $rates[‘breakfast’] + $lunchScore * $rates[‘lunch’] + $supperScore * $rates[‘supper’]) * $rates[‘diet’] * self::TOTAL_SCORE_MESURE_STEP;
error_log(‘current item name =====================>’.$itemName);
error_log(‘current item value =====================>’.$itemValue);
// 兼容可以分三餐评论的逻辑
// $dietScore = $itemName == ‘diet’ ? $dietScore : $threeTimeMealScore;
$dietScore = $useNewDietRule ? $dietScore : $threeTimeMealScore;
// 因为数据库中总分存储的整形,所以插入的数据需要做转换
$totalScore = $drinkScore[‘score’] + $dietScore + $weightScoreData[‘score’] + $stepScoreData[‘score’] + $sleepScoreData[‘score’]+ $getupScoreData[‘score’];
return $totalScore;
}

/**
* 计算新增一条历史记录时候各个项目的总分
*/
public static function calNewHistoryDataTotalScore($itemName,$itemValue,$drinkWater = 0){
$measureStep = self::TOTAL_SCORE_MESURE_STEP;
$measureStep = 1;
$score = 0;
$itemName = strtolower($itemName);
switch ($itemName){
case ‘weight’ :
$punchTime = $itemValue > 0 ? time():0;
$result = self::getWeightPunchScore($punchTime);
$score = $result[‘score’] / $measureStep;
break;
case ‘sport’ :
$result = self::getSportScore($itemValue);
$score = $result[‘score’] / $measureStep;
break;
case ‘sleep’ :
$result = self::getSleepScore($itemValue);
$score = $result[‘score’] / $measureStep;
break;
case ‘getup’ :
$result = self::getGetupPunchScore($itemValue);
$score = $result[‘score’] / $measureStep;
break;
case ‘supper’ :
$result = self::getDrinkScore($drinkWater);
$score = $result[‘score’] / $measureStep;
break;
case ‘diet_score’ :
$score = $itemValue;
break;
default :
$score = 0;
break;
}

return $score;

}

/**
* 获取已存在的历史记录中体重的分数
* 根据录入的体重计算,当体重值大于 0 时候
*/
protected static function getExistHistoryDataWeightScore($historyData){
$currentHour = date(“H:i:s”);
return $historyData[‘body_weight’] > 0 ? self::getWeightPunchScore(self::convertInputTime($historyData[‘record_time’])): [‘score’ => 0];
}

/**
* 获取满分的规则
* {“summary”:{“actual_score”:0,”total_score”:150},”diet”:{“actual_score”:0,”total_score”:100},”sleep”:{“actual_score”:0,”total_score”:10},”sports”:{“actual_score”:0,”total_score”:30},”drink”:{“actual_score”:0,”total_score”:5},”weight”:{“actual_score”:0,”total_score”:5}}
*/
public static function getFullScoreRule(){
$json = SystemconfigService::getValue(‘jz.score.evaluate.rule.full.score’);
$data = json_decode($json,true);
return $data;
}

/**
* 获取两个日期中间所有的连续的日期
* @param $startDay 开始的日期
* @param $endDay 结束的日期
* @return array
*/
public static function calcContinuesDayList($startDay,$endDay){
$startTime = strtotime($startDay);
$endTime = strtotime($endDay);
$day = ($endTime – $startTime) / (60*60*24);
$list =[];
array_push($list , $startDay);
for ($i=1;$i<=$day;$i++){
$targetDay = date(‘Y-m-d’,strtotime(“+$i day”,$startTime));
if($targetDay == $endDay){
break;
}
array_push($list,$targetDay);
}
array_push($list , $endDay);
$list = array_unique($list);
return $list;
}

/** 订单状态
* @return array
*/
public static function getStatusDescribe(){
return [
1 => ‘ 未开始 ’,
// 2 => ‘ 进行中 ’,
3 => ‘ 中断 ’,
4 => ‘ 结束 ’,
5 => ‘ 失联 ’,
];
}

/**
* 获取远程异步实例
*/
public static function getAsynWeixinInstance(){
$workmanJsonRpcDir = config(‘param.workman_json_rpc_dir’);
$path = $workmanJsonRpcDir.’/Applications/JsonRpc/Clients/RpcClient.php’;
error_log(“path===============>”.$path);
include_once $path;
$address_array = array(‘tcp://0.0.0.0:23469’);
RpcClient::config($address_array);
$weixin = RpcClient::instance(‘Weixin’);
return $weixin;
}

/**
* 异步发送 http 请求
*/
public static function sendAsynRequest($url,$method = ‘get’,$params = [] ){
$client = self::getAsynWeixinInstance();
$params = [
‘url’ => $url,
‘params’ => $params,
‘method’ => $method,
];
$client->asend_sendAsynHttpRequest($params);
}

public static function batchSendRequest($urls){
$helper = new GuzzleHelper($urls);
$helper->batchRequest();
}

public static function formatBusinessData($businessData)
{
error_log(“business data is=============>”.json_encode($businessData));
if(!isset($businessData[‘wx_union_id’])){
return $businessData;
}

$unionId = $businessData[‘wx_union_id’];
if(!$unionId){
return $businessData;
}
// 处理 uid
$uid = WxaUserService::getJzUidByWxUnionId($unionId);
if(isset($businessData[‘uid’])){
$businessData[‘origin_uid’] = $businessData[‘uid’];
}
$businessData[‘uid’] = $uid;
return $businessData;
}

/**
* 获取服务类型的方案
* @param $serviceType 服务方案
* @param $mapping
* @return int
*/
public static function getServiceTypeCase($serviceType, $mapping =””){
$caseNo = 21;
$mapping =$mapping?$mapping:SystemconfigService::getValue(“JZ.admin.order.service.cycle”,””,false,true);
if($mapping){
foreach ($mapping as $item){
if($item[‘key’] == $serviceType){
$caseNo = $item[‘case_no’];
break;
}
}
}
return $caseNo;
}

/**
* 格式化特殊的方案组,因为很多方案都是以 7 的杯数为周期的
*/
public static function formatSpecialCaseNo($caseNo,$originMaxCaseNo){
$specialCaseNoArr = [
45 => [
‘max_case_no’ => 45
]
];
$specialCaseNos = array_keys($specialCaseNoArr);
if(in_array($caseNo,$specialCaseNos)){
$originMaxCaseNo = $specialCaseNoArr[$caseNo][‘max_case_no’];
}
return $originMaxCaseNo;
}

/**
* 获取有效的食谱周期
*/
public static function getValidCaseNo($serviceType){
$caseNo = self::getServiceTypeCase($serviceType);
$recipeDefaultParam = SystemConfigService::getValue(“jz.wxa.recipe.default.param”,””,false,true);
$maxRecipeDayIndex = isset($recipeDefaultParam[‘max_recipe_day_index’]) ? $recipeDefaultParam[‘max_recipe_day_index’] : 42;
$validRecipeCaseNos = isset($recipeDefaultParam[‘valid_recipe_case_no’]) ? $recipeDefaultParam[‘valid_recipe_case_no’] : [7,14,21,42];
$caseNo = in_array($caseNo,$validRecipeCaseNos)?$caseNo:$maxRecipeDayIndex;
return $caseNo;
}

/**
* 获取服务类型的方案
* @param $serviceType 服务方案
* @param $mapping
* @return integer
*/
public static function getServiceTypeName($serviceType,$mapping =””){
$serviceName = “21 天 ”;
$mapping = $mapping ? $mapping : SystemconfigService::getValue(“JZ.admin.order.service.cycle”,””,false,true);
if($mapping){
foreach ($mapping as $item){
if($item[‘key’] == $serviceType){
$serviceName = $item[‘value’];
break;
}
}
}
return $serviceName;
}

/**
* 获取客户端服务类型的方案
* @param $serviceType 服务方案
* @param $mapping
* @return string
*/
public static function getClientServiceTypeName($serviceType,$mapping =””){
$caseNo = 21;
$mapping = $mapping ? $mapping:SystemconfigService::getValue(“JZ.admin.order.service.cycle”,””,false,true);
if($mapping){
foreach ($mapping as $item){
if($item[‘key’] == $serviceType){
$caseNo = $item[‘case_no’];
break;
}
}
}
if ($caseNo > 28 && $caseNo % 7 == 0) {
return ($caseNo / 7) . ‘ 周 ’;
}
return $caseNo . ‘ 天 ’;
}

/**
* 获取服务类型列表参数
*/
public static function getServiceType(){
return SystemconfigService::getValue(“JZ.admin.order.service.cycle”,””,false,true);
}

/**
* 获取服务能量组
*/
public static function getServiceEnergyGroup(){
return SystemconfigService::getValue(“jz.wxa.order.servcie.energy”,[],false,true);
}

/**
* 活动的提示
*/
public static function getActivityTips()
{
return SystemconfigService::getValue(“jz.wxa.order.acitivity.tips”,””);
}

/**
* 获取服务时间的提示
*/
public static function getServiceTimeTips()
{
return SystemconfigService::getValue(“jz.wxa.order.change.service.time.tips”,””);
}

public static function getServiceEnergyGroupValues(){
$data = self::getServiceEnergyGroup();
return array_column($data,’key’);
}

/**
* 获取可用的内部角色编号
*/
public static function getValidInnerRoleIds(){
return SystemconfigService::getValue(“jz.wxa.recipe.valid.role”,[],false,true);
}

public static function getExpOrderNoteMapping()
{
return [
‘-1’ => ‘ 未开始 ’,
‘1’ => ‘ 未开始 ’,
‘2’ => ‘ 进行中 ’,
‘3’ => ‘ 已中断 ’,
‘4’ => ‘ 已结束 ’,
‘5’ => ‘ 已失联 ’,
];
}

/**
* 格式花天的显示
*/
public static function formatCurrentDay($currentDay){
$len = strlen($currentDay);
$str = $len > 1 ? $currentDay : ‘0’.$currentDay;
$str .= ‘ 天 ’;
return $str;
}

/**
* 获取运动规则
*/
public static function getSportRule(){
$rules = SystemconfigService::getValue(‘jz.score.evaluate.rule.sport.range’,[],false,true);
$contentList = [];
$maxStep = 10000;
foreach ($rules as $rule){
$min = isset($rule[‘min’]) ? $rule[‘min’] : 1;
$max = isset($rule[‘max’]) ? $rule[‘max’] : 1;
$max = $max + 1;
$min = $min+1;
$score = isset($rule[‘score’])?$rule[‘score’]:0;
if($min > $maxStep && $max > $maxStep){
$content = $maxStep . ‘ 步以上,30 分 ’;
}else{
$content = $min . ‘-‘ .$max . ‘ 步,’.$score.’ 分 ’;
}
array_push($contentList,$content);
}
$obj[‘content’] = $contentList;
return $obj;
}

public static function getDrinkWaterRule(){
return SystemconfigService::getValue(‘jz.score.evaluate.rule.drink.range’,[],false,true);

}

/**
* 获取活动参数 Mapping
*/
public static function getAcitivityParamMapping(){
return SystemconfigService::getValue(‘jz.activity.param.mapping’,[],false,true);
}

/**
* 获取随机食谱的缓存 key
*/
public static function getRandomRecipeCacheKey($uid,$energyGroup,$caseNo){
$cacheKey = getCacheKey(‘redis_key.cache_key.recipe_case.random_case’) . $uid.”_”.$energyGroup.”_”.$caseNo;
return $cacheKey;
}

/**
* 获取基础的业务参数
*/
public static function getBaseBusinessParam(){
return SystemconfigService::getValue(‘jz.base.business.param’,[],false,true);
}

/**
* 获取减脂营的渠道列表
* @param $convertObj 表示是否将列表转换成对象类型
* @return array
*/
public static function getCampChannel($convertObj = false){
$data = SystemconfigService::getValue(‘jz.camp.channel.list’,[],false,true);
if(!$convertObj){
return $data;
}
$obj = [];
if($data){
foreach ($data as $ch){
$obj[$ch[‘id’]] = $ch[‘channel_name’];
}
}
return $obj;
}

/**
* 获取减脂营排行的参数映射表
*/
public static function getCampRankKeyMapping(){
return [
‘health’ => ‘total_score’,
‘diet’ => ‘diet_score’,
‘getup’ => ‘getup_time’,
‘weight’ => ‘weight’,
];

}

/**
* 获取减脂营排行基础信息
*/
public static function getCampRankBaseInfo(){
return SystemconfigService::getValue(‘jz.camp.rank.base.info’,[],false,true);
}

/**
* 获取减脂营的结束时间
* @param $startTime 开始时间
* @return string
*/
public static function getCampEndTime($startTime){
$maxDay = SystemconfigService::getValue(‘jz.camp.max.day’,30);
return TimeHelper::getEndDayByDayAndDiff($startTime,$maxDay);
}

/**
* 获取代谢用户统一二维码的回调地址
*/
public static function getMetaCommonQrAuthBackUrl(){
return getDomain().”/wechat/meta/common/qr/auth/callback”;
}

/**
* 获取代谢用户匹配信息页面
*/
public static function getMetaUserMatchPage(){
$domain = self::getBackendDomain();
$path = SystemconfigService::getValue(‘jz.h5.meta.user.match.page’);
return $domain.$path;
}

/**
* 获取代谢用户匹配错误信息页面
*/
public static function getMetaUserMatchErrorPage(){
$domain = self::getBackendDomain();
$path = SystemconfigService::getValue(‘jz.h5.meta.user.match.error.page’);
return $domain.$path;
}
/**
* 获取代谢用户匹配错误信息页面
*/
public static function getMetaUserFinalQnPage(){
$domain = self::getBackendDomain();
$path = SystemconfigService::getValue(‘jz.h5.meta.user.qn.page’);
return $domain.$path;
}

/**
* 获取授权的公众号信息
*/
public static function getGhInfo(){
$authorGhInfo = SystemConfigService::getValue(‘JZ.admin.login.authorization.gh’,[],false,true);
return $authorGhInfo;
}

/**
* 获取单个微信公众号的 appid
*/
public static function getWxAppInfo($appid){
$mapping = self::getWxAppMapping();
return isset($mapping[$appid]) ? $mapping[$appid]:[];
}

/**
* 所有所有的微信 app 信息,包括小程序和公众号,主要用于生成公众号全局 token 使用
*/
public static function getWxAppMapping(){
return SystemConfigService::getValue(‘jz.wx.gh.mapping’,[],false,true);
}

/**
* 获取测评的域名
*/
public static function getQnDomain(){
$domain = SystemConfigService::getValue(‘JZ.admin.testing.base.url’);
return $domain;
}

/**
* 获取后台的域名
*/
public static function getBackendDomain(){
return SystemConfigService::getValue(‘JZ.frontend.url’);
}
/**
* 获取后台的域名
*/
public static function getMetaUserAutoIncreIndex(){
return SystemConfigService::get(‘jz.meta.user.auto.incre.index’);
}

/**
* 获取早起打卡小程序扫码的提示
*/
public static function getGetupScanTips(){
return SystemConfigService::getValue(‘getup.wxa.scan.tips’);
}

/**
* 获取代谢用户的测评地址
*/
public static function getMetaUserQnUrl($uid, $freeOrderId, $nutriId){
$qnDomain = self::getQnDomain();
$qnUrlPath = SystemConfigService::getValue(‘jz.h5.meta.user.qn.url.path’);
$url = $qnDomain .$qnUrlPath;
///quesdetail/try/AzY3d1PVWZ/%s?appid=%s&free_order_id=%s&nutritionist_id=%s
$ghInfo = self::getGhInfo();
$appid = base64_encode($ghInfo[‘appid’]);
$url = sprintf($url,$uid,$appid,$freeOrderId,$nutriId);
error_log(“scan common qrcode jump url=================>”.$uid.$url);
return $url;
}

/**
* 获取代谢测评编号
*/
public static function getMetaUserQnTid(){
$qnUrlPath = SystemConfigService::getValue(‘jz.h5.meta.user.qn.url.path’);
$data = explode(“/”,$qnUrlPath);
error_log(“qn url path ===================>”.$qnUrlPath);
$tidStr = $data[3];
$result = IdEncryptHelper::encryption($tidStr,’decode’);
$tid = $result ? $result[0] : 0;
return $tid;
}

/**
* 生成代谢系统自建的订单内部序号
* @param index 索引值
* @param $baseNum 基数
* @return string
*/
public static function generateMetaUserAutoIndex($index,$baseNum = 1000000){
$len = strlen($baseNum);
$newNum = $index + $baseNum;
$innerNo = “ZZ”.substr($newNum,1,$len); // 即截取掉最前面的“1”
return $innerNo;
}

/**
* 获取自动创建服务订单的负责人
*/
public static function getAutoCreateMetaUserPricipal(){
return SystemConfigService::getValue(“jz.meta.user.auto.create.principal”,367);
}

/**
* 获取通用二维码的测评跳转链接
*/
public static function getCommonQrRedirectUrl(){
$path = SystemConfigService::getValue(“jz.meta.user.common.qr.redirect.path”);
$url = getDomain().$path;
return $url;
}

/**
* 发送测评 api 请求,url 为 http://cptest.qiezilife.com/{$apiPath}?param=xxx 这种形式
* @param $apiPath apil 就
* @param $paramObj 参数列表
* @return array
*/
public static function sendQnApiRequest($apiPath,$paramObj){
$domain = SystemConfigService::getValue(“tesing_api_base_url”);
$url = $domain . $apiPath;
$paramJson = json_encode($paramObj);
$param = OpensslEncryptHelper::encryptWithOpenssl($paramJson);
$url = sprintf($url,$param);
error_log(“url=================>”.$url);
$response = curlRequest($url);
error_log(“response=================>”.$response);
$data = json_decode($response,true);
if($data[‘errcode’] == 200){
$result = $data[‘data’];
}else{
$result = [
‘errcode’ => $data[‘errcode’]
];
}
return $result;
}

/** 根据开始时间获取用户所有拼装数据
* @param $start
* @return array
*/
public static function togetherAllMealByTime($start){
$mealList = [];
$now = time();
$now_date = date(“Y-m-d”,$now);
$now_time = strtotime($now_date);
if(strtotime($start) !== $now_time){
$yesterday = date(“Y-m-d”,strtotime(“-1 day”));
$dateList = self::calcContinuesDayList($start , $yesterday);
if($dateList){
foreach($dateList as $k => $v){
for($i=1;$i<4;$i++){
array_push($mealList,$v.’_’.$i);
}
}
}
}
// 当天登录
if ($now_time + 65700 – $now < 0) {//18 点 15 之后登陆
array_push($mealList,$now_date.’_1′);
array_push($mealList,$now_date.’_2′);
array_push($mealList,$now_date.’_3′);
} elseif ($now_time + 50400 – $now < 0) {//14 点之后登陆
array_push($mealList,$now_date.’_1′);
array_push($mealList,$now_date.’_2′);
} elseif ($now_time + 32400 – $now < 0) {// 9 点之后登陆
array_push($mealList,$now_date.’_1′);
}
return $mealList;
}

/**
* 获取代谢二维码的图片的路径
* @param $imgType 图片的类型,有 common_qr,ticket_qr 等值
* @param $isImgLink 表示是否为图片链接, 否则为真实图片路径
* @return string
*/
public static function getCommonQrPath($imgType = ‘common_qr’, $isImgLink = false){
$validTypes = [‘common_qr’,’ticket_qr’];
$path = ”;
if(!in_array($imgType,$validTypes)){
return $path;
}
$basePath = $isImgLink ? getUploadUrl():getUploadDir();
$pathMapping = self::getCommonQrPathMapping();
$relativePath = $pathMapping[$imgType];
$path = $basePath.$relativePath;
return $path;

}

public static function getCommonQrPathMapping()
{
$backendPath = self::getBackendRelativePath();
return [
‘common_qr’ => $backendPath.’qrcode/meta/common/’,
‘ticket_qr’ => $backendPath.’qrcode/meta/ticket/’,
];
}

/**
* 获取准备日食谱的图片
*/
public static function getReadyDayRecipeImg(){
$prefix = getUploadUrl().self::getBackendRelativePath().’recipe/’;
$img = $prefix.’ready_recipe.jpg’;
return $img;
}

/**
* 获取 618 活动日的食谱图片
*/
public static function getActivityRecipeImage($isLink = false){
$basePath = $isLink ? getUploadUrl() : getUploadDir();
$prefix = $basePath.self::getBackendRelativePath().’recipe/’;
$img = $prefix.’activity_recipe.jpg’;
return $img;
}

/** 小打卡小程序码
* @return string
*/
public static function getGetUpQrcodeImage(){
$prefix = getUploadDir().self::getBackendRelativePath().’getup/qrcode/’;
$img = $prefix.’qrcode.jpg’;
return $img;
}

/**
* 获取后台资源文件的相对路径
*/
public static function getBackendRelativePath(){
return ‘jz/backend/’;
}

/**
* 获取前端域名
* @return mixed
*/
public static function getFrontDomain() {
return SystemConfigService::getValue(‘JZ.frontend.url’);
}

/**
* 获取用户自定义食谱的 union_id
*/
public static function getUserDiyRecipeUnionId($orderId, $caseNo, $serviceEnergy, $dayIndex){
$str = $orderId.$caseNo.$serviceEnergy.$dayIndex;
return md5($str);
}

/**
* 获取微信的带参数二维码的缓存 key
*/
public static function getWxQrTicketRedisKey(){
return self::getWxaZsetKey(‘wx_qr_ticket_list’,0);
}

/**
* 获取用户积分缓存列表的 redis 的 key
*/
public static function getUserCacheIntegralRedisKey($uid = 0){
$cacheKey = BusinessHelper::getWxaZsetKey(Constant::REDIS_ZSET_KEY_USER_CACHE_INTEGRAL_LIST,$uid);
return $cacheKey;
}

/**
* 获取微课的浏览量的 rediskey
*/
public static function getSeminarViewsRedisKey(){
$cacheKey = BusinessHelper::getWxaZsetKey(Constant::REDIS_ZSET_KEY_SEMINAR_VIEWS,”);
return $cacheKey;
}

public static function getPayOrderLockRedisKey(){
$cacheKey = BusinessHelper::getWxaZsetKey(Constant::REDIS_ZSET_KEY_PAY_ORDER_LOCK,”);
return $cacheKey;

}

/**
* 获取 pop 的 guide 显示的次数的 redis key
*/
public static function getPopGuideTimesRedisKey(){
$cacheKey = BusinessHelper::getWxaZsetKey(Constant::REDIS_ZSET_KEY_USER_POP_GUIDE,”);
return $cacheKey;
}

/**
* 获取微课指定的系列课编号
*/
public static function getWxaPointSeminarSeriesId(){
return SystemConfigService::getValue(‘jz.seminar.series.id’);
}

/**
* 获取课程信息相关的路径
*/
public static function getSeminarDataPath($seminarType = ‘banner’,$mapping = null){
$mapping = $mapping ? $mapping : self::getSeminarDataPathMapping();
return $mapping[$seminarType];
}

/**
* 获取课程数据的相关路径映射
*/
public static function getSeminarDataPathMapping($isUrl = true)
{
$backendPath = self::getBackendRelativePath();
$basePath = $isUrl ? getUploadUrl() : getUploadDir();
$backendPath = $basePath . $backendPath;
return [
‘seires_banner’ => $backendPath.’seminar/series/banner/’,
‘seminar_banner’ => $backendPath.’seminar/detail/banner/’,
‘seminar_thumbnail’ => $backendPath.’seminar/detail/thumbnail/’,
‘seminar_audio’ => $backendPath.’seminar/detail/audio/’,
‘top_banner’ => $backendPath.’seminar/detail/top_banner/’,
];
}

/**
* 获取课程顶部的 banner
*/
public static function getSeminarTopBanner(){
$relativePath = SystemConfigService::getValue(‘jz.seminar.top.banner’);
return getUploadUrl().$relativePath;
}

/**
* 获取周期对应的金额 mapping
*/
public static function getCaseNoMoneyMapping(){
return [
“3” => 99,
“5” => 219,
“7” => 199,
“14” => 699,
“21” => 999,
“84” => 3299,
“168” => 6599,
];
}

/**
* 获取微信关注的回复消息
* @return mixed
*/
public static function getWechatSubscribeReply() {
return SystemConfigService::getValue(‘jz.wechat.subscribe.reply’, ”);
}

/**
* 获取后台的资源文件路径,为了不去重复的写各种办法
*/
public static function getBackendResourcePath($type,$isUrl = false){
$mapping =self::getBackendResourcePathMapping($isUrl);
return formatArrValue($mapping,$type,”);
}

/**
* 获取后台资源路径的 mapping
*/
public static function getBackendResourcePathMapping($isUrl = false){
$backendPath = self::getBackendRelativePath();
$basePath = $isUrl ? getUploadUrl() : getUploadDir();
$backendPath = $basePath . $backendPath;
return [
Constant::RESOURCE_PATH_WECHAT_VERIFY => $backendPath.’verify_wechat/’,
Constant::RESOURCE_PATH_NUTRI_CARD => $backendPath.’nutri_card/’,
Constant::RESOURCE_PATH_EXCHANGE_GOODS => $backendPath.’exchange_goods/thumbnail/’,
Constant::RESOURCE_PATH_EXCHANGE_GOODS_CATE_ICON => $backendPath.’exchange_goods/cateicon/’,
Constant::RESOURCE_PATH_SHOP_GOODS => $backendPath.’shop_goods/detail/’
];
}

public static function getDefaultSkuPrice(){
return 0;
}

/**
* 获取奖品名称
* @return array
*/
public static function getPrizeTitle() {
return SystemConfigService::getValue(‘jz.order.prize.titles’, [], false, true);
}

/**
* 匹配订单形式
* @param $form
* @return int
*/
public static function mappingMktFormByValue($form){
// 获取
$key = 0;
$mkt = SystemconfigService::getValue(‘JZ.order.statistics.mkt.mapping’);
$mkt = json_decode($mkt,true);
foreach($mkt as $k => $v){
if($v[‘value’] == $form){
$key = $v[‘key’];
break;
}
}
return $key;
}

/**
* 获取一个团队 ID
* @return int
*/
public static function getUniqueManageId(){
$innerManager = json_decode(SystemconfigService::getValue(‘JZ.admin.inner.manager.ids’),true);
return $innerManager[‘inner_manager_id’];
}

/**
* 获取复购类型
* @return array
*/
public static function getRepurchaseType()
{
return SystemconfigService::getValue(‘JZ.admin.repurchase.type’, [], false, true);
}
/**
* 获取营养师的介绍模板
*/
public static function getNutriIntroduceTpl(){
return SystemConfigService::getValue(‘jz.wxa.readyday.nutri.introduce.tpl’);
}
/**
* 获取营养师在没有设置周期时候的的介绍模板
*/
public static function getNutriIntroduceWithoutCaseNoTpl(){
return SystemConfigService::getValue(‘jz.wxa.readyday.nutri.introduce.without.case.tpl’);
}

/**
* 获取运动的随机规则
*/
public static function getSportV2RandomRule(){
return SystemConfigService::getValue(‘jz.sport.v2.random.rule’, [], false, true);
}

/**
* 获取其他额外项目的加分项
*/
public static function getItemExtraIntegralMapping(){
return SystemConfigService::getValue(‘jz.item.extra.integral.mapping’, [], false, true);
}

public static function getSportNewVideoBaseUrl($type = ‘P1′){
$baseUrl = getSportVideoNewBaseUrl().$type.’/’;
return $baseUrl;
}

/**
* 获取用户订单带 key 的来源
* @return mixed
*/
public static function getUserOrderSource() {
return SystemconfigService::getValue(‘JZ.admin.user.order.source’, [], false, true);
}

/**
* 获取测评后端的 url
* @return mixed
*/
public static function getCpDomain()
{
return SystemConfigService::getValue(‘tesing_api_base_url’);
}

/**
* 获取食谱的默认参数
*/
public static function getRecipeDefaultParam() {
return SystemconfigService::getValue(‘jz.wxa.recipe.default.param’, [], false, true);
}

/**
* 获取开放的五维测评的 ID
* @return mixed
*/
public static function getFiveDimensionPublicId() {
return env(‘FIVE_DIMENSION_FREE_TID’, 92);
}

/**
* 获取私有的五维测评的 ID
* @return mixed
*/
public static function getFiveDimensionPrivateId() {
return env(‘FIVE_DIMENSION_PAY_TID’, 93);
}

/**
* 获取五维测评的 ID 数组
* @return mixed
*/
public static function getFiveDimensionIds() {
return [
env(‘FIVE_DIMENSION_FREE_TID’, 92),
env(‘FIVE_DIMENSION_PAY_TID’, 93)
];
}

/**
* 获取营销数据的参数选项
*/
public static function getMarketingDataParam() {
return SystemconfigService::getValue(‘jz.backend.marketing.data.param’, [], false, true);
}

public static function getIntegralTypeMapping(){
return SystemconfigService::getValue(‘jz.integral.type.mapping’, [], false, true);
}

/**
* 获取新的积分系统的发布日期
*/
public static function getIntegralCacheReleaseDate(){
return SystemconfigService::getValue(‘jz.integral.cache.release.date’);
}

/**
* 获取是否为新的积分系统的标志
*/
public static function getNewIntegralCacheFlag($time){
$releaseDayTime = self::getIntegralCacheReleaseDate();
return strtotime($time) < strtotime($releaseDayTime) ? false : true;
}

/**
* 获取减脂营周期和能量的映射
*/
public static function getCaseNoEnergyMapping()
{
return SystemconfigService::getValue(‘jz.backend.case_no.energy’, [], false, true);
}

public static function getExchangeGoodsCategory($convertObj = true){
$list = SystemconfigService::getValue(‘jz.exchange.goods.category’, [], false, true);
$list = sortArr($list,’sort’,’asc’);
$obj = [];
$basePath = self::getBackendResourcePath(Constant::RESOURCE_PATH_EXCHANGE_GOODS_CATE_ICON,true);
if($convertObj){
foreach ($list as $val){
$icon = $basePath.$val[‘icon’];
$val[‘icon’] = $icon;
$obj[$val[‘id’]] = $val;
}
}else{
foreach ($list as &$val){
$icon = $basePath.$val[‘icon’];
$val[‘icon’] = $icon;
$obj[$val[‘id’]] = $val;
}
}
return $convertObj ? $obj : $list;
}

/**
* 获取模板消息
*/
public static function getGhTplMsgInfo($type){
$info = SystemConfigService::getValue(‘jz.gh.tpl.msg.info’,[],false,true);
return formatArrValue($info,$type,[]);
}

/**
* 获取兑换商品的对应的提示
*/
public static function getExchangeGoodsTips($type){
$info = SystemConfigService::getValue(‘jz.exchange.goods.tips’,[],false,true);
return formatArrValue($info,$type,[]);
}

/**
* 获取购买平台信息
* @return mixed
*/
public static function getProductBuyPlatform(){
return SystemConfigService::getValue(‘jz.backend.buy.platform’, [], false, true);
}

/**
* 获取国华人寿的 h5 链接
* @return mixed
*/
public static function getGhInsuranceInfo() {
return SystemconfigService::getValue(‘jz.wxa.gh_insurance.info’, [], false, true);
}

/**
* 获取密钥存放配置
* @return mixed
*/
public static function getRsaKeyInfo() {
return SystemconfigService::getValue(‘jz.rpc.rsa_key.info’, [], false, true);
}

/**
* 获取赠险领取信息的文案
* @return mixed
*/
public static function getInsuranceCopyInfo() {
return SystemconfigService::getValue(‘jz.wxa.insurance.copy’, [], false, true);
}

/**
* 获取支付场景的 map,这个是为了区分不同的支付场景时候更新不同的业务字段,为了拓展进行的预留
*/
public static function getPaidSceneMapping(){
return [
Constant::PAID_SCENE_SEMINAR_ORDER => ‘0001’,
Constant::PAID_SCENE_SHOP_GOODS_ORDER => ‘0002’
];
}

/**
* 生成第三方支付的外部订单号
*/
public static function generateOutTradeNo($paidScene = Constant::PAID_SCENE_SEMINAR_ORDER){
$prefix = date(‘YmdHis’);
$paidSceneMap = self::getPaidSceneMapping();
$scene = formatArrValue($paidSceneMap,$paidScene,’0001′);
$suffix = generateRandomNum(10);
return $prefix.$scene.$suffix;
}

/**
* 获取微信小程序支付的配置信息
*/
public static function getWxaPayBaseInfo(){
$baseInfo = SystemConfigService::getValue(‘jz.wxa.pay.config’,[],false,true);
return $baseInfo;
}

/**
* 获取微信支付的相关信息
*/
public static function getWechatPayConfig(){
$baseInfo = self::getWxaPayBaseInfo();
$config = [
‘appid’ => $baseInfo[‘appid’],
‘mchid’ => $baseInfo[‘mchid’],
‘mch_secret’ => $baseInfo[‘mch_secret’],
‘notify_url’ => self::getWechatPayNotifyUrl(),
];
return $config;
}

public static function getWechatPayNotifyUrl(){
return str_replace(‘https’,’http’,getDomain()).’/wechat/pay/notify’;
}

/**
* 获取课程的浏览量的 hash key
*/
public static function getSeminarViewsCacheHashKey($id,$isSeries = true){
$prefix = $isSeries ? Constant::SEMINAR_VIEWS_CACHE_PREFIX_SERIES : Constant::SEMINAR_VIEWS_CACHE_PREFIX_SEMINAR;
return $prefix.$id;
}

/**
* 获取课程的基础描述 map
*/
public static function getSeminarBaseDescMapping(){
return [
‘paid_type’ => [
Constant::PAID_TYPE_INTEGRAL => ‘ 健康币支付 ’,
Constant::PAID_TYPE_WXPAY => ‘ 微信小程序支付 ’,
Constant::PAID_TYPE_MIXED => ‘ 微信小程序支付 + 健康币 ’,
],
‘paid_status’ => [
Constant::PAID_STATUS_SUCCESS => ‘ 支付成功 ’,
Constant::PAID_STATUS_CHECKED => ‘ 待支付 ’,
Constant::PAID_STATUS_FAIL => ‘ 支付失败 ’,
],
‘unit’ => [
Constant::PAID_TYPE_WXPAY => ‘¥’,
Constant::PAID_TYPE_INTEGRAL => ‘ 健康币 ’,
],
];
}

/**
* 获取微信小程序支付的配置信息
*/
public static function getPopGuideConfig(){
$baseInfo = SystemConfigService::getValue(‘jz.wxa.pop.guide.config’,[],false,true);
return $baseInfo;
}

/**
* 获取系列课程的周期对应的系列课编号的 mapping
*/
public static function getSeminarSeriesNotifyCaseMapping(){
$obj = SystemConfigService::getValue(‘jz.case.seminar.series.mapping’,[],false,true);
return $obj;
}

/**
* 获取用户已经购买了商品的提示
* @param $goodName 商品名称
* @param $nutriName 营养师名称
* @return string
*/
public static function getShopGoodsUserPaidTips($goodName,$nutriName,$paidTime){
$data = SystemConfigService::getValue(‘shop.goods.user.paid.tips’,[],false,true);
$tips = $data[‘tips’];
$showTimeDiff = formatArrValue($data,’show_tips_time_diff’,259200);
$now = time();
// 控制 tips 只能在
$diffTime = $now – $paidTime;
$tips = $diffTime > $showTimeDiff ? ” : sprintf($tips,$goodName,$nutriName);
return $tips;
}

/**
* 获取指定发送消息的公众号 openid
*/
public static function getPointSendMsgOpenids(){
$data = SystemConfigService::getValue(‘jz.point.send.msg.openids’,[],false,true);
return $data;
}

/**
* 获取维度测评 id 信息
* @return mixed
*/
public static function getDimensionTidInfo() {
return SystemConfigService::getValue(‘testing.dimension.tid.info’, [], false, true);
}
}

正文完
 0