Browse Source

add to local

root 9 years atrás
parent
commit
8dd2a857f7
55 changed files with 2864 additions and 635 deletions
  1. 57 3
      admin/control/cache.php
  2. 1 0
      admin/language/zh/cache.php
  3. 1 0
      admin/language/zh_cn/cache.php
  4. 5 0
      admin/templates/default/cache.clear.php
  5. 16 0
      core/framework/cache/cache.redis.php
  6. 133 102
      core/framework/libraries/sms.php
  7. 9 0
      crontab/control/hour.php
  8. 0 26
      crontab/control/testpush.php
  9. 934 0
      data/api/smsapi/yunpian/README.html
  10. 12 46
      data/api/smsapi/yunpian/Send.php
  11. 30 0
      data/api/smsapi/yunpian/YunpianAutoload.php
  12. 0 10
      data/api/smsapi/yunpian/config.inc.php
  13. 57 0
      data/api/smsapi/yunpian/config.php
  14. 26 0
      data/api/smsapi/yunpian/lib/ArrayToObject.php
  15. 95 0
      data/api/smsapi/yunpian/lib/EncryptUtil.php
  16. 54 0
      data/api/smsapi/yunpian/lib/FlowOperator.php
  17. 337 338
      data/api/smsapi/yunpian/lib/HttpClient.class.php
  18. 50 0
      data/api/smsapi/yunpian/lib/HttpUtil.php
  19. 35 0
      data/api/smsapi/yunpian/lib/Result.php
  20. 88 0
      data/api/smsapi/yunpian/lib/SmsOperator.php
  21. 304 0
      data/api/smsapi/yunpian/lib/TeaUtil.php
  22. 75 0
      data/api/smsapi/yunpian/lib/TplOperator.php
  23. 42 0
      data/api/smsapi/yunpian/lib/UserOperator.php
  24. 52 0
      data/api/smsapi/yunpian/lib/VoiceOperator.php
  25. 1 1
      data/logic/queue.logic.php
  26. 60 0
      data/model/bonus_type.model.php
  27. 10 0
      data/model/predeposit.model.php
  28. 23 0
      data/resource/mobile/bonus/css/common.css
  29. BIN
      data/resource/mobile/bonus/imgaes/icon_logo.png
  30. 0 0
      data/sales/home_goods.txt
  31. 22 21
      fooder.php
  32. 0 6
      helper/bonus/factory.php
  33. 36 5
      helper/bonus/generator.php
  34. 3 1
      helper/bonus/manager.php
  35. 7 3
      helper/bonus/type.php
  36. 4 3
      helper/bonus/user_bonus.php
  37. 46 0
      helper/configure.php
  38. 1 1
      helper/fcgi_server.php
  39. 26 6
      helper/kdn_helper.php
  40. 22 1
      helper/predeposit_helper.php
  41. 1 2
      request_helper.php
  42. 28 9
      helper/session.php
  43. 0 1
      helper/user_helper.php
  44. 15 6
      mobile/alipay_notify_url.php
  45. 7 5
      mobile/control/app_pay.php
  46. 72 15
      mobile/control/bonusex.php
  47. 2 2
      mobile/control/login.php
  48. 0 1
      mobile/control/member_feedback.php
  49. 1 1
      mobile/control/member_order.php
  50. 12 10
      mobile/dispatch_notify.php
  51. 3 3
      mobile/kdniao_notify.php
  52. 1 1
      mobile/templates/default/bonus/bind.php
  53. 32 0
      mobile/templates/default/bonus/end.php
  54. 8 1
      mobile/templates/default/bonus/open.php
  55. 8 5
      mobile/wxnotify.php

+ 57 - 3
admin/control/cache.php

@@ -21,15 +21,18 @@ class cacheControl extends SystemControl
         'circle_level',     // 圈子成员等级
         'area',             // 省市区地址
         'home_goods',       // 手机首页商品缓存
-        'bonus',            // 手机红包相关缓存
-        'specials',         // 手机专题活动相关缓存
-        'discovery',        // 手机发现页相关缓存
+        //'bonus',            // 手机红包相关缓存
+        //'specials',         // 手机专题活动相关缓存
+        //'discovery',        // 手机发现页相关缓存
     );
 
+    protected $cacher = '';
+
     public function __construct()
     {
         parent::__construct();
         Language::read('cache');
+        $this->cacher = Cache::getInstance('cacheredis');
     }
 
     /**
@@ -69,6 +72,19 @@ class cacheControl extends SystemControl
             // 首页
             Model('web_config')->getWebHtml('index', 1);
             delCacheFile('index');
+
+            // 删除商品相关数据
+            $this->del_keys('goods*');
+
+            // 删除手机红包相关缓存
+            $this->del_keys('bonus*');
+
+            //删除手机专题活动相关缓存
+            $this->del_keys('specials*');
+
+            //删除手机发现页相关缓存
+            $this->del_keys('discovery*');
+
         } else {
             $todo = (array) $_POST['cache'];
 
@@ -108,9 +124,47 @@ class cacheControl extends SystemControl
                 dkcache('area_toplevelareas');  // 省级别缓存处理
                 dkcache('area_cityprovince');   // 市级别缓存处理
             }
+
+            // 删除商品相关数据
+            if (in_array('goods',$todo)) {
+                $this->del_keys('goods*');
+            }
+
+            // 删除手机红包相关缓存
+            if (in_array('bonus',$todo)) {
+                $this->del_keys('bonus*');
+            }
+
+            // 删除手机专题活动相关缓存
+            if (in_array('specials',$todo)) {
+                $this->del_keys('specials*');
+            }
+
+            // 删除手机发现页相关缓存
+            if (in_array('discovery',$todo)) {
+                $this->del_keys('discovery*');
+            }
+
         }
 
         $this->log(L('cache_cls_operate'));
         showMessage($lang['cache_cls_ok']);
     }
+
+    /**
+     * 删除通配的keys
+     * @param $key
+     * @return bool
+     */
+    protected function del_keys($key) {
+        $keys = $this->cacher->keys($key);
+
+        if(!empty($keys) && is_array($keys)){
+            foreach($keys as $key) {
+                $this->cacher->del($key);
+            }
+        }
+
+        return true;
+    }
 }

+ 1 - 0
admin/language/zh/cache.php

@@ -22,4 +22,5 @@ $lang['cache_cls_home_goods']	= '手机首页商品缓存';
 $lang['cache_cls_bonus']	    = '手机红包相关缓存';
 $lang['cache_cls_specials']	    = '手机专题活动相关缓存';
 $lang['cache_cls_discovery']	= '手机发现页相关缓存';
+$lang['cache_cls_goods']	    = '商品相关缓存';
 $lang['cache_cls_ok']			= '更新成功';

+ 1 - 0
admin/language/zh_cn/cache.php

@@ -22,4 +22,5 @@ $lang['cache_cls_home_goods']	= '手机首页商品缓存';
 $lang['cache_cls_bonus']	    = '手机红包相关缓存';
 $lang['cache_cls_specials']	    = '手机专题活动相关缓存';
 $lang['cache_cls_discovery']	= '手机发现页相关缓存';
+$lang['cache_cls_goods']	    = '商品相关缓存';
 $lang['cache_cls_ok']			= '更新成功';

+ 5 - 0
admin/templates/default/cache.clear.php

@@ -116,6 +116,11 @@
                               <input type="checkbox" name="cache[]" id="specials" value="bonus" >
                               &nbsp;<?php echo $lang['cache_cls_specials']?></label>
                       </li>
+                          <li class="left w18pre">
+                              <label>
+                                  <input type="checkbox" name="cache[]" id="specials" value="goods" >
+                                  &nbsp;<?php echo $lang['cache_cls_goods']?></label>
+                          </li>
                       <li class="left w18pre">
                           <label>
                               <input type="checkbox" name="cache[]" id="discovery" value="discovery" >

+ 16 - 0
core/framework/cache/cache.redis.php

@@ -152,4 +152,20 @@ class CacheRedis extends Cache {
 	private function _key($str) {
 		return $this->prefix.$this->type.$str;
 	}
+
+    public function keys($key = '') {
+        $this->init_master();
+
+        if(!isset($key) || empty($key)) {
+            $key = '*';
+        }
+
+        return $this->handler->keys($this->_key($key));
+    }
+
+    public function del($key){
+        $this->init_master();
+        if (!$this->enable) return false;
+        return $this->handler->delete($key);
+    }
 }

+ 133 - 102
core/framework/libraries/sms.php

@@ -10,69 +10,69 @@ defined('InShopNC') or exit('Access Invalid!');
 
 class Sms
 {
-	const register_code = 1;
-	const resetpass_code = 2;
-	const getbonus_code = 3;
-	const getbind_code = 4;
+    const register_code = 1;
+    const resetpass_code = 2;
+    const getbonus_code = 3;
+    const getbind_code = 4;
 
     /*
      * 发送手机短信
      * @param unknown $mobile 手机号
      * @param unknown $content 短信内容
     */
-    public function send($mobile,$content) 
+    public function send($mobile, $content)
     {
-		$mobile_host_type=C('mobile_host_type');
-		if($mobile_host_type == 1) {
-			return $this->mysend_smsbao($mobile,$content);
-		}
-		elseif($mobile_host_type == 2) {
-			return $this->mysend_yunpian($mobile,$content);
-		}
-        elseif($mobile_host_type == 3) {
-            return $this->mysend_yuntx($mobile,$content);
+        $mobile_host_type = C('mobile_host_type');
+        if ($mobile_host_type == 1) {
+            return $this->mysend_smsbao($mobile, $content);
+        } elseif ($mobile_host_type == 2) {
+            return $this->mysend_yunpian($mobile, $content);
+        } elseif ($mobile_host_type == 3) {
+            return $this->mysend_yuntx($mobile, $content);
+        } elseif ($mobile_host_type == 4) {
+            $this->send_yunpian($mobile, $content);
         }
     }
 
-    public function send_msg($mobile,$code,$type,$extime='5')
+    public function send_msg($mobile, $code, $type, $extime = '5')
     {
-		Log::record("SMS send:{$mobile} {$code} {$type}",Log::DEBUG);
-    	$folder = 'yuntx';
-    	$plugin = str_replace('\\', '', str_replace('/', '', str_replace('.', '', $folder)));
-    	if (!empty($plugin)) {
-    	    define('PLUGIN_ROOT', BASE_DATA_PATH . DS . 'api/smsapi');
+        Log::record("SMS send:{$mobile} {$code} {$type}", Log::DEBUG);
+        $folder = 'yuntx';
+        $plugin = str_replace('\\', '', str_replace('/', '', str_replace('.', '', $folder)));
+        if (!empty($plugin)) {
+            define('PLUGIN_ROOT', BASE_DATA_PATH . DS . 'api/smsapi');
             require_once(PLUGIN_ROOT . DS . $plugin . DS . 'CCPRestSDK.php');
-    	    require_once(PLUGIN_ROOT . DS . $plugin . DS . 'SendSMS.php');
+            require_once(PLUGIN_ROOT . DS . $plugin . DS . 'SendSMS.php');
 
-    	    return sendSMS($mobile, array($code,$extime),$type);
-    	} else {
-    	    return -1;
-    	}
+            return sendSMS($mobile, array($code, $extime), $type);
+        } else {
+            return -1;
+        }
     }
-    
-   /*
-	您于{$send_time}绑定手机号,验证码是:{$verify_code}。【{$site_name}】
-	0  提交成功
-	30:密码错误
-	40:账号不存在
-	41:余额不足
-	42:帐号过期
-	43:IP地址限制
-	50:内容含有敏感词
-	51:手机号码不正确
-	http://api.smsbao.com/sms?u=USERNAME&p=PASSWORD&m=PHONE&c=CONTENT
-	*/
+
+    /*
+     您于{$send_time}绑定手机号,验证码是:{$verify_code}。【{$site_name}】
+     0  提交成功
+     30:密码错误
+     40:账号不存在
+     41:余额不足
+     42:帐号过期
+     43:IP地址限制
+     50:内容含有敏感词
+     51:手机号码不正确
+     http://api.smsbao.com/sms?u=USERNAME&p=PASSWORD&m=PHONE&c=CONTENT
+     */
     private function mysend_yuntx($mobile, $content)
     {
         $code = $content['code'];
         $time = $content['time'];
         $type = intval($content['type']);
 
-		static $templates = array(self::register_code => '59006',self::resetpass_code => '63477', self::getbonus_code => '63479',self::getbind_code => '59006');
-		if(!array_key_exists($type,$templates)) return -1;
+        static $templates = array(self::register_code => '59006', self::resetpass_code => '63477', self::getbonus_code => '63479', self::getbind_code => '59006');
+        if (!array_key_exists($type, $templates)) return -1;
 
-        return $this->send_msg($mobile,$code,$templates[$type],$time);
-	}
+        return $this->send_msg($mobile, $code, $templates[$type], $time);
+    }
 
     /*
 	您于{$send_time}绑定手机号,验证码是:{$verify_code}。【{$site_name}】
@@ -86,75 +86,106 @@ class Sms
 	51:手机号码不正确
 	http://api.smsbao.com/sms?u=USERNAME&p=PASSWORD&m=PHONE&c=CONTENT
 	*/
-    private function mysend_smsbao($mobile,$content)
-    {     
-	   $user_id = urlencode(C('mobile_username')); // 这里填写用户名
- 	   $pass = urlencode(C('mobile_pwd')); // 这里填登陆密码
- 	   if(!$mobile || !$content || !$user_id || !$pass) return false;
-	   if(is_array($mobile)) $mobile = implode(",",$mobile);
-       $mobile=urlencode($mobile);
-       //$content=$content."【我的网站】";
-       $content=urlencode($content);
-	   $pass =md5($pass);//MD5加密
-	   $url="http://api.smsbao.com/sms?u=".$user_id."&p=".$pass."&m=".$mobile."&c=".$content."";
- 	   $res = file_get_contents($url);
- 	   //return $res;
- 	   $ok=$res=="0";
- 	   if($ok) {
- 	     return true;
- 	   }
- 	   return false;
+    private function mysend_smsbao($mobile, $content)
+    {
+        $user_id = urlencode(C('mobile_username')); // 这里填写用户名
+        $pass = urlencode(C('mobile_pwd')); // 这里填登陆密码
+        if (!$mobile || !$content || !$user_id || !$pass) return false;
+        if (is_array($mobile)) $mobile = implode(",", $mobile);
+        $mobile = urlencode($mobile);
+        //$content=$content."【我的网站】";
+        $content = urlencode($content);
+        $pass = md5($pass);//MD5加密
+        $url = "http://api.smsbao.com/sms?u=" . $user_id . "&p=" . $pass . "&m=" . $mobile . "&c=" . $content . "";
+        $res = file_get_contents($url);
+        //return $res;
+        $ok = $res == "0";
+        if ($ok) {
+            return true;
+        }
+        return false;
 
     }
-	 /**
-	 * http://www.yunpian.com/
+
+    /**
+     * http://www.yunpian.com/
      * 发送手机短信
      * @param unknown $mobile 手机号
      * @param unknown $content 短信内容
-	  0 	OK 	调用成功,该值为null 	无需处理
-	  1 	请求参数缺失 	补充必须传入的参数 	开发者
-	  2 	请求参数格式错误 	按提示修改参数值的格式 	开发者
-	  3 	账户余额不足 	账户需要充值,请充值后重试 	开发者
-	  4 	关键词屏蔽 	关键词屏蔽,修改关键词后重试 	开发者
-	  5 	未找到对应id的模板 	模板id不存在或者已经删除 	开发者
-	  6 	添加模板失败 	模板有一定的规范,按失败提示修改 	开发者
-	  7 	模板不可用 	审核状态的模板和审核未通过的模板不可用 	开发者
-	  8 	同一手机号30秒内重复提交相同的内容 	请检查是否同一手机号在30秒内重复提交相同的内容 	开发者
-	  9 	同一手机号5分钟内重复提交相同的内容超过3次 	为避免重复发送骚扰用户,同一手机号5分钟内相同内容最多允许发3次 	开发者
-	  10 	手机号黑名单过滤 	手机号在黑名单列表中(你可以把不想发送的手机号添加到黑名单列表) 	开发者
-	  11 	接口不支持GET方式调用 	接口不支持GET方式调用,请按提示或者文档说明的方法调用,一般为POST 	开发者
-	  12 	接口不支持POST方式调用 	接口不支持POST方式调用,请按提示或者文档说明的方法调用,一般为GET 	开发者
-	  13 	营销短信暂停发送 	由于运营商管制,营销短信暂时不能发送 	开发者
-	  14 	解码失败 	请确认内容编码是否设置正确 	开发者
-	  15 	签名不匹配 	短信签名与预设的固定签名不匹配 	开发者
-	  16 	签名格式不正确 	短信内容不能包含多个签名【 】符号 	开发者
-	  17 	24小时内同一手机号发送次数超过限制 	请检查程序是否有异常或者系统是否被恶意攻击 	开发者
-	  -1 	非法的apikey 	apikey不正确或没有授权 	开发者
-	  -2 	API没有权限 	用户没有对应的API权限 	开发者
-	  -3 	IP没有权限 	访问IP不在白名单之内,可在后台"账户设置->IP白名单设置"里添加该IP 	开发者
-	  -4 	访问次数超限 	调整访问频率或者申请更高的调用量 	开发者
-	  -5 	访问频率超限 	短期内访问过于频繁,请降低访问频率 	开发者
-	  -50 未知异常 	系统出现未知的异常情况 	技术支持
-	  -51 系统繁忙 	系统繁忙,请稍后重试 	技术支持
-	  -52 充值失败 	充值时系统出错 	技术支持
-	  -53 提交短信失败 	提交短信时系统出错 	技术支持
-	  -54 记录已存在 	常见于插入键值已存在的记录 	技术支持
-	  -55 记录不存在 	没有找到预期中的数据 	技术支持
-	  -57 用户开通过固定签名功能,但签名未设置 	联系客服或技术支持设置固定签名 	技术支持
+     * 0    OK    调用成功,该值为null    无需处理
+     * 1    请求参数缺失    补充必须传入的参数    开发者
+     * 2    请求参数格式错误    按提示修改参数值的格式    开发者
+     * 3    账户余额不足    账户需要充值,请充值后重试    开发者
+     * 4    关键词屏蔽    关键词屏蔽,修改关键词后重试    开发者
+     * 5    未找到对应id的模板    模板id不存在或者已经删除    开发者
+     * 6    添加模板失败    模板有一定的规范,按失败提示修改    开发者
+     * 7    模板不可用    审核状态的模板和审核未通过的模板不可用    开发者
+     * 8    同一手机号30秒内重复提交相同的内容    请检查是否同一手机号在30秒内重复提交相同的内容    开发者
+     * 9    同一手机号5分钟内重复提交相同的内容超过3次    为避免重复发送骚扰用户,同一手机号5分钟内相同内容最多允许发3次    开发者
+     * 10    手机号黑名单过滤    手机号在黑名单列表中(你可以把不想发送的手机号添加到黑名单列表)    开发者
+     * 11    接口不支持GET方式调用    接口不支持GET方式调用,请按提示或者文档说明的方法调用,一般为POST    开发者
+     * 12    接口不支持POST方式调用    接口不支持POST方式调用,请按提示或者文档说明的方法调用,一般为GET    开发者
+     * 13    营销短信暂停发送    由于运营商管制,营销短信暂时不能发送    开发者
+     * 14    解码失败    请确认内容编码是否设置正确    开发者
+     * 15    签名不匹配    短信签名与预设的固定签名不匹配    开发者
+     * 16    签名格式不正确    短信内容不能包含多个签名【 】符号    开发者
+     * 17    24小时内同一手机号发送次数超过限制    请检查程序是否有异常或者系统是否被恶意攻击    开发者
+     * -1    非法的apikey    apikey不正确或没有授权    开发者
+     * -2    API没有权限    用户没有对应的API权限    开发者
+     * -3    IP没有权限    访问IP不在白名单之内,可在后台"账户设置->IP白名单设置"里添加该IP    开发者
+     * -4    访问次数超限    调整访问频率或者申请更高的调用量    开发者
+     * -5    访问频率超限    短期内访问过于频繁,请降低访问频率    开发者
+     * -50 未知异常    系统出现未知的异常情况    技术支持
+     * -51 系统繁忙    系统繁忙,请稍后重试    技术支持
+     * -52 充值失败    充值时系统出错    技术支持
+     * -53 提交短信失败    提交短信时系统出错    技术支持
+     * -54 记录已存在    常见于插入键值已存在的记录    技术支持
+     * -55 记录不存在    没有找到预期中的数据    技术支持
+     * -57 用户开通过固定签名功能,但签名未设置    联系客服或技术支持设置固定签名    技术支持
+     * @return bool|string
      */
-    private function mysend_yunpian($mobile,$content) {
-		$yunpian='yunpian';
-		$plugin = str_replace('\\', '', str_replace('/', '', str_replace('.', '',$yunpian)));
+    private function mysend_yunpian($mobile, $content)
+    {
+        $yunpian = 'yunpian';
+        $plugin = str_replace('\\', '', str_replace('/', '', str_replace('.', '', $yunpian)));
         if (!empty($plugin)) {
-            define('PLUGIN_ROOT', BASE_DATA_PATH . DS .'api/smsapi');
+            define('PLUGIN_ROOT', BASE_DATA_PATH . DS . 'api/smsapi');
             require_once(PLUGIN_ROOT . DS . $plugin . DS . 'Send.php');
             return send_sms($content, $mobile);
+        } else {
+            return false;
         }
-		else
-		{
-			return false;
-		}
     }
-	
-   
+
+    protected function send_yunpian($mobile, $content)
+    {
+        $code = $content['code'];
+        //$time = $content['time'];
+        $type = intval($content['type']);
+
+        static $templates = array(self::register_code => '1382929', self::resetpass_code => '1386969', self::getbonus_code => '1386979', self::getbind_code => '1382929');
+        if (!array_key_exists($type, $templates)) return -1;
+
+        return $this->tpl_send_sms($mobile, $code, $templates[$type]);
+    }
+
+
+    protected function tpl_send_sms($mobile, $tpl_value, $tpl_id)
+    {
+        $yunpian = 'yunpian';
+        $plugin = str_replace('\\', '', str_replace('/', '', str_replace('.', '', $yunpian)));
+        Log::record("SMS yunpian send:{$mobile} {$tpl_value} {$tpl_id}", Log::DEBUG);
+
+        if (!empty($plugin)) {
+            $plugin_root = BASE_DATA_PATH . DS . 'api/smsapi';
+            require_once($plugin_root . DS . $plugin . DS . 'Send.php');
+
+            return tpl_send_sms($tpl_id, $tpl_value, $mobile);
+        } else {
+
+            return false;
+        }
+    }
+
+
 }

+ 9 - 0
crontab/control/hour.php

@@ -240,4 +240,13 @@ class hourControl extends BaseCronControl {
             }
         }
     }
+
+    /**
+     * 定时释放红包
+     */
+    public function releaseBonusOp()
+    {
+        $bonus_type = Model('bonus_type');
+        $bonus_type->bonus_refund();
+    }
 }

+ 0 - 26
crontab/control/testpush.php

@@ -1,26 +0,0 @@
-<?php
-/**
- * Created by PhpStorm.
- * User: zry
- * Date: 2016/5/9
- * Time: 12:55
- */
-defined('InShopNC') or exit('Access Invalid!');
-ini_set('default_socket_timeout', -1);
-
-class testpushControl extends BaseCronControl
-{
-
-    public function indexOp() {
-        if (ob_get_level()) ob_end_clean();
-
-        $param = array(
-            'member_id'=>'36489',
-            'text'     =>'Helloworld',
-            'go_type'  =>'bonus',
-        );
-
-        QueueClient::push('upushSendMsg',$param);
-
-    }
-}

File diff suppressed because it is too large
+ 934 - 0
data/api/smsapi/yunpian/README.html


+ 12 - 46
data/api/smsapi/yunpian/Send.php

@@ -1,66 +1,32 @@
 <?php
 defined('InShopNC') or exit('Access Invalid!');
-
-require_once(dirname(__FILE__) . DS . 'lib/HttpClient.class.php');
-require_once(dirname(__FILE__) . DS . 'config.inc.php');
-
-$GLOBALS['sms_options'] = $options;
+require_once(dirname(__FILE__) . DS . 'YunpianAutoload.php');
 
 /**
 * 模板接口发短信
-* apikey 为云片分配的apikey
 * tpl_id 为模板id
 * tpl_value 为模板值
 * mobile 为接收短信的手机号
 */
 function tpl_send_sms($tpl_id, $tpl_value, $mobile){
-	$path = "/v1/sms/tpl_send.json";
-	return Send::sendSms($path, $GLOBALS['sms_options']['apikey'], $mobile, $tpl_id, $tpl_value);
+	$smsOperator = new SmsOperator();
+	$data['mobile'] = $mobile;
+    $data['tpl_id'] = $tpl_id;
+	$data['tpl_value'] = urlencode("#code#") . "=" . urlencode($tpl_value) ;
+
+	return $smsOperator->tpl_send($data);
 }
 
 /**
 * 普通接口发短信
-* apikey 为云片分配的apikey
-* text 为短信内容
+* content 为短信内容
 * mobile 为接收短信的手机号
 */
 function send_sms($content, $mobile){
-	$path = "/v1/sms/send.json";
-	return Send::sendSms($path, $GLOBALS['sms_options']['apikey'], str_replace(C('site_name'), $GLOBALS['sms_options']['signature'], $content), $mobile);
-}
+	$smsOperator = new SmsOperator();
+	$data['mobile'] = $mobile;
+	$data['text'] = $content;
 
-class Send {
-
-	const HOST = 'yunpian.com';
-
-	final private static function __replyResult($jsonStr) {
-		//header("Content-type: text/html; charset=utf-8");
-		$result = json_decode($jsonStr);
-		if ($result->code == 0) {
-			$data['state'] = 'true';
-			return ture;
-		} else {
-			$data['state'] = 'false';
-			$data['msg'] = $result->msg;
-			return false;
-		}
-	}
-
-	final public static function sendSms($path, $apikey, $encoded_text, $mobile, $tpl_id = '', $encoded_tpl_value = '') {
-		$client = new HttpClient(self::HOST);
-		$client->setDebug(false);
-		if (!$client->post($path, array (
-				'apikey' 		=> $apikey,
-				'text' 			=> $encoded_text,
-				'mobile' 		=> $mobile,
-				'tpl_id' 		=> $tpl_id,
-				'tpl_value' 	=> $encoded_tpl_value
-		))) {
-			return '-10000';
-		} else {
-			return self::__replyResult($client->getContent());
-		}
-	}
+	return $smsOperator->single_send($data);
 }
-
 ?>

+ 30 - 0
data/api/smsapi/yunpian/YunpianAutoload.php

@@ -0,0 +1,30 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: bingone
+ * Date: 16/1/20
+ * Time: 上午10:20
+ */
+require_once(dirname(__FILE__) . DS . 'config.php');
+function YAutoload($classname)
+{
+    $filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lib/'. $classname . '.php';
+    echo $filename;
+    if (is_readable($filename)) {
+        require $filename;
+    }
+}
+
+if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
+    if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
+        spl_autoload_register('YAutoload', true, true);
+    } else {
+        spl_autoload_register('YAutoload');
+    }
+} else {
+    function __autoload($classname)
+    {
+        YAutoload($classname);
+    }
+}
+?>

+ 0 - 10
data/api/smsapi/yunpian/config.inc.php

@@ -1,10 +0,0 @@
-<?php
-defined('InShopNC') or exit('Access Invalid!');
-/*
- * 配置文件 好商城V3
- */
-$options = array();
-$options['apikey'] = C('mobile_key'); //apikey
-$options['signature'] =  C('mobile_signature'); //签名
-return $options;
-?>

+ 57 - 0
data/api/smsapi/yunpian/config.php

@@ -0,0 +1,57 @@
+<?php
+/*
+ * config file
+ */
+//You can get the APIKEY and APISECRET from http://www.yunpian.com/ when log on.
+
+$yunpian_config = array();
+$yunpian_config['APIKEY'] = "ec9c15640fe9997720c70b1ad828fa49";
+
+// php sdk 暂不支持加密算法
+$yunpian_config['API_SECRET'] = "229d68d3";
+
+//System
+$yunpian_config['SMS_HOST'] = 'https://sms.yunpian.com';
+$yunpian_config['VOICE_HOST'] = 'https://voice.yunpian.com';
+$yunpian_config['FLOW_HOST'] = 'https://flow.yunpian.com';
+$yunpian_config['VERSION'] = '/v1';
+
+// retry times
+$yunpian_config['RETRY_TIMES'] = 3;
+// 短信
+$yunpian_config['URI_SEND_SINGLE_SMS'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/sms/single_send.json";
+$yunpian_config['URI_SEND_BATCH_SMS'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/sms/batch_send.json";
+$yunpian_config['URI_SEND_MULTI_SMS'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/sms/multi_send.json";
+$yunpian_config['URI_SEND_TPL_SMS'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . '/sms/tpl_send.json';
+$yunpian_config['URI_PULL_SMS_STATUS'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/sms/pull_status.json";
+# 获取回复短信
+$yunpian_config['URI_PULL_SMS_REPLY'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/sms/pull_reply.json";
+# 查询回复短信
+$yunpian_config['URI_GET_SMS_REPLY'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/sms/get_reply.json";
+# 查短信发送记录
+$yunpian_config['URI_GET_SMS_RECORD'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/sms/get_record.json";
+
+// 语音
+$yunpian_config['URI_SEND_VOICE_SMS'] = $yunpian_config['VOICE_HOST'] . $yunpian_config['VERSION'] . "/voice/send.json";
+$yunpian_config['URI_PULL_VOICE_STATUS'] = $yunpian_config['VOICE_HOST'] . $yunpian_config['VERSION'] . "/voice/pull_status.json";
+
+// 流量
+$yunpian_config['URI_GET_FLOW_PACKAGE'] = $yunpian_config['FLOW_HOST'] . $yunpian_config['VERSION'] . "/flow/get_package.json";
+$yunpian_config['URI_PULL_FLOW_STATUS'] = $yunpian_config['FLOW_HOST'] . $yunpian_config['VERSION'] . "/flow/pull_status.json";
+$yunpian_config['URI_RECHARGE_FLOW'] = $yunpian_config['FLOW_HOST'] . $yunpian_config['VERSION'] . "/flow/recharge.json";
+
+// 用户操作
+$yunpian_config['URI_GET_USER_INFO'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/user/get.json";
+$yunpian_config['URI_SET_USER_INFO'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/user/set.json";
+
+
+// 模板操作
+$yunpian_config['URI_GET_DEFAULT_TEMPLATE'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/tpl/get_default.json";
+$yunpian_config['URI_GET_TEMPLATE'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/tpl/get.json";
+$yunpian_config['URI_ADD_TEMPLATE'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/tpl/add.json";
+$yunpian_config['URI_UPD_TEMPLATE'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/tpl/update.json";
+$yunpian_config['URI_DEL_TEMPLATE'] = $yunpian_config['SMS_HOST'] . $yunpian_config['VERSION'] . "/tpl/del.json";
+$GLOBALS['YUNPIAN_CONFIG'] = $yunpian_config;
+
+//print_r($yunpian_config);
+?>

+ 26 - 0
data/api/smsapi/yunpian/lib/ArrayToObject.php

@@ -0,0 +1,26 @@
+<?php
+/* Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ )
+   Manual: http://scripts.incutio.com/httpclient/
+*/
+
+function arrayToObject($e){
+    if( gettype($e)!='array' ) return;
+    foreach($e as $k=>$v){
+        if( gettype($v)=='array' || getType($v)=='object' )
+            $e[$k]=(object)arrayToObject($v);
+    }
+    return (object)$e;
+}
+ 
+ 
+function objectToArray($e){
+    $e=(array)$e;
+    foreach($e as $k=>$v){
+        if( gettype($v)=='resource' ) return;
+        if( gettype($v)=='object' || gettype($v)=='array' )
+            $e[$k]=(array)objectToArray($v);
+    }
+    return $e;
+} 
+
+?>

+ 95 - 0
data/api/smsapi/yunpian/lib/EncryptUtil.php

@@ -0,0 +1,95 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: bingone
+ * Date: 16/1/19
+ * Time: 下午6:18
+ */
+
+
+
+class EncryptUtil
+{
+    public static function encryptForYunpian($msg, $key)
+    {
+        $key = EncryptUtil::getTeaKey($key);
+        $info=EncryptUtil::getBytes($msg);
+        $retLen = count($info) + 8 - count($info) % 8;
+
+    }
+    public static function encrypt($content, $offset, $key, $times){
+        $tempInt=EncryptUtil::bytesToInteger($content,$offset);
+        $y=$tempInt[0];
+        $z=$tempInt[1];
+        $sum=0;
+        $a=$key[0];$b=$key[1];$c=$key[2];$d=$key[3];
+        $delta=0x9e3779b9;
+        for ($i = 0; $i < $times; $i++) {
+            $sum += $delta;
+            $y += (($z<<4) + $a) ^ ($z + $sum) ^ (($z>>5) + $b);
+            $z += (($y<<4) + $c) ^ ($y + $sum) ^ (($y>>5) + $d);
+        }
+        $tempInt[0]=$y;
+        $tempInt[1]=$z;
+        return EncryptUtil::integerToBytes($tempInt, 0);
+
+
+    }
+    public static function decrypt($bytes){
+
+    }
+    public static function bytesToInteger($bytes, $position) {
+        $val = 0;
+        $val = $bytes[$position + 3] & 0xff;
+        $val <<= 8;
+        $val |= $bytes[$position + 2] & 0xff;
+        $val <<= 8;
+        $val |= $bytes[$position + 1] & 0xff;
+        $val <<= 8;
+        $val |= $bytes[$position] & 0xff;
+        return $val;
+    }
+    public static function integerToBytes($val) {
+        $byt = array();
+        $byt[0] = ($val & 0xff);
+        $byt[1] = ($val >> 8 & 0xff);
+        $byt[2] = ($val >> 16 & 0xff);
+        $byt[3] = ($val >> 24 & 0xff);
+        return $byt;
+    }
+
+
+    public static function getBytes($string)
+    {
+        $bytes = array();
+        for ($i = 0; $i < strlen($string); $i++) {
+            $bytes[] = ord($string[$i]);
+        }
+        return $bytes;
+    }
+
+    public static function getTeaKey($key)
+    {
+        $ints = array();
+        $ints[0] = intval(substr($key, 0, 8),16);
+        $ints[1] = intval(substr($key, 8, 8),16);
+        $ints[2] = intval(substr($key, 16, 8),16);
+        $ints[3] = intval(substr($key, 24, 8),16);
+        return $ints;
+
+    }
+    public static function strToHex($string)//字符串转十六进制
+    {
+        $hex = "";
+        for ($i = 0; $i < strlen($string); $i++)
+            $hex .= dechex(ord($string[$i]));
+        $hex = strtoupper($hex);
+        return $hex;
+    }
+
+
+
+}
+
+print_r(EncryptUtil::getTeaKey("12345678123456781234567812345678"));
+print_r(ord('a'));

+ 54 - 0
data/api/smsapi/yunpian/lib/FlowOperator.php

@@ -0,0 +1,54 @@
+<?php
+
+/**
+ * Created by PhpStorm.
+ * User: bingone
+ * Date: 16/1/19
+ * Time: 下午5:42
+ */
+class FlowOperator
+{
+    public $apikey;
+    public $api_secret;
+    public $yunpian_config;
+
+    public function __construct($apikey = null, $api_secret = null)
+    {
+        $this->yunpian_config = $GLOBALS['YUNPIAN_CONFIG'];
+        if ($api_secret == null)
+            $this->api_secret = $this->yunpian_config['API_SECRET'];
+        else
+            $this->api_secret = $apikey;
+        if ($apikey == null)
+            $this->apikey = $this->yunpian_config['APIKEY'];
+        else
+            $this->apikey = $api_secret;
+    }
+
+    public function encrypt(&$data)
+    {
+
+    }
+
+    public function get_package($data=array())
+    {
+        $data['apikey'] = $this->apikey;
+
+        return HttpUtil::PostCURL($this->yunpian_config['URI_GET_FLOW_PACKAGE'], $data);
+    }
+
+    public function pull_status($data=array())
+    {
+        $data['apikey'] = $this->apikey;
+        return HttpUtil::PostCURL($this->yunpian_config['URI_PULL_FLOW_STATUS'], $data);
+    }
+
+    public function recharge($data=array())
+    {
+        if (!array_key_exists('mobile', $data))
+            return new Result(null,$data,null,$error = 'mobile 为空');
+
+        $data['apikey'] = $this->apikey;
+        return HttpUtil::PostCURL($this->yunpian_config['URI_RECHARGE_FLOW'], $data);
+    }
+}

+ 337 - 338
data/api/smsapi/yunpian/lib/HttpClient.class.php

@@ -1,339 +1,338 @@
-<?php
-defined('InShopNC') or exit('Access Invalid!');
-/* Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ )
-   Manual: http://scripts.incutio.com/httpclient/
-*/
-
-class HttpClient {
-    // Request vars
-    var $host;
-    var $port;
-    var $path;
-    var $method;
-    var $postdata = '';
-    var $cookies = array();
-    var $referer;
-    var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
-    var $accept_encoding = 'gzip';
-    var $accept_language = 'en-us';
-    var $user_agent = 'Incutio HttpClient v0.9';
-    // Options
-    var $timeout = 20;
-    var $use_gzip = true;
-    var $persist_cookies = true;  // If true, received cookies are placed in the $this->cookies array ready for the next request
-                                  // Note: This currently ignores the cookie path (and time) completely. Time is not important, 
-                                  //       but path could possibly lead to security problems.
-    var $persist_referers = true; // For each request, sends path of last request as referer
-    var $debug = false;
-    var $handle_redirects = true; // Auaomtically redirect if Location or URI header is found
-    var $max_redirects = 5;
-    var $headers_only = false;    // If true, stops receiving once headers have been read.
-    // Basic authorization variables
-    var $username;
-    var $password;
-    // Response vars
-    var $status;
-    var $headers = array();
-    var $content = '';
-    var $errormsg;
-    // Tracker variables
-    var $redirect_count = 0;
-    var $cookie_host = '';
-    function HttpClient($host, $port=80) {
-        $this->host = $host;
-        $this->port = $port;
-    }
-    function get($path, $data = false) {
-        $this->path = $path;
-        $this->method = 'GET';
-        if ($data) {
-            $this->path .= '?'.$this->buildQueryString($data);
-        }
-        return $this->doRequest();
-    }
-    function post($path, $data) {
-        $this->path = $path;
-        $this->method = 'POST';
-        $this->postdata = $this->buildQueryString($data);
-        return $this->doRequest();
-    }
-    function buildQueryString($data) {
-        $querystring = '';
-        if (is_array($data)) {
-            // Change data in to postable data
-            foreach ($data as $key => $val) {
-                if (is_array($val)) {
-                    foreach ($val as $val2) {
-                        $querystring .= urlencode($key).'='.urlencode($val2).'&';
-                    }
-                } else {
-                    $querystring .= urlencode($key).'='.urlencode($val).'&';
-                }
-            }
-            $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
-        } else {
-            $querystring = $data;
-        }
-        return $querystring;
-    }
-    function doRequest() {
-        // Performs the actual HTTP request, returning true or false depending on outcome
-        if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
-            // Set error message
-            switch($errno) {
-                case -3:
-                    $this->errormsg = 'Socket creation failed (-3)';
-                case -4:
-                    $this->errormsg = 'DNS lookup failure (-4)';
-                case -5:
-                    $this->errormsg = 'Connection refused or timed out (-5)';
-                default:
-                    $this->errormsg = 'Connection failed ('.$errno.')';
-                $this->errormsg .= ' '.$errstr;
-                $this->debug($this->errormsg);
-            }
-            return false;
-        }
-        socket_set_timeout($fp, $this->timeout);
-        $request = $this->buildRequest();
-        $this->debug('Request', $request);
-        fwrite($fp, $request);
-        // Reset all the variables that should not persist between requests
-        $this->headers = array();
-        $this->content = '';
-        $this->errormsg = '';
-        // Set a couple of flags
-        $inHeaders = true;
-        $atStart = true;
-        // Now start reading back the response
-        while (!feof($fp)) {
-            $line = fgets($fp, 4096);
-            if ($atStart) {
-                // Deal with first line of returned data
-                $atStart = false;
-                if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
-                    $this->errormsg = "Status code line invalid: ".htmlentities($line);
-                    $this->debug($this->errormsg);
-                    return false;
-                }
-                $http_version = $m[1]; // not used
-                $this->status = $m[2];
-                $status_string = $m[3]; // not used
-                $this->debug(trim($line));
-                continue;
-            }
-            if ($inHeaders) {
-                if (trim($line) == '') {
-                    $inHeaders = false;
-                    $this->debug('Received Headers', $this->headers);
-                    if ($this->headers_only) {
-                        break; // Skip the rest of the input
-                    }
-                    continue;
-                }
-                if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
-                    // Skip to the next header
-                    continue;
-                }
-                $key = strtolower(trim($m[1]));
-                $val = trim($m[2]);
-                // Deal with the possibility of multiple headers of same name
-                if (isset($this->headers[$key])) {
-                    if (is_array($this->headers[$key])) {
-                        $this->headers[$key][] = $val;
-                    } else {
-                        $this->headers[$key] = array($this->headers[$key], $val);
-                    }
-                } else {
-                    $this->headers[$key] = $val;
-                }
-                continue;
-            }
-            // We're not in the headers, so append the line to the contents
-            $this->content .= $line;
-        }
-        fclose($fp);
-        // If data is compressed, uncompress it
-        if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
-            $this->debug('Content is gzip encoded, unzipping it');
-            $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php
-            $this->content = gzinflate($this->content);
-        }
-        // If $persist_cookies, deal with any cookies
-        if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) {
-            $cookies = $this->headers['set-cookie'];
-            if (!is_array($cookies)) {
-                $cookies = array($cookies);
-            }
-            foreach ($cookies as $cookie) {
-                if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
-                    $this->cookies[$m[1]] = $m[2];
-                }
-            }
-            // Record domain of cookies for security reasons
-            $this->cookie_host = $this->host;
-        }
-        // If $persist_referers, set the referer ready for the next request
-        if ($this->persist_referers) {
-            $this->debug('Persisting referer: '.$this->getRequestURL());
-            $this->referer = $this->getRequestURL();
-        }
-        // Finally, if handle_redirects and a redirect is sent, do that
-        if ($this->handle_redirects) {
-            if (++$this->redirect_count >= $this->max_redirects) {
-                $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')';
-                $this->debug($this->errormsg);
-                $this->redirect_count = 0;
-                return false;
-            }
-            $location = isset($this->headers['location']) ? $this->headers['location'] : '';
-            $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
-            if ($location || $uri) {
-                $url = parse_url($location.$uri);
-                // This will FAIL if redirect is to a different site
-                return $this->get($url['path']);
-            }
-        }
-        return true;
-    }
-    function buildRequest() {
-        $headers = array();
-        $headers[] = "{$this->method} {$this->path} HTTP/1.0"; // Using 1.1 leads to all manner of problems, such as "chunked" encoding
-        $headers[] = "Host: {$this->host}";
-        $headers[] = "User-Agent: {$this->user_agent}";
-        $headers[] = "Accept: {$this->accept}";
-        if ($this->use_gzip) {
-            $headers[] = "Accept-encoding: {$this->accept_encoding}";
-        }
-        $headers[] = "Accept-language: {$this->accept_language}";
-        if ($this->referer) {
-            $headers[] = "Referer: {$this->referer}";
-        }
-        // Cookies
-        if ($this->cookies) {
-            $cookie = 'Cookie: ';
-            foreach ($this->cookies as $key => $value) {
-                $cookie .= "$key=$value; ";
-            }
-            $headers[] = $cookie;
-        }
-        // Basic authentication
-        if ($this->username && $this->password) {
-            $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
-        }
-        // If this is a POST, set the content type and length
-        if ($this->postdata) {
-            $headers[] = 'Content-Type: application/x-www-form-urlencoded';
-            $headers[] = 'Content-Length: '.strlen($this->postdata);
-        }
-        $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata;
-        return $request;
-    }
-    function getStatus() {
-        return $this->status;
-    }
-    function getContent() {
-        return $this->content;
-    }
-    function getHeaders() {
-        return $this->headers;
-    }
-    function getHeader($header) {
-        $header = strtolower($header);
-        if (isset($this->headers[$header])) {
-            return $this->headers[$header];
-        } else {
-            return false;
-        }
-    }
-    function getError() {
-        return $this->errormsg;
-    }
-    function getCookies() {
-        return $this->cookies;
-    }
-    function getRequestURL() {
-        $url = 'http://'.$this->host;
-        if ($this->port != 80) {
-            $url .= ':'.$this->port;
-        }            
-        $url .= $this->path;
-        return $url;
-    }
-    // Setter methods
-    function setUserAgent($string) {
-        $this->user_agent = $string;
-    }
-    function setAuthorization($username, $password) {
-        $this->username = $username;
-        $this->password = $password;
-    }
-    function setCookies($array) {
-        $this->cookies = $array;
-    }
-    // Option setting methods
-    function useGzip($boolean) {
-        $this->use_gzip = $boolean;
-    }
-    function setPersistCookies($boolean) {
-        $this->persist_cookies = $boolean;
-    }
-    function setPersistReferers($boolean) {
-        $this->persist_referers = $boolean;
-    }
-    function setHandleRedirects($boolean) {
-        $this->handle_redirects = $boolean;
-    }
-    function setMaxRedirects($num) {
-        $this->max_redirects = $num;
-    }
-    function setHeadersOnly($boolean) {
-        $this->headers_only = $boolean;
-    }
-    function setDebug($boolean) {
-        $this->debug = $boolean;
-    }
-    // "Quick" static methods
-    function quickGet($url) {
-        $bits = parse_url($url);
-        $host = $bits['host'];
-        $port = isset($bits['port']) ? $bits['port'] : 80;
-        $path = isset($bits['path']) ? $bits['path'] : '/';
-        if (isset($bits['query'])) {
-            $path .= '?'.$bits['query'];
-        }
-        $client = new HttpClient($host, $port);
-        if (!$client->get($path)) {
-            return false;
-        } else {
-            return $client->getContent();
-        }
-    }
-    function quickPost($url, $data) {
-        $bits = parse_url($url);
-        $host = $bits['host'];
-        $port = isset($bits['port']) ? $bits['port'] : 80;
-        $path = isset($bits['path']) ? $bits['path'] : '/';
-        $client = new HttpClient($host, $port);
-        if (!$client->post($path, $data)) {
-            return false;
-        } else {
-            return $client->getContent();
-        }
-    }
-    function debug($msg, $object = false) {
-        if ($this->debug) {
-            print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg;
-            if ($object) {
-                ob_start();
-                print_r($object);
-                $content = htmlentities(ob_get_contents());
-                ob_end_clean();
-                print '<pre>'.$content.'</pre>';
-            }
-            print '</div>';
-        }
-    }   
-}
-
+<?php
+/* Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ )
+   Manual: http://scripts.incutio.com/httpclient/
+*/
+
+class HttpClient {
+    // Request vars
+    var $host;
+    var $port;
+    var $path;
+    var $method;
+    var $postdata = '';
+    var $cookies = array();
+    var $referer;
+    var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
+    var $accept_encoding = 'gzip';
+    var $accept_language = 'en-us';
+    var $user_agent = 'Incutio HttpClient v0.9';
+    // Options
+    var $timeout = 20;
+    var $use_gzip = true;
+    var $persist_cookies = true;  // If true, received cookies are placed in the $this->cookies array ready for the next request
+                                  // Note: This currently ignores the cookie path (and time) completely. Time is not important, 
+                                  //       but path could possibly lead to security problems.
+    var $persist_referers = true; // For each request, sends path of last request as referer
+    var $debug = false;
+    var $handle_redirects = true; // Auaomtically redirect if Location or URI header is found
+    var $max_redirects = 5;
+    var $headers_only = false;    // If true, stops receiving once headers have been read.
+    // Basic authorization variables
+    var $username;
+    var $password;
+    // Response vars
+    var $status;
+    var $headers = array();
+    var $content = '';
+    var $errormsg;
+    // Tracker variables
+    var $redirect_count = 0;
+    var $cookie_host = '';
+    function HttpClient($host, $port=80) {
+        $this->host = $host;
+        $this->port = $port;
+    }
+    function get($path, $data = false) {
+        $this->path = $path;
+        $this->method = 'GET';
+        if ($data) {
+            $this->path .= '?'.$this->buildQueryString($data);
+        }
+        return $this->doRequest();
+    }
+    function post($path, $data) {
+        $this->path = $path;
+        $this->method = 'POST';
+        $this->postdata = $this->buildQueryString($data);
+        return $this->doRequest();
+    }
+    function buildQueryString($data) {
+        $querystring = '';
+        if (is_array($data)) {
+            // Change data in to postable data
+            foreach ($data as $key => $val) {
+                if (is_array($val)) {
+                    foreach ($val as $val2) {
+                        $querystring .= urlencode($key).'='.urlencode($val2).'&';
+                    }
+                } else {
+                    $querystring .= urlencode($key).'='.urlencode($val).'&';
+                }
+            }
+            $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
+        } else {
+            $querystring = $data;
+        }
+        return $querystring;
+    }
+    function doRequest() {
+        // Performs the actual HTTP request, returning true or false depending on outcome
+        if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
+            // Set error message
+            switch($errno) {
+                case -3:
+                    $this->errormsg = 'Socket creation failed (-3)';
+                case -4:
+                    $this->errormsg = 'DNS lookup failure (-4)';
+                case -5:
+                    $this->errormsg = 'Connection refused or timed out (-5)';
+                default:
+                    $this->errormsg = 'Connection failed ('.$errno.')';
+                $this->errormsg .= ' '.$errstr;
+                $this->debug($this->errormsg);
+            }
+            return false;
+        }
+        socket_set_timeout($fp, $this->timeout);
+        $request = $this->buildRequest();
+        $this->debug('Request', $request);
+        fwrite($fp, $request);
+        // Reset all the variables that should not persist between requests
+        $this->headers = array();
+        $this->content = '';
+        $this->errormsg = '';
+        // Set a couple of flags
+        $inHeaders = true;
+        $atStart = true;
+        // Now start reading back the response
+        while (!feof($fp)) {
+            $line = fgets($fp, 4096);
+            if ($atStart) {
+                // Deal with first line of returned data
+                $atStart = false;
+                if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
+                    $this->errormsg = "Status code line invalid: ".htmlentities($line);
+                    $this->debug($this->errormsg);
+                    return false;
+                }
+                $http_version = $m[1]; // not used
+                $this->status = $m[2];
+                $status_string = $m[3]; // not used
+                $this->debug(trim($line));
+                continue;
+            }
+            if ($inHeaders) {
+                if (trim($line) == '') {
+                    $inHeaders = false;
+                    $this->debug('Received Headers', $this->headers);
+                    if ($this->headers_only) {
+                        break; // Skip the rest of the input
+                    }
+                    continue;
+                }
+                if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
+                    // Skip to the next header
+                    continue;
+                }
+                $key = strtolower(trim($m[1]));
+                $val = trim($m[2]);
+                // Deal with the possibility of multiple headers of same name
+                if (isset($this->headers[$key])) {
+                    if (is_array($this->headers[$key])) {
+                        $this->headers[$key][] = $val;
+                    } else {
+                        $this->headers[$key] = array($this->headers[$key], $val);
+                    }
+                } else {
+                    $this->headers[$key] = $val;
+                }
+                continue;
+            }
+            // We're not in the headers, so append the line to the contents
+            $this->content .= $line;
+        }
+        fclose($fp);
+        // If data is compressed, uncompress it
+        if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
+            $this->debug('Content is gzip encoded, unzipping it');
+            $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php
+            $this->content = gzinflate($this->content);
+        }
+        // If $persist_cookies, deal with any cookies
+        if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) {
+            $cookies = $this->headers['set-cookie'];
+            if (!is_array($cookies)) {
+                $cookies = array($cookies);
+            }
+            foreach ($cookies as $cookie) {
+                if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
+                    $this->cookies[$m[1]] = $m[2];
+                }
+            }
+            // Record model of cookies for security reasons
+            $this->cookie_host = $this->host;
+        }
+        // If $persist_referers, set the referer ready for the next request
+        if ($this->persist_referers) {
+            $this->debug('Persisting referer: '.$this->getRequestURL());
+            $this->referer = $this->getRequestURL();
+        }
+        // Finally, if handle_redirects and a redirect is sent, do that
+        if ($this->handle_redirects) {
+            if (++$this->redirect_count >= $this->max_redirects) {
+                $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')';
+                $this->debug($this->errormsg);
+                $this->redirect_count = 0;
+                return false;
+            }
+            $location = isset($this->headers['location']) ? $this->headers['location'] : '';
+            $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
+            if ($location || $uri) {
+                $url = parse_url($location.$uri);
+                // This will FAIL if redirect is to a different site
+                return $this->get($url['path']);
+            }
+        }
+        return true;
+    }
+    function buildRequest() {
+        $headers = array();
+        $headers[] = "{$this->method} {$this->path} HTTP/1.0"; // Using 1.1 leads to all manner of problems, such as "chunked" encoding
+        $headers[] = "Host: {$this->host}";
+        $headers[] = "User-Agent: {$this->user_agent}";
+        $headers[] = "Accept: {$this->accept}";
+        if ($this->use_gzip) {
+            $headers[] = "Accept-encoding: {$this->accept_encoding}";
+        }
+        $headers[] = "Accept-language: {$this->accept_language}";
+        if ($this->referer) {
+            $headers[] = "Referer: {$this->referer}";
+        }
+        // Cookies
+        if ($this->cookies) {
+            $cookie = 'Cookie: ';
+            foreach ($this->cookies as $key => $value) {
+                $cookie .= "$key=$value; ";
+            }
+            $headers[] = $cookie;
+        }
+        // Basic authentication
+        if ($this->username && $this->password) {
+            $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
+        }
+        // If this is a POST, set the content type and length
+        if ($this->postdata) {
+            $headers[] = 'Content-Type: application/x-www-form-urlencoded';
+            $headers[] = 'Content-Length: '.strlen($this->postdata);
+        }
+        $request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata;
+        return $request;
+    }
+    function getStatus() {
+        return $this->status;
+    }
+    function getContent() {
+        return $this->content;
+    }
+    function getHeaders() {
+        return $this->headers;
+    }
+    function getHeader($header) {
+        $header = strtolower($header);
+        if (isset($this->headers[$header])) {
+            return $this->headers[$header];
+        } else {
+            return false;
+        }
+    }
+    function getError() {
+        return $this->errormsg;
+    }
+    function getCookies() {
+        return $this->cookies;
+    }
+    function getRequestURL() {
+        $url = 'http://'.$this->host;
+        if ($this->port != 80) {
+            $url .= ':'.$this->port;
+        }            
+        $url .= $this->path;
+        return $url;
+    }
+    // Setter methods
+    function setUserAgent($string) {
+        $this->user_agent = $string;
+    }
+    function setAuthorization($username, $password) {
+        $this->username = $username;
+        $this->password = $password;
+    }
+    function setCookies($array) {
+        $this->cookies = $array;
+    }
+    // Option setting methods
+    function useGzip($boolean) {
+        $this->use_gzip = $boolean;
+    }
+    function setPersistCookies($boolean) {
+        $this->persist_cookies = $boolean;
+    }
+    function setPersistReferers($boolean) {
+        $this->persist_referers = $boolean;
+    }
+    function setHandleRedirects($boolean) {
+        $this->handle_redirects = $boolean;
+    }
+    function setMaxRedirects($num) {
+        $this->max_redirects = $num;
+    }
+    function setHeadersOnly($boolean) {
+        $this->headers_only = $boolean;
+    }
+    function setDebug($boolean) {
+        $this->debug = $boolean;
+    }
+    // "Quick" static methods
+    function quickGet($url) {
+        $bits = parse_url($url);
+        $host = $bits['host'];
+        $port = isset($bits['port']) ? $bits['port'] : 80;
+        $path = isset($bits['path']) ? $bits['path'] : '/';
+        if (isset($bits['query'])) {
+            $path .= '?'.$bits['query'];
+        }
+        $client = new HttpClient($host, $port);
+        if (!$client->get($path)) {
+            return false;
+        } else {
+            return $client->getContent();
+        }
+    }
+    function quickPost($url, $data) {
+        $bits = parse_url($url);
+        $host = $bits['host'];
+        $port = isset($bits['port']) ? $bits['port'] : 80;
+        $path = isset($bits['path']) ? $bits['path'] : '/';
+        $client = new HttpClient($host, $port);
+        if (!$client->post($path, $data)) {
+            return false;
+        } else {
+            return $client->getContent();
+        }
+    }
+    function debug($msg, $object = false) {
+        if ($this->debug) {
+            print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg;
+            if ($object) {
+                ob_start();
+                print_r($object);
+                $content = htmlentities(ob_get_contents());
+                ob_end_clean();
+                print '<pre>'.$content.'</pre>';
+            }
+            print '</div>';
+        }
+    }   
+}
+
 ?>

+ 50 - 0
data/api/smsapi/yunpian/lib/HttpUtil.php

@@ -0,0 +1,50 @@
+<?php
+
+/**
+ * Created by PhpStorm.
+ * User: bingone
+ * Date: 16/1/19
+ * Time: 下午3:39
+ */
+require_once('Result.php');
+class HttpUtil
+{
+    public static function PostCURL($url,$post_data){
+        $ch = curl_init();
+
+        /* 设置验证方式 */
+
+        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded','charset=utf-8'));
+
+        /* 设置返回结果为流 */
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+
+        /* 设置超时时间*/
+        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
+
+        /* 设置通信方式 */
+        curl_setopt($ch, CURLOPT_POST, 1);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
+        curl_setopt ($ch, CURLOPT_URL, $url);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
+        $retry=0;
+        // 若执行失败则重试
+        do{
+            $output = curl_exec($ch);
+            $retry++;
+//            echo $retry."\n";
+        }while((curl_errno($ch) !== 0) && $retry<$GLOBALS['YUNPIAN_CONFIG']['RETRY_TIMES']);
+
+        if (curl_errno($ch) !== 0) {
+            $r = new Result(null, $post_data, null,curl_error($ch));
+            curl_close($ch);
+            return $r;
+        }
+        $output = trim($output, "\xEF\xBB\xBF");
+        $statusCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
+        $ret = new Result($statusCode,$post_data,json_decode($output,true),null);
+        curl_close($ch);
+        return $ret;
+    }
+}

+ 35 - 0
data/api/smsapi/yunpian/lib/Result.php

@@ -0,0 +1,35 @@
+<?php
+
+/**
+ * Created by PhpStorm.
+ * User: bingone
+ * Date: 16/1/19
+ * Time: 下午4:15
+ */
+
+class Result
+{
+    public $success;
+    public $statusCode;
+    public $requestData;
+    public $responseData;
+    public $error;
+    public function __construct($statusCode=null,$requestData = null, $responseData = null,$error=null )
+    {
+        $this->success = false;
+        if ($statusCode == 200)
+            $this->success = true;
+        $this->statusCode = $statusCode;
+        $this->requestData = $requestData;
+        $this->responseData = $responseData;
+        $this->error = $error;
+    }
+
+    public function getData()
+    {
+        return $this->responseData;
+    }
+    public function isSuccess(){
+        return $this->success;
+    }
+}

+ 88 - 0
data/api/smsapi/yunpian/lib/SmsOperator.php

@@ -0,0 +1,88 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: bingone
+ * Date: 16/1/19
+ * Time: 下午5:42
+ */
+
+require_once('HttpUtil.php');
+
+class SmsOperator
+{
+    public $apikey;
+    public $api_secret;
+    public $yunpian_config;
+
+    public function __construct($apikey = null, $api_secret = null)
+    {
+        $this->yunpian_config = $GLOBALS['YUNPIAN_CONFIG'];
+        if ($api_secret == null)
+            $this->api_secret = $this->yunpian_config['API_SECRET'];
+        else
+            $this->api_secret = $apikey;
+        if ($apikey == null)
+            $this->apikey = $this->yunpian_config['APIKEY'];
+        else
+            $this->apikey = $api_secret;
+    }
+
+    public function encrypt(&$data)
+    {
+
+    }
+
+    public function single_send($data = array())
+    {
+        if (!array_key_exists('mobile', $data))
+            return new Result(null, $data, null, 'mobile 为空');
+        if (!array_key_exists('text', $data))
+            return new Result(null, $data, null, 'text 为空');
+        $data['apikey'] = $this->apikey;
+
+        return HttpUtil::PostCURL($this->yunpian_config['URI_SEND_SINGLE_SMS'], $data);
+    }
+
+    public function batch_send($data = array())
+    {
+        if (!array_key_exists('mobile', $data))
+            return new Result(null, $data, null, $error = 'mobile 为空');
+        if (!array_key_exists('text', $data))
+            return new Result(null, $data, null, $error = 'text 为空');
+        $data['apikey'] = $this->apikey;
+
+        return HttpUtil::PostCURL($this->yunpian_config['URI_SEND_BATCH_SMS'], $data);
+    }
+
+    public function multi_send($data = array())
+    {
+        if (!array_key_exists('mobile', $data))
+            return new Result(null, $data, null, $error = 'mobile 为空');
+        if (!array_key_exists('text', $data))
+            return new Result(null, $data, null, $error = 'text 为空');
+        if (count(explode(',', $data['mobile'])) != count(explode(',', $data['text'])))
+            return new Result(null, $data, null, $error = 'mobile 与 text 个数不匹配');
+        $data['apikey'] = $this->apikey;
+        $text_array = explode(',', $data['text']);
+        $data['text'] = '';
+        for ($index = 0; $index < count($text_array); $index++) {
+            $data['text'] .= urlencode($text_array[$index]) . ',';
+        }
+        $data['text'] = substr($data['text'],0,-1);
+        return HttpUtil::PostCURL($this->yunpian_config['URI_SEND_MULTI_SMS'], $data);
+    }
+
+    public function tpl_send($data = array())
+    {
+        if (!array_key_exists('mobile', $data))
+            return new Result(null, $data, null, 'mobile 为空');
+        if (!array_key_exists('tpl_id', $data))
+            return new Result(null, $data, null, 'tpl_id 为空');
+        if (!array_key_exists('tpl_value', $data))
+            return new Result(null, $data, null, 'tpl_value 为空');
+
+        $data['apikey'] = $this->apikey;
+
+        return HttpUtil::PostCURL($this->yunpian_config['URI_SEND_TPL_SMS'], $data);
+    }
+}

+ 304 - 0
data/api/smsapi/yunpian/lib/TeaUtil.php

@@ -0,0 +1,304 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: bingone
+ * Date: 16/1/19
+ * Time: 下午6:21
+ */
+
+
+$date = '';
+$key = '002d88e24fdaf41801d1d18ef8109996';
+$t = new TeaUtil ();
+$tea = $t->encrypt($date, $key);
+$eetea = $t->decrypt($tea, $key);
+print $eetea;
+var_dump(base64_encode($tea));
+var_dump($eetea);
+
+class TeaUtil
+{
+    public static function getBytes($string)
+    {
+        $bytes = array();
+        for ($i = 0; $i < strlen($string); $i++) {
+            $bytes[] = ord($string[$i]);
+        }
+        return $bytes;
+    }
+
+    private $a, $b, $c, $d;
+    private $n_iter;
+
+    public function __construct()
+    {
+        $this->setIter(32);
+    }
+
+    private function setIter($n_iter)
+    {
+        $this->n_iter = $n_iter;
+    }
+
+    private function getIter()
+    {
+        return $this->n_iter;
+    }
+
+    public function encrypt($data, $key)
+    {
+        // resize data to 32 bits (4 bytes)
+        $n = $this->_resize($data, 8);
+
+        // convert data to long
+        $data_long [0] = $n;
+        $n_data_long = $this->_str2long($n, $data, $data_long);
+
+        // resize data_long to 64 bits (2 longs of 32 bits)
+        $n = count($data_long);
+        if (($n & 1) == 1) {
+            $data_long [$n] = chr(0);
+            $n_data_long++;
+        }
+
+        // resize key to a multiple of 128 bits (16 bytes)
+        $this->_resize($key, 16, true);
+        if ('' == $key)
+            $key = '0000000000000000';
+
+        // convert key to long
+        $n_key_long = $this->_str2long(0, $key, $key_long);
+
+        // encrypt the long data with the key
+        $enc_data = '';
+        $w = array(0, 0);
+        $j = 0;
+        $k = array(0, 0, 0, 0);
+        for ($i = 0; $i < $n_data_long; ++$i) {
+            // get next key part of 128 bits
+            if ($j + 4 <= $n_key_long) {
+                $k [0] = $key_long [$j];
+                $k [1] = $key_long [$j + 1];
+                $k [2] = $key_long [$j + 2];
+                $k [3] = $key_long [$j + 3];
+            } else {
+                $k [0] = $key_long [$j % $n_key_long];
+                $k [1] = $key_long [($j + 1) % $n_key_long];
+                $k [2] = $key_long [($j + 2) % $n_key_long];
+                $k [3] = $key_long [($j + 3) % $n_key_long];
+            }
+            $j = ($j + 4) % $n_key_long;
+
+            $this->_encipherLong($data_long [$i], $data_long [++$i], $w, $k);
+
+            // append the enciphered longs to the result
+            $enc_data .= $this->_long2str($w [0]);
+            $enc_data .= $this->_long2str($w [1]);
+        }
+
+        return $enc_data;
+    }
+
+    public function decrypt($enc_data, $key)
+    {
+        // convert data to long
+        $n_enc_data_long = $this->_str2long(0, $enc_data, $enc_data_long);
+
+        // resize key to a multiple of 128 bits (16 bytes)
+        $this->_resize($key, 16, true);
+        if ('' == $key)
+            $key = '0000000000000000';
+
+        // convert key to long
+        $n_key_long = $this->_str2long(0, $key, $key_long);
+
+        // decrypt the long data with the key
+        $data = '';
+        $w = array(0, 0);
+        $j = 0;
+        $len = 0;
+        $k = array(0, 0, 0, 0);
+        $pos = 0;
+
+        for ($i = 0; $i < $n_enc_data_long; $i += 2) {
+            // get next key part of 128 bits
+            if ($j + 4 <= $n_key_long) {
+                $k [0] = $key_long [$j];
+                $k [1] = $key_long [$j + 1];
+                $k [2] = $key_long [$j + 2];
+                $k [3] = $key_long [$j + 3];
+            } else {
+                $k [0] = $key_long [$j % $n_key_long];
+                $k [1] = $key_long [($j + 1) % $n_key_long];
+                $k [2] = $key_long [($j + 2) % $n_key_long];
+                $k [3] = $key_long [($j + 3) % $n_key_long];
+            }
+            $j = ($j + 4) % $n_key_long;
+
+            $this->_decipherLong($enc_data_long [$i], $enc_data_long [$i + 1], $w, $k);
+
+            // append the deciphered longs to the result data (remove padding)
+            if (0 == $i) {
+                $len = $w [0];
+                if (4 <= $len) {
+                    $data .= $this->_long2str($w [1]);
+                } else {
+                    $data .= substr($this->_long2str($w [1]), 0, $len % 4);
+                }
+            } else {
+                $pos = ($i - 1) * 4;
+                if ($pos + 4 <= $len) {
+                    $data .= $this->_long2str($w [0]);
+
+                    if ($pos + 8 <= $len) {
+                        $data .= $this->_long2str($w [1]);
+                    } elseif ($pos + 4 < $len) {
+                        $data .= substr($this->_long2str($w [1]), 0, $len % 4);
+                    }
+                } else {
+                    $data .= substr($this->_long2str($w [0]), 0, $len % 4);
+                }
+            }
+        }
+        return $data;
+    }
+
+    private function _encipherLong($y, $z, &$w, &$k)
+    {
+        $sum = ( integer )0;
+        $delta = 0x9E3779B9;
+        $n = ( integer )$this->n_iter;
+
+        while ($n-- > 0) {
+            //C v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
+            //C v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
+            $sum = $this->_add($sum, $delta);
+            $y = $this->_add($y, $this->_add(($z << 4), $this->a) ^ $this->_add($z, $sum) ^ $this->_add($this->_rshift($z, 5), $this->b));
+            $z = $this->_add($z, $this->_add(($y << 4), $this->a) ^ $this->_add($y, $sum) ^ $this->_add($this->_rshift($y, 5), $this->b));
+        }
+
+        $w [0] = $y;
+        $w [1] = $z;
+    }
+
+    private function _decipherLong($y, $z, &$w, &$k)
+    {
+        // sum = delta<<5, in general sum = delta * n
+        $sum = 0xC6EF3720;
+        $delta = 0x9E3779B9;
+        $n = ( integer )$this->n_iter;
+
+        while ($n-- > 0) {
+            //C v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
+            //C v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
+            $z = $this->_add($z, -($this->_add(($y << 4), $this->a) ^ $this->_add($y, $sum) ^ $this->_add($this->_rshift($y, 5), $this->b)));
+            $y = $this->_add($y, -($this->_add(($z << 4), $this->a) ^ $this->_add($z, $sum) ^ $this->_add($this->_rshift($z, 5), $this->b)));
+            $sum = $this->_add($sum, -$delta);
+        }
+
+        $w [0] = $y;
+        $w [1] = $z;
+    }
+
+    private function _resize(&$data, $size, $nonull = false)
+    {
+        $n = strlen($data);
+        $nmod = $n % $size;
+        if (0 == $nmod)
+            $nmod = $size;
+
+        if ($nmod > 0) {
+            if ($nonull) {
+                for ($i = $n; $i < $n - $nmod + $size; ++$i) {
+                    $data [$i] = $data [$i % $n];
+                }
+            } else {
+                for ($i = $n; $i < $n - $nmod + $size; ++$i) {
+                    $data [$i] = chr(0);
+                }
+            }
+        }
+        return 8-$nmod;
+    }
+
+    private function _hex2bin($str)
+    {
+        $len = strlen($str);
+        return pack('H' . $len, $str);
+    }
+
+    private function _str2long($start, &$data, &$data_long)
+    {
+        $n = strlen($data);
+
+        $tmp = unpack('N*', $data);
+        $j = $start;
+
+        foreach ($tmp as $value)
+            $data_long [$j++] = $value;
+
+        return $j;
+    }
+
+    private function _long2str($l)
+    {
+        return pack('N', $l);
+    }
+
+
+    private function _rshift($integer, $n)
+    {
+        // convert to 32 bits
+        if (0xffffffff < $integer || -0xffffffff > $integer) {
+            $integer = fmod($integer, 0xffffffff + 1);
+        }
+
+        // convert to unsigned integer
+        if (0x7fffffff < $integer) {
+            $integer -= 0xffffffff + 1.0;
+        } elseif (-0x80000000 > $integer) {
+            $integer += 0xffffffff + 1.0;
+        }
+
+        // do right shift
+        if (0 > $integer) {
+            $integer &= 0x7fffffff; // remove sign bit before shift
+            $integer >>= $n; // right shift
+            $integer |= 1 << (31 - $n); // set shifted sign bit
+        } else {
+            $integer >>= $n; // use normal right shift
+        }
+
+        return $integer;
+    }
+
+    private function _add($i1, $i2)
+    {
+        $result = 0.0;
+
+        foreach (func_get_args() as $value) {
+            // remove sign if necessary
+            if (0.0 > $value) {
+                $value -= 1.0 + 0xffffffff;
+            }
+
+            $result += $value;
+        }
+
+        // convert to 32 bits
+        if (0xffffffff < $result || -0xffffffff > $result) {
+            $result = fmod($result, 0xffffffff + 1);
+        }
+
+        // convert to signed integer
+        if (0x7fffffff < $result) {
+            $result -= 0xffffffff + 1.0;
+        } elseif (-0x80000000 > $result) {
+            $result += 0xffffffff + 1.0;
+        }
+
+        return $result;
+    }
+}
+
+?>

+ 75 - 0
data/api/smsapi/yunpian/lib/TplOperator.php

@@ -0,0 +1,75 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: bingone
+ * Date: 16/1/20
+ * Time: 上午10:37
+ */
+require_once 'HttpUtil.php';
+
+class TplOperator
+{
+    public $apikey;
+    public $api_secret;
+    public $yunpian_config;
+
+    public function __construct($apikey = null, $api_secret = null)
+    {
+        $this->yunpian_config = $GLOBALS['YUNPIAN_CONFIG'];
+        if ($api_secret == null)
+            $this->api_secret = $this->yunpian_config['API_SECRET'];
+        else
+            $this->api_secret = $apikey;
+        if ($apikey == null)
+            $this->apikey = $this->yunpian_config['APIKEY'];
+        else
+            $this->apikey = $api_secret;
+    }
+
+    public function encrypt(&$data)
+    {
+
+    }
+    public function get_default($data = array())
+    {
+        $data['apikey'] = $this->apikey;
+
+        return HttpUtil::PostCURL($this->yunpian_config['URI_GET_DEFAULT_TEMPLATE'], $data);
+    }
+    public function get($data = array())
+    {
+        $data['apikey'] = $this->apikey;
+
+        return HttpUtil::PostCURL($this->yunpian_config['URI_GET_TEMPLATE'], $data);
+    }
+
+    public function add($data = array())
+    {
+        if (!array_key_exists('tpl_id',$data))
+            return new Result(null,$data,null,$error = 'tpl_id 为空');
+        if (!array_key_exists('tpl_content',$data))
+            return new Result(null,$data,null,$error = 'tpl_content 为空');
+        $data['apikey'] = $this->apikey;
+        return HttpUtil::PostCURL($this->yunpian_config['URI_ADD_TEMPLATE'], $data);
+    }
+
+    public function upd($data = array())
+    {
+        if (!array_key_exists('tpl_id',$data))
+            return new Result(null,$data,null,$error = 'tpl_id 为空');
+        if (!array_key_exists('tpl_content',$data))
+            return new Result(null,$data,null,$error = 'tpl_content 为空');
+        $data['apikey'] = $this->apikey;
+        return HttpUtil::PostCURL($this->yunpian_config['URI_UPD_TEMPLATE'], $data);
+    }
+
+    public function del($data = array())
+    {
+        if (!array_key_exists('tpl_id',$data))
+            return new Result(null,$data,null,$error = 'tpl_id 为空');
+        $data['apikey'] = $this->apikey;
+
+        return HttpUtil::PostCURL($this->yunpian_config['URI_DEL_TEMPLATE'], $data);
+    }
+
+}

+ 42 - 0
data/api/smsapi/yunpian/lib/UserOperator.php

@@ -0,0 +1,42 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: bingone
+ * Date: 16/1/20
+ * Time: 上午10:11
+ */
+
+//namespace Yunpian\lib;
+
+require_once 'HttpUtil.php';
+class UserOperator
+{
+    public $apikey;
+    public $api_secret;
+    public $yunpian_config;
+    public function __construct($apikey=null,$api_secret=null)
+    {
+        $this->yunpian_config = $GLOBALS['YUNPIAN_CONFIG'];
+        if($api_secret == null)
+            $this->api_secret = $this->yunpian_config['API_SECRET'];
+        else
+            $this->api_secret = $apikey;
+        if($apikey == null)
+            $this->apikey = $this->yunpian_config['APIKEY'];
+        else
+            $this->apikey = $api_secret;
+    }
+    public function encrypt(&$data){
+
+    }
+    public function get($data=array()){
+        $data['apikey'] = $this->apikey;
+
+        return HttpUtil::PostCURL($this->yunpian_config['URI_GET_USER_INFO'],$data);
+    }
+    public function set($data=array()){
+        $data['apikey'] = $this->apikey;
+        return HttpUtil::PostCURL($this->yunpian_config['URI_SET_USER_INFO'],$data);
+    }
+}
+?>

+ 52 - 0
data/api/smsapi/yunpian/lib/VoiceOperator.php

@@ -0,0 +1,52 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: bingone
+ * Date: 16/1/19
+ * Time: 下午5:42
+ */
+
+require_once 'HttpUtil.php';
+
+class VoiceOperator
+{
+    public $apikey;
+    public $api_secret;
+    public $yunpian_config;
+
+    public function __construct($apikey = null, $api_secret = null)
+    {
+        $this->yunpian_config = $GLOBALS['YUNPIAN_CONFIG'];
+        if ($api_secret == null)
+            $this->api_secret = $this->yunpian_config['API_SECRET'];
+        else
+            $this->api_secret = $apikey;
+        if ($apikey == null)
+            $this->apikey = $this->yunpian_config['APIKEY'];
+        else
+            $this->apikey = $api_secret;
+    }
+
+    public function encrypt(&$data)
+    {
+
+    }
+
+    public function send($data=array())
+    {
+        if (!array_key_exists('mobile', $data))
+            return new Result($error = 'mobile 为空');
+        if (!array_key_exists('code', $data))
+            return new Result($error = 'code 为空');
+        $data['apikey'] = $this->apikey;
+//        encrypt($data);
+        return HttpUtil::PostCURL($this->yunpian_config['URI_SEND_VOICE_SMS'], $data);
+    }
+
+    public function pull_status($data=array())
+    {
+        $data['apikey'] = $this->apikey;
+        return HttpUtil::PostCURL($this->yunpian_config['URI_PULL_VOICE_STATUS'], $data);
+    }
+
+}

+ 1 - 1
data/logic/queue.logic.php

@@ -460,7 +460,7 @@ class queueLogic
      *
      * @return bool
      */
-    public function dispatchKDN($param)
+    public function subscribeKDN($param)
     {
         if (empty($param) || empty($param['order_sn'])) {
             Log::record("kdn_helper: 数据有误! param:" . json_encode($param));

+ 60 - 0
data/model/bonus_type.model.php

@@ -44,4 +44,64 @@ class bonus_typeModel extends Model
         $this->where($condition)->update($data);
     }
 
+    /**
+     * 获取已过期的余额列表
+     */
+    private function get_endbonus_list()
+    {
+        $one_hour = 60 * 60;
+        $condition = array('remain_amount' => array('gt',0),'is_refund' => 0,'send_end_date' =>array('lt',time() - $one_hour));
+        return $this->where($condition)->field('type_id,type_sn,sender_id,sender_name,remain_amount')->limit(false)->select();
+    }
+
+    /**
+     * 红包退款
+     * @return bool
+     */
+    public function bonus_refund()
+    {
+        $results = $this->get_endbonus_list();
+        if(empty($results)) {
+            return false;
+        }
+
+        $model_predeposit = Model('predeposit');
+        foreach($results as $result)
+        {
+            Model::beginTransaction();
+            try
+            {
+                //将没抢完的钱退还到用户余额
+                $log_data = array();
+                $log_data['member_id']   = $result['sender_id'];
+                $log_data['member_name'] = $result['sender_name'];
+                $log_data['amount'] = $result['remain_amount'];
+                $log_data['type_sn'] = $result['type_sn'];
+
+                $model_predeposit->changePd('bonus_refund',$log_data);
+
+                //更新红包状态
+                $this->where(array('type_id' =>$result['type_id']))->update(array('is_refund' => 1,'refund_time' => time()));
+                if ($this->affected_rows() <= 0) {
+                    Model::rollback();
+
+                    $sresult = implode(',',$result);
+                    Log::record("bonus refund 更新状态失败,result:{$sresult}.");
+                } else {
+                    $condition = array('type_id' =>$result['type_id'],'bonus_status' => array('in','0,1'));
+                    Model('user_bonus')->where($condition)->delete();
+                    Model::commit();
+                }
+            }
+            catch (Exception $e)
+            {
+                Model::rollback();
+
+                $sresult = implode(',',$result);
+                Log::record('bonus refund : error:' . $e->getMessage() . " result:{$sresult}.");
+            }
+        }
+
+        return true;
+    }
 }

+ 10 - 0
data/model/predeposit.model.php

@@ -363,6 +363,16 @@ class predepositModel extends Model {
                 $data_msg['freeze_amount'] = -$data['amount'];
                 $data_msg['desc'] = $data_log['lg_desc'];
                 break;
+            case 'bonus_refund':
+                $data_log['lg_av_amount'] = $data['amount'];
+                $data_log['lg_desc'] = '退还没抢的红包金额,红包单号: '.$data['type_sn'];
+
+                $data_pd['available_predeposit'] = array('exp','available_predeposit+'.$data['amount']);
+
+                $data_msg['av_amount'] = $data['amount'];
+                $data_msg['freeze_amount'] = 0;
+                $data_msg['desc'] = $data_log['lg_desc'];
+                break;
             case 'bonus_add_money':
                 $data_log['lg_av_amount'] = $data['amount'];
                 $data_log['lg_desc'] = '红包系统调节预存款【增加】,红包单号: '.$data['pdr_sn'];

+ 23 - 0
data/resource/mobile/bonus/css/common.css

@@ -178,4 +178,27 @@ a {
 }
 .gold_coin{
     -webkit-animation: coin 1s ease-out ;
+}
+.time_over {
+    margin-top: 75px;
+    font-size: 1.4rem;
+    line-height: 1.8rem;
+}
+.bottom_pro {
+    position: absolute;
+    bottom: 8%;
+    left: 0;
+    width: 100%;
+    color: #fff;
+    font-size: 10px;
+    line-height:1.1rem;
+}
+.icon_logo {
+    display: inline-block;
+    width: 0.8rem;
+    height: 0.8rem;
+    background: url("../imgaes/icon_logo.png") no-repeat;
+    background-size: 100% 100%;
+    vertical-align: middle;
+    margin-right: 0.3rem;
 }

BIN
data/resource/mobile/bonus/imgaes/icon_logo.png


+ 0 - 0
data/sales/home_goods.txt


+ 22 - 21
fooder.php

@@ -9,30 +9,31 @@ define('BASE_CRONTAB_PATH',BASE_ROOT_PATH.'/crontab');
 define('BASE_UPLOAD_PATH',BASE_DATA_PATH.'/upload');
 define('BASE_UTIL_PATH',BASE_ROOT_PATH.'/util');
 
-require_once(BASE_MOBILE_PATH . '/util/errcode.php');
-require_once(BASE_ROOT_PATH . '/request_helper.php');
 require_once(BASE_ROOT_PATH . '/global.php');
-
 require_once(BASE_DATA_PATH . '/config/config.ini.php');
-require_once(BASE_CORE_PATH .'/33hao.php');
+require_once(BASE_CORE_PATH . '/33hao.php');
+
 require_once(BASE_MOBILE_PATH . '/config/config.ini.php');
-require_once(BASE_MOBILE_PATH.'/framework/function/function.php');
+require_once(BASE_MOBILE_PATH . '/framework/function/function.php');
+require_once(BASE_MOBILE_PATH . '/util/errcode.php');
+require_once(BASE_MOBILE_PATH . '/control/log.php');
 
-require_once(BASE_CORE_PATH.'/framework/libraries/queue.php');
-require_once(BASE_CORE_PATH.'/framework/libraries/tpl.php');
-require_once(BASE_CORE_PATH.'/framework/function/core.php');
-require_once(BASE_CORE_PATH.'/framework/core/base.php');
-require_once(BASE_CORE_PATH.'/framework/libraries/cache.php');
-require_once(BASE_CORE_PATH.'/framework/libraries/queue.php');
-require_once(BASE_CORE_PATH.'/framework/libraries/language.php');
-require_once(BASE_CORE_PATH.'/framework/libraries/model.php');
-require_once(BASE_CORE_PATH.'/framework/libraries/log.php');
-require_once(BASE_CORE_PATH.'/framework/db/mysqli.php');
-require_once(BASE_CORE_PATH.'/framework/function/goods.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/queue.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/tpl.php');
+require_once(BASE_CORE_PATH . '/framework/function/core.php');
+require_once(BASE_CORE_PATH . '/framework/core/base.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/cache.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/queue.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/language.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/model.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/log.php');
+require_once(BASE_CORE_PATH . '/framework/db/mysqli.php');
+require_once(BASE_CORE_PATH . '/framework/function/goods.php');
 require_once(BASE_CORE_PATH . '/framework/libraries/validate.php');
-require_once(BASE_CORE_PATH.'/framework/libraries/resizeimage.php');
-require_once (BASE_MOBILE_PATH . '/control/log.php');
-require_once (BASE_ROOT_PATH . '/helper/performance_helper.php');
-require_once (BASE_ROOT_PATH . '/helper/sensitive_word/dfa.php');
-?>
+require_once(BASE_CORE_PATH . '/framework/libraries/resizeimage.php');
 
+require_once(BASE_ROOT_PATH . '/helper/performance_helper.php');
+require_once(BASE_ROOT_PATH . '/helper/sensitive_word/dfa.php');
+require_once(BASE_ROOT_PATH . '/helper/request_helper.php');
+require_once(BASE_ROOT_PATH . '/helper/configure.php');
+?>

+ 0 - 6
helper/bonus/factory.php

@@ -51,12 +51,6 @@ class factory
         } catch (Exception $ex) {
             return false;
         }
-
-    }
-
-    static public function add_fixed_bonus()
-    {
-
     }
 }
 

+ 36 - 5
helper/bonus/generator.php

@@ -104,6 +104,20 @@ class GeneralGenerator extends IGenerator
         return true;
     }
 
+    private function get_maxamount($total,$num)
+    {
+        $avg = floatval($total / $num);
+        return intval($avg * 2 + 0.5);
+    }
+
+    private function get_minamount($total,$num)
+    {
+        $avg = floatval($total / $num);
+        $avg = $avg / 10;
+        $avg = intval($avg + 0.5);
+
+        return $avg;
+    }
     /**
      * @param $paramer
      */
@@ -111,25 +125,34 @@ class GeneralGenerator extends IGenerator
     {
         $min_amount = intval(floatval($paramer['min_amount']) * 100);
         $base_amount = $min_amount;
-
         $num = intval($paramer['total_num']);
-        $total_amount = intval(intval(floatval($paramer['total_amount']) * 100) - $num * $base_amount);
 
         $ret = array();
         for ($i = 0; $i < $num; $i++) {
             array_push($ret,$base_amount);
         }
 
-        $max_amount = $total_amount;
+        $total_amount = intval(intval(floatval($paramer['total_amount']) * 100) - $num * $base_amount);
+        $min_amount = $this->get_minamount($total_amount,$num);
+
+        if($min_amount > 0)
+        {
+            foreach($ret as &$val) {
+                $val += $min_amount;
+            }
+            $total_amount -= $min_amount * $num;
+        }
+
         $max_val = 0;
+        $max_amount = $this->get_maxamount($total_amount,$num);
         for ($i = 0; $i < $num && $total_amount > 0;)
         {
             $amount = intval(mt_rand(0, $max_amount));
+            $amount = $amount > $total_amount ? $total_amount : $amount;
 
             $ret[$i] += $amount;
             $total_amount -= $amount;
             $max_val = $ret[$i] > $max_val ? $ret[$i] : $max_val;
-            $max_amount = $total_amount;
 
             if($i == $num -1) {
                 $i = 0;
@@ -138,7 +161,6 @@ class GeneralGenerator extends IGenerator
             }
         }
 
-        //$y = array_sum($ret); //验证制造的数据是否可以正好相等
         $max_val = floatval($max_val) / 100;
         $min_val = $ret[0];
         foreach ($ret as &$val) {
@@ -147,6 +169,15 @@ class GeneralGenerator extends IGenerator
         }
         $min_val = floatval($min_val) / 100;
 
+        for($index = 0; $index < $num - 1; $index++) {
+            $pos_a = mt_rand(0, $num - 1);
+            $pos_b = mt_rand(0, $num - 1);
+
+            $tmp = $ret[$pos_a];
+            $ret[$pos_a] = $ret[$pos_b];
+            $ret[$pos_b] = $tmp;
+        }
+
         return $ret;
     }
 }

+ 3 - 1
helper/bonus/manager.php

@@ -44,7 +44,6 @@ class manager
                 $lasted_time = Model('user_bonus')->lasted_binded(array('type_id' => $type->getType_id()));
                 if($lasted_time > 0) {
                     $period = $lasted_time - $type->get_start_time();
-                    $period = intval($period / 60);
                     $type_info['binded_period'] = $period == 0 ? 1 : $period;
                 }
                 $type_info['binded_over'] = 1;
@@ -258,6 +257,9 @@ class manager
         if($ret == true) {
             $user_bonus = user_bonus::create_by_sn($bonus_sn);
             dcache($user_bonus->type_sn(),self::type_prefix);
+            return true;
+        } else {
+            return false;
         }
     }
 

+ 7 - 3
helper/bonus/type.php

@@ -29,7 +29,7 @@ class type
     const def_maxamount = 200.00;
     const def_minnum = 1;
 
-    const def_period_day = 10;
+    const def_period_day = 1;
 //    private $type_id;      // '表ID\n',
 //    private $type_sn;      // '对应的唯一识别号码',
 //    private $type_name;      // '红包名称',
@@ -61,7 +61,8 @@ class type
         }
         $this->mParam['type_name'] = sprintf("%s发的红包.",$this->mParam['sender_name']);
         $this->mParam['send_start_date'] = time();
-        $this->mParam['send_end_date'] = time() + self::def_period_day * 60 * 60 * 24;
+        //$this->mParam['send_end_date'] = time() + self::def_period_day * 60 * 60 * 24;
+        $this->mParam['send_end_date'] = time() + 5 * 60;
 
         if($this->isFixedAmount()) {
             $this->mParam['min_amount'] = 0;
@@ -121,6 +122,9 @@ class type
     public function sender_name() {
         return $this->mParam['sender_name'];
     }
+    public function sender_id() {
+        return $this->mParam['sender_id'];
+    }
     public function isStart() {
         $start_time = intval($this->mParam['send_start_date']);
         if($start_time === 0) {
@@ -139,7 +143,7 @@ class type
             return false;
         }
         else {
-            return time() > $end_time;
+            return time() >= $end_time;
         }
     }
     public function binded_num() {

+ 4 - 3
helper/bonus/user_bonus.php

@@ -31,7 +31,9 @@ class user_bonus
     public function isBinded() {
         return (intval($this->mParamer['bonus_status']) >= 2);
     }
-    public function isGrabed() {
+    public function grab_time()
+    {
+        return intval($this->mParamer['grab_time']);
     }
     public function bonus_sn() {
         return $this->mParamer['bonus_sn'];
@@ -46,7 +48,6 @@ class user_bonus
         $val = intval(floatval($this->mParamer['bonus_value']) * 100 + 0.5);
         return floatval($val) / 100;
     }
-
     public function type_sn() {
         return $this->mParamer['type_sn'];
     }
@@ -76,7 +77,7 @@ class user_bonus
         $get_time = $this->mParamer['get_time'];
         return strftime("%m-%d %H:%M",$get_time);
     }
-
+    
     static public function create_by_param($param) {
         return new user_bonus($param);
     }

+ 46 - 0
helper/configure.php

@@ -0,0 +1,46 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: stanley-king
+ * Date: 16/5/24
+ * Time: 下午6:07
+ */
+
+function is_debug()
+{
+    if(defined('DEBUG_MODE') && DEBUG_MODE == true) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+function is_publish()
+{
+    if(defined('MOBILE_PUBLISH') && MOBILE_PUBLISH == false) {
+        return false;
+    } else {
+        return true;
+    }
+}
+
+function is_pushoms()
+{
+    if(is_publish()) return true;
+    if(is_debug() == false) return true;
+
+    if(defined('PUSH_OMS') && PUSH_OMS == true) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+function is_localdebug()
+{
+    if(defined('LOCAL_DEBUG') && LOCAL_DEBUG == true) {
+        return true;
+    } else {
+        return false;
+    }
+}

+ 1 - 1
helper/fcgi_server.php

@@ -110,7 +110,7 @@ class fcgi_server
             fcgi_headers_sent();
             $contents = ob_get_clean();
             fcgi_echo($contents);
-            Log::record("return msg={$contents}",Log::DEBUG);
+            //Log::record("return msg={$contents}",Log::DEBUG);
 
             session::instance()->end();
             fcgi_finish();

+ 26 - 6
helper/kdn_helper.php

@@ -18,16 +18,32 @@ class kdn_helper
     static public function query($shipperCode, $logisticCode)
     {
         $requestData = json_encode(array('ShipperCode' => $shipperCode,'LogisticCode' => $logisticCode));
+
+        $account = self::get_account();
+        Log::record("EBusinessID={$account}",Log::DEBUG);
         $datas = array(
-            'EBusinessID' => '1256051',
+            'EBusinessID' => $account['EBusinessID'],
             'RequestType' => '1002',
             'RequestData' => urlencode($requestData),
             'DataType' => '2',
-            'DataSign' => self::encrypt($requestData, '6718d260-e2b6-4329-ad78-daff173309ac')
+            'DataSign' => self::encrypt($requestData, $account['AppID'])
         );
         $result = http_post_data(self::req_url,$datas);
         return $result;
     }
+    static public function cur_businessid() {
+        $account = self::get_account();
+        return $account['EBusinessID'];
+    }
+
+    static public function get_account()
+    {
+        if(defined('MOBILE_PUBLISH') && MOBILE_PUBLISH == true) {
+            return array('EBusinessID' => '1256766','AppID' => '22c88d88-3565-4023-b5ac-0201792869ed');
+        } else {
+            return array('EBusinessID' => '1256051','AppID' => '6718d260-e2b6-4329-ad78-daff173309ac');
+        }
+    }
 
     static private function encrypt($data, $appkey)
     {
@@ -59,12 +75,14 @@ class kdn_helper
     {
         $datas = array(array('Code' => $e_code,'Item' => array(array('No' => $logisticCode,'Bk' => $order_sn))));
         $requestData = json_encode($datas);
+
+        $account = self::get_account();
         $datas = array(
-            'EBusinessID' => '1256051',
+            'EBusinessID' => $account['EBusinessID'],
             'RequestType' => '1005',
             'RequestData' => urlencode($requestData),
             'DataType' => '2',
-            'DataSign' => self::encrypt($requestData, '6718d260-e2b6-4329-ad78-daff173309ac')
+            'DataSign' => self::encrypt($requestData, $account['AppID'])
         );
         $result = http_post_data(self::req_url, $datas);
         return $result;
@@ -75,8 +93,10 @@ class kdn_helper
         $order_sn = $data['CallBack'];
         if(empty($order_sn)) return;
 
-        $key = "express_" . $data['LogisticCode'];
-        wkcache($key, $data, 3600 * 24 * 30);
+        $e_code = $data['ShipperCode'];
+        $shipping_code = $data['LogisticCode'];
+        $key = "express_{$e_code}_{$shipping_code}";
+        wkcache($key, $data);
         // 数据解析
         switch ($data['State'])
         {

+ 22 - 1
helper/predeposit_helper.php

@@ -48,6 +48,17 @@ class predeposit_helper
         $this->model_pd->changePd("bonus_add_money", $data);
     }
 
+    public function bonus_refund($mod_pred,$sender_id,$sener_name,$amount,$type_sn)
+    {
+        $log_data = array();
+        $log_data['member_id']   = $sender_id;
+        $log_data['member_name'] = $sener_name;
+        $log_data['amount'] = $amount;
+        $log_data['type_sn'] = $type_sn;
+
+        $mod_pred->changePd('bonus_refund',$log_data);
+    }
+
     public function pay_add_money($paysn,$total_fee)
     {
 
@@ -148,6 +159,10 @@ class predeposit_helper
                 $item['title'] = "发出红包";
                 $item['sn'] = '';
             }
+            else if($type == 'bonus_refund') {
+                $item['title'] = "红包退款";
+                $item['sn'] = '';
+            }
             else if($type == 'bonus_add_money') {
                 $item['title'] = "{$admin_name}的红包";
                 $item['sn'] = '';
@@ -184,7 +199,13 @@ class predeposit_helper
     //返回分
     public function calc_pred($order_amount,$avail_amound,$pd_amount,&$no_cash)
     {
-        $cur_used = intval($order_amount * 0.20 + 0.5);
+        if(is_pushoms()) {
+            $scale = 0.30;
+        } else {
+            $scale = 0.99;
+        }
+
+        $cur_used = intval($order_amount * $scale + 0.5);
         $cur_used = $cur_used > $avail_amound  ? $avail_amound : $cur_used;
 
         if($order_amount == $cur_used) {

+ 1 - 2
request_helper.php

@@ -209,8 +209,7 @@ class request_helper
         $_SERVER[REQUEST_TIME] = intval($tm['sec']);
 
         $fields = self::SRV_PARAMS();
-        foreach ($fields as $field)
-        {
+        foreach ($fields as $field) {
             $param = fcgi_getparam($field);
             $_SERVER[$field] = $param;
         }

+ 28 - 9
helper/session.php

@@ -47,8 +47,6 @@ class session
         $this->fdestroy = false;
         session_start();
         $_SESSION['MPHPSESSID'] = $_COOKIE[self::session_name];
-//        Log::record("_SESSION[MPHPSESSID]=" . $_SESSION['MPHPSESSID'], Log::DEBUG);
-
     }
 
     public function end()
@@ -82,14 +80,29 @@ class session
     }
     public function onRead($rsid)
     {
+        //这段代码为了确保内置H5,直接使用客户端的session 状态。
         $sid = $_COOKIE[self::session_name];
+        Log::record("MPHPSESSID = {$sid}." , Log::DEBUG);
+
+        if(isset($_POST['HPHPSESSID']) && !empty($_POST['HPHPSESSID']))
+        {
+            $msid = $_POST['HPHPSESSID'];
+            Log::record("HPHPSESSID = {$msid}." , Log::DEBUG);
+
+            if($sid != $msid) {
+                $sid = $msid;
+                $this->set_cookie($sid);
+                $_COOKIE[self::session_name] = $sid;
+            }
+        }
+        Log::record("HPHPSESSID = {$msid}.",Log::DEBUG);
+
         if(empty($sid))
         {
             $ret = session_regenerate_id(false);
             if($ret == true) {
                 $sid = session_id();
-                $this->expire_time = time() + self::expire_min * 60;
-                fcgi_setcookie("MPHPSESSID","{$sid}",$this->expire_time,'/', '.lrlz.com');
+                $this->set_cookie($sid);
                 $_COOKIE[self::session_name] = $sid;
                 $this->sessid = $sid;
             } else {
@@ -107,8 +120,7 @@ class session
                 $ret = session_regenerate_id(false);
                 if($ret == true) {
                     $sid = session_id();
-                    $this->expire_time = time() + self::expire_min * 60;
-                    fcgi_setcookie("MPHPSESSID","{$sid}",$this->expire_time,'/', '.lrlz.com');
+                    $this->set_cookie($sid);
                     $this->sessid = $sid;
                     $_COOKIE[self::session_name] = $sid;
                 } else {
@@ -144,7 +156,14 @@ class session
     public function onGc($expire) {
         return true;
     }
-}
-
-
 
+    private function set_cookie($sid)
+    {
+        $this->expire_time = time() + self::expire_min * 60;
+        if(is_localdebug()) {
+            fcgi_setcookie("MPHPSESSID","{$sid}",$this->expire_time);
+        } else {
+            fcgi_setcookie("MPHPSESSID", "{$sid}", $this->expire_time, '/', '.lrlz.com');
+        }
+    }
+}

+ 0 - 1
helper/user_helper.php

@@ -70,7 +70,6 @@ class user_helper
 
         $info = array();
         $info['member_nickname'] = $user['nickname'];
-        //$info['member_wxopenid'] = $user['openid'];
         $info['member_avatar'] = $user['headimgurl'];
         $info['member_sex'] = intval($user['sex']);
 

+ 15 - 6
mobile/alipay_notify_url.php

@@ -31,6 +31,7 @@ if ($verify_result)
         if($chk == false) {
             Log::record("AliPay check: pay_sn={$pay_sn},total_fee={$total_fee},need_pay={$need_pay}",Log::WAIT_HANDLE);
             echo("fail");
+            return;
         }
         else
         {
@@ -40,24 +41,32 @@ if ($verify_result)
             if ($cb_info['state'] == false) {
                 Log::record("update_order fail: pay_sn={$pay_sn}", Log::DEBUG);
                 echo('fail');
-            } else {
-                $logic_delivery = Logic('delivery');
-                $ret = $logic_delivery->putOrder($pay_sn, $trade_no);
-                Log::record("update_order success: pay_sn={$pay_sn}", Log::DEBUG);
-                echo('success');
+                return;
             }
+            else
+            {
+                if(is_pushoms()) {
+                    $logic_delivery = Logic('delivery');
+                    $ret = $logic_delivery->putOrder($pay_sn, $trade_no);
+                    Log::record("update_order success: pay_sn={$pay_sn}", Log::DEBUG);
+                }
 
+                echo('success');
+                return;
+            }
          }
     }
     else if ($trade_status == 'WAIT_BUYER_PAY') {
 
     }
     echo("success"); // 交易正确时,返回success
+    return;
 }
 else
 {
-    echo("fail");  // 验证错误时,返回fail
     Log::record("verify notify fail : pay_sn={$pay_sn}");
+    echo("fail");
+    return;
 }
 
 ?>

+ 7 - 5
mobile/control/app_pay.php

@@ -98,11 +98,13 @@ class app_payControl extends mbMemberControl
             // 推送到oms
             if (isset($result) && $result['state'])
             {
-                $logic_delivery = Logic('delivery');
-                $ret = $logic_delivery->putOrder($pay_sn, $pay_sn);
-
-                if(empty($ret)) { //todo must add to 定时任务
-                    Log::record("Put order to oms error: pay_sn={$pay_sn},bonus pay.",Log::ERR);
+                if(is_pushoms())
+                {
+                    $logic_delivery = Logic('delivery');
+                    $ret = $logic_delivery->putOrder($pay_sn, $pay_sn);
+                    if(empty($ret)) { //todo must add to 定时任务
+                        Log::record("Put order to oms error: pay_sn={$pay_sn},bonus pay.",Log::ERR);
+                    }
                 }
             }
         }

+ 72 - 15
mobile/control/bonusex.php

@@ -38,9 +38,6 @@ class bonusexControl extends mobileControl
         }
     }
 
-    //打开红包页面:
-    //1:如果已经被抢光,显示已经被抢光界面
-    //2:
     public function openOp()
     {
         if(!isset($_GET['type_sn']) || empty($_GET['type_sn'])) {
@@ -70,14 +67,24 @@ class bonusexControl extends mobileControl
             $data = array('type_info' => $type_info, 'mine_bonus' => $mine_bonus,'binded_info' => $binded_info);
             if($bonus->isBinded()) {
                 return self::outsuccess($data,"bonus/content");
-            } else {
-                return self::outsuccess($data,"bonus/bind");
+            }
+            else
+            {
+                $type = \bonus\type::crate_by_paramer($type_infos['type_info']);
+                if($type->isEnd()) {
+                    return self::outsuccess(NULL,"bonus/end");
+                } else {
+                    return self::outsuccess($data,"bonus/bind");
+                }
             }
         }
         else
-        {
+        { //我没有抢过的情况
             $type = \bonus\type::crate_by_paramer($type_infos['type_info']);
-            if($type->binded_over()) {
+            if($type->isEnd()) {
+                return self::outsuccess(NULL,"bonus/end");
+            }
+            else if($type->binded_over()) {
                 return self::outsuccess(array('type_info' => $type_info,'msg' => "手慢了,红包派完了"),"bonus/over");
             } else {
                 return self::outsuccess(array('type_info' => $type_info),"bonus/open");
@@ -116,17 +123,21 @@ class bonusexControl extends mobileControl
         if(empty($type_infos)) {
             return self::outerr(errcode::ErrBonus,"无此红包.");
         }
-        $this->fileter_typeinfos($type_infos,$type_info,$binded_info);
 
+        $this->fileter_typeinfos($type_infos,$type_info,$binded_info);
         $mine_bonus = bonus_helper::get_mine_by_typesn($type_sn);
         if($mine_bonus != false)
         { //显示我抢到的红包,按照状态进行判断
             $bonus_obj = \bonus\user_bonus::create_by_param($mine_bonus);
             $mine_bonus = bonus_helper::filter_bonus($mine_bonus);
+            $type = \bonus\type::crate_by_paramer($type_infos['type_info']);
 
             if($bonus_obj->isBinded()) {
                 return self::outsuccess(array('type_info' => $type_info, 'mine_bonus' => $mine_bonus,'binded_info' => $binded_info),"bonus/content");
             }
+            elseif($type->isEnd()) {
+                 return self::outsuccess(array('type_info' => $type_info),"bonus/end");
+            }
             else
             {
                 if(user_helper::isVerfiyMobile())
@@ -146,11 +157,14 @@ class bonusexControl extends mobileControl
         else
         {
             $type = \bonus\type::crate_by_paramer($type_infos['type_info']);
-            if($type->binded_over()) {
+            if($type->isEnd()) {
+                return self::outsuccess(array('type_info' => $type_info),"bonus/end");
+            }
+            elseif($type->binded_over()) {
                 return self::outsuccess(array('type_info' => $type_info,'msg' => "手慢了,红包派完了"),"bonus/over");
             }
             else
-            {//从库里抢一个红包逻辑
+            {
                 $bonus = bonus_helper::grab_bonus($type_sn);
                 if($bonus == false) {
                     return self::outsuccess(array('type_info' => $type_info,'msg' => "手慢了,红包派完了"),"bonus/over");
@@ -198,7 +212,13 @@ class bonusexControl extends mobileControl
             return self::outsuccess(array('type_info' => $type_info, 'mine_bonus' => $mine_bonus,'binded_info' => $binded_info),"bonus/content");
         }
 
-        if(user_helper::isVerfiyMobile()) {
+        $type_sn = $bonus_obj->type_sn();
+        $type_infos = bonus_helper::get_typeinfo($type_sn);
+        $type = \bonus\type::crate_by_paramer($type_infos['type_info']);
+        if($type->isEnd()) {
+            return self::outsuccess(array('type_info' => $type_infos['type_info']),"bonus/end");
+        }
+        elseif(user_helper::isVerfiyMobile()) {
             $mobile = user_helper::cur_mobile();
         }
         else
@@ -282,6 +302,17 @@ function bonus_output_grabinfo($output)
     }
 }
 
+function bonus_output_sender($output)
+{
+    $type_info = $output['type_info'];
+    if(!empty($type_info)) {
+        $type = \bonus\type::crate_by_paramer($type_info);
+        echo($type->sender_name());
+    } else {
+        echo("");
+    }
+}
+
 function bonus_output_openurl($output)
 {
     $type_info = $output['type_info'];
@@ -348,19 +379,45 @@ function bonus_output_mine($output)
     }
 }
 
+function bonus_out_bindtimeout($output)
+{
+    $mine_bonus = $output['mine_bonus'];
+    if(!empty($mine_bonus))
+    {
+        $bonus = \bonus\user_bonus::create_by_param($mine_bonus);
+        $grab_time = $bonus->grab_time();
+        $time_out = 600;
+
+        if($grab_time > 0)
+        {
+            if($grab_time + $time_out <= time() - 60) {
+                return '您的红包随时可能被抢走,抓紧领啊~';
+            } else {
+                $left_time = $grab_time + $time_out - time();
+                $mins = $left_time / 60;
+                return "请{$mins}分钟内,输入手机号领取红包";
+            }
+        }
+    }
+
+    return '';
+}
+
 function bonus_out_bindedtime($period)
 {
-    $min = 60;
+    $min  = 60;
     $hour = 3600;
-    $day = 24 * 3600;
+    $day  = 24 * 3600;
 
     $days = intval($period / $day);
     $period = $period % $day;
+
     $houres = intval($period / $hour);
     $period = $period % $hour;
-    $mins = intval($period / $min);
 
-    if($period % $min > 0) {
+    $mins = intval($period / $min);
+    $period = $period % $min;
+    if($period > 0) {
         $mins += 1;
     }
 

+ 2 - 2
mobile/control/login.php

@@ -37,7 +37,7 @@ class loginControl extends mobileHomeControl
     public function loginOp()
     {
         if ($_SESSION['is_login'] == '1') { //检查是否已经登录
-            return self::outsuccess(array('member_id' => $_SESSION['member_id']));
+            return self::outsuccess(array('member_id' => $_SESSION['member_id'],'HPHPSESSID' => $_SESSION['MPHPSESSID']));
         }
 
         if (process::islock('login')) { //检查登录操作是否已经锁定
@@ -96,7 +96,7 @@ class loginControl extends mobileHomeControl
         Model('goods_browse')->mergebrowse($_SESSION['member_id'], $_SESSION['store_id']);
         $this->addMbUseToken($_SESSION['MPHPSESSID']);
 
-        return self::outsuccess(array('member_id' => $_SESSION['member_id']));
+        return self::outsuccess(array('member_id' => $_SESSION['member_id'],'HPHPSESSID' => $_SESSION['MPHPSESSID']));
     }
 
     private function register_open($model_member,$type,$openid)

+ 0 - 1
mobile/control/member_feedback.php

@@ -14,7 +14,6 @@ defined('InShopNC') or exit('Access Invalid!');
 
 class member_feedbackControl extends mobileControl //mbMemberControl
 {
-
     public function __construct()
     {
         parent::__construct();

+ 1 - 1
mobile/control/member_order.php

@@ -231,7 +231,7 @@ class member_orderControl extends mbMemberControl
         $e_code = $express[$order_info['extend_order_common']['shipping_express_id']]['e_kdn_code'];
         $e_name = $express[$order_info['extend_order_common']['shipping_express_id']]['e_name'];
 
-        $key = "express_" . $order_info['shipping_code'];
+        $key = "express_{$e_code}_" . $order_info['shipping_code'];
         $deliver_info = rkcache($key);
         if (empty($deliver_info))
         {

+ 12 - 10
mobile/dispatch_notify.php

@@ -9,9 +9,9 @@
 require_once(BASE_ROOT_PATH . '/helper/kdn_helper.php');
 
 fcgi_header("Content-Type: text/plain; charset=UTF-8");
-try {
+try
+{
     //tid-订单号,status-1,consign_time-发货时间,logistics_no-快递流水,logistics_company-快递公司
-
     $order_sn = trim($_POST['tid']);
     $status = intval($_POST['status']);
     $consign_time = urldecode(trim($_POST['consign_time']));
@@ -30,26 +30,28 @@ try {
     $shipping_express_id = $express[0]['id'];
     $remote_addr = $_SERVER['REMOTE_ADDR'];
 
-    if (!empty($order_sn) && !empty($logistics_no)) {
-        if ($status == 1) {
+    if (!empty($order_sn) && !empty($logistics_no))
+    {
+        if ($status == 1)
+        {
             $order = Model('order');
             $ret = $order->setOrderDelivery($order_sn, $shipping_express_id, $logistics_no, $ship_time);
             if ($ret) {
-                //kdn_helper::subscribe($order_sn);
-                QueueClient::push('dispatchKDN',array('order_sn'=>$order_sn));
+                QueueClient::push('subscribeKDN',array('order_sn'=>$order_sn));
                 echo 'SUCCESS';
             } else {
-                echo 'AGAIN';
+                echo 'SUCCESS';
             }
         } else {
-           // kdn_helper::subscribe($order_sn);
-            QueueClient::push('dispatchKDN',array('order_sn'=>$order_sn));
+            QueueClient::push('subscribeKDN',array('order_sn'=>$order_sn));
             echo 'SUCCESS';
         }
     } else {
         echo 'FAIL';
     }
-} catch (Exception $e) {
+}
+catch (Exception $e)
+{
     Log::record($e->getMessage(), Log::ERR);
     echo 'AGAIN';
 }

+ 3 - 3
mobile/kdniao_notify.php

@@ -20,9 +20,9 @@ else
 {
     Log::record("start handle....",Log::DEBUG);
     $count = intval($deliver_info['Count']);
-    if($count <= 0 || $deliver_info['EBusinessID'] != '1256051') {
+    if($count <= 0 || $deliver_info['EBusinessID'] != kdn_helper::cur_businessid()) {
         $success = false;
-        $reson = "count={$count} or EBusinessID = {$deliver_info['EBusinessID']} != 1256051";
+        $reson = "count={$count} or EBusinessID = {$deliver_info['EBusinessID']} != " . kdn_helper::cur_businessid();
     }
     else
     {
@@ -32,6 +32,6 @@ else
     }
 }
 
-echo (json_encode(array('EBusinessID' => '1256051','UpdateTime' => strftime("%Y-%m-%d %H:%M:%S",time()), 'Success' => $success,'Reason' => $reson)));
+echo (json_encode(array('EBusinessID' => kdn_helper::cur_businessid(),'UpdateTime' => strftime("%Y-%m-%d %H:%M:%S",time()), 'Success' => $success,'Reason' => $reson)));
 
 ?>

+ 1 - 1
mobile/templates/default/bonus/bind.php

@@ -25,7 +25,7 @@
 
     <div class="linqu_box" id="bind_link">
         <div>
-            <p class="prompt tel_pro">请十分钟内,输入手机号领取红包</p>
+            <p class="prompt tel_pro"><?php bonus_out_bindtimeout($output); ?></p>
         </div>
         <div class="tel_box">
             <div class="tel">

+ 32 - 0
mobile/templates/default/bonus/end.php

@@ -0,0 +1,32 @@
+<!doctype html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <title>熊猫美妆红包</title>
+    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
+    <link rel="stylesheet" href="<?php echo RESOURCE_SITE_URL; ?>/mobile/bonus/css/common.css"/>
+    <script type="text/javascript" src="<?php echo RESOURCE_SITE_URL; ?>/mobile/bonus/js/zepto.min.js"></script>
+</head>
+
+<body>
+<div class="maincontent">
+    <div class="bg_position cloud_left"></div>
+    <div class="bg_position cloud_right"></div>
+    <div class="bg_position dot_left"></div>
+    <div class="bg_position dot_right"></div>
+    <div class="content center">
+        <div class="msg_box">
+            <p class="name"><?php bonus_output_sender($output); ?></p>
+        </div>
+        <div class="time_over">
+            <p>该红包已超过24小时。如已领取,</p>
+            <p>可在熊猫美妆APP中“我的红包”中查看</p>
+        </div>
+    </div>
+    <div class="bottom_pro center">
+        <p class="">独家运营70多个知名化妆品品牌的天猫官方旗舰店</p>
+        <p><s class="icon_logo"></s>丽人丽妆股份有限公司出品</p>
+    </div>
+</div>
+</body>
+</html>

+ 8 - 1
mobile/templates/default/bonus/open.php

@@ -39,15 +39,22 @@
             </div>
         </div>
         <input type="hidden" id="grab_url" value="<?php echo(bonus_output_graburl($output)); ?>">
+
+        <div class="bottom_pro center">
+            <p class="">独家运营70多个知名化妆品品牌的天猫官方旗舰店</p>
+            <p><s class="icon_logo"></s>丽人丽妆股份有限公司出品</p>
+        </div>
+        <input type="hidden" value="<?php echo($_SESSION['MPHPSESSID']); ?>" id="sessionId">
     </div>
     <script>
         $(function(){
             $('.open').on('touchstart',function(){
+                var sId=$('#sessionId').val();
                 $(this).hide();
                 $('#coin').addClass('gold_coin');
                var grab_url=$('#grab_url').val();
                 setTimeout(function(){
-                     window.location.href=grab_url;
+                     window.location.href=grab_url + '&HPHPSESSID=' + sId;
                 },500)
             })
         })

+ 8 - 5
mobile/wxnotify.php

@@ -42,7 +42,7 @@ fcgi_header("Content-Type: text/html; charset=UTF-8");
 
 try
 {
-    $content = $_SERVER['original_querystring'];//request_helper::content();
+    $content = $_SERVER['original_querystring'];
     Log::record("content = {$content}",Log::DEBUG);
     $result = WxPayResults::Init($content);
     $ret_wx = array();
@@ -56,13 +56,16 @@ try
 
         Log::record("out_trade_no={$out_trade_no} and pay_sn={$pay_sn} and trade_no = {$trade_no}",Log::DEBUG);
         $cb_info = app_payControl::update_order($pay_sn,$trade_no,'wxpay');
-
         if($cb_info['state'] == false) {
             Log::record('wxpay error.',Log::DEBUG);
-        } else {
+        }
+        else
+        {
             Log::record('wxpay success.',Log::DEBUG);
-            $logic_delivery = Logic('delivery');
-            $ret = $logic_delivery->putOrder($pay_sn, $trade_no);
+            if(is_pushoms()) {
+                $logic_delivery = Logic('delivery');
+                $ret = $logic_delivery->putOrder($pay_sn, $trade_no);
+            }
         }
 
         $ret_wx['return_code'] = 'SUCCESS';