Wechat.php 23.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
<?php

namespace app\api\controller\v1;
use app\server\Wechat as WehcatModule;
use app\common\controller\Api;

use think\Cache;
use think\Config;
use think\Db;
use think\Response;
use think\Validate;
use app\api\controller\Common;
/**
 * 首页公共
 */
class Wechat extends Api
{
	protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

    }
	/**
	 * 根据门店获取 appid等信息
	 */
	public function get_wx_config(){
		if(empty(request()->param('store_id'))){return $this->error('门店信息错误');}
		WehcatModule::getInstance(request()->param('store_id'));
		$data['appid'] = WehcatModule::$appid;
		$data['appsecret'] = WehcatModule::$appsecret;
		return $this->success('ok',$data);
	}

    /*
		1.前端获取jsjdk的配置
	*/
	public function get_jsjdk_config(){
		if(empty(request()->param('store_id'))){return $this->error('门店信息错误');}
		try{
			$param = request()->param();
			$url = urldecode($param['url']);
			$app = WehcatModule::getInstance(request()->param('store_id'))->initWechat();
			$app->jssdk->setUrl($url);
			$APIs = ['updateAppMessageShareData','updateTimelineShareData','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone','chooseWXPay','openLocation','getLocation'];
			$config = $app->jssdk->buildConfig($APIs, false);
		}catch(\Exception $e){
			$this->error($e->getMessage());
		}
		$this->success('配置获取成功', json_decode($config,true));
	}

	/*
		服务器跳转授权code测试

		https://coupon.xp.yn.cn/index.php/api/v1/Wechat/test_code
	*/
	public function test_code(){
		$code = request()->param('code');
		$app = WehcatModule::getInstance()->initWechat();
		if(empty($code)){
			//跳转官方
			$APPID = config("site.appid");
			$REDIRECT_URI = urlencode('https://coupon.xp.yn.cn/index.php/api/v1/Wechat/test_code');
			$SCOPE = 'snsapi_userinfo';//snsapi_base
			$redirect = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$APPID&redirect_uri=$REDIRECT_URI&response_type=code&scope=$SCOPE&state=STATE#wechat_redirect";
			$curUrl = request()->url(true);
			header("Location:".$redirect);

		}else{

			//模拟获取code
			echo $code;
			die;
			//解析code
			$user = $app->oauth->user();

			var_dump($user);die;
			/*
			$user的数据结构 snsapi_userinfo 授权获取
			object(Overtrue\Socialite\User)#143 (1) {
				  ["attributes":protected]=>
				  array(10) {
					["id"]=>
					string(28) "oFycus-NxBBtBjfyd_xClnPrdaok"
					["name"]=>
					string(23) "app.微信开发 陈工"
					["nickname"]=>
					string(23) "app.微信开发 陈工"
					["avatar"]=>
					string(134) "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJFicTnPRiaic62m4HY4YxrHPRKa92HQrvPOcYRAJSKLRYwCibFWuJCXUCoib9QpE2rKbs4WVVoXVDticdQ/132"
					["email"]=>
					NULL
					["original"]=>
					array(9) {
					  ["openid"]=>
					  string(28) "oFycus-NxBBtBjfyd_xClnPrdaok"
					  ["nickname"]=>
					  string(23) "app.微信开发 陈工"
					  ["sex"]=>
					  int(0)
					  ["language"]=>
					  string(0) ""
					  ["city"]=>
					  string(0) ""
					  ["province"]=>
					  string(0) ""
					  ["country"]=>
					  string(0) ""
					  ["headimgurl"]=>
					  string(134) "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJFicTnPRiaic62m4HY4YxrHPRKa92HQrvPOcYRAJSKLRYwCibFWuJCXUCoib9QpE2rKbs4WVVoXVDticdQ/132"
					  ["privilege"]=>
					  array(0) {
					  }
					}
					["token"]=>
					string(110) "69_a0ecHFb5w81Cen3R11WfYMO2nD88jiyhsLC7jfqmCYC71maesd2OaDEvH4LaQAZsYfejWGdGYEGRzKjCQu8kX7FBZc4_nJ6so3Cxn9E_mt0"
					["access_token"]=>
					string(110) "69_a0ecHFb5w81Cen3R11WfYMO2nD88jiyhsLC7jfqmCYC71maesd2OaDEvH4LaQAZsYfejWGdGYEGRzKjCQu8kX7FBZc4_nJ6so3Cxn9E_mt0"
					["refresh_token"]=>
					string(110) "69_tFnfQInYcufQQoK5DpstHgucGKGnZjA_Jido5TLyIR1ye3GNYnZS0eJLv5kJ7zJuoJiHD10mzH1wrLicGaFdet_NYkGTAhVZ17QIPMzKkr4"
					["provider"]=>
					string(6) "WeChat"
				  }
				}
				$user的数据结构 静默获取 snsapi_base
				{
					"id": "oFycus-NxBBtBjfyd_xClnPrdaok",
					"name": null,
					"nickname": null,
					"avatar": null,
					"email": null,
					"original": {
						"access_token": "69_SqtOdZrnGsLIb4LE2fg3GLYVTuxff9kqe2rRA8qYAnAhMP4Tgs0adKcoJcW6P5gL1HabRGP0BXFljLdxiSilZePmY0xBEM-6iDGdWk1xNwc",
						"expires_in": 7200,
						"refresh_token": "69_6hfHqqVMWVBIq1OYISnrMbjr5YyO9znGUwI5nwhNMRT_QrShqRd-oxivWYs9SCeLzZbY4Hb0OIejNyz3dNvBMwlPhjXL7C0fhK9wiiB_BLU",
						"openid": "oFycus-NxBBtBjfyd_xClnPrdaok",
						"scope": "snsapi_base"
					},
					"token": "69_SqtOdZrnGsLIb4LE2fg3GLYVTuxff9kqe2rRA8qYAnAhMP4Tgs0adKcoJcW6P5gL1HabRGP0BXFljLdxiSilZePmY0xBEM-6iDGdWk1xNwc",
					"access_token": "69_SqtOdZrnGsLIb4LE2fg3GLYVTuxff9kqe2rRA8qYAnAhMP4Tgs0adKcoJcW6P5gL1HabRGP0BXFljLdxiSilZePmY0xBEM-6iDGdWk1xNwc",
					"refresh_token": "69_6hfHqqVMWVBIq1OYISnrMbjr5YyO9znGUwI5nwhNMRT_QrShqRd-oxivWYs9SCeLzZbY4Hb0OIejNyz3dNvBMwlPhjXL7C0fhK9wiiB_BLU",
					"provider": "WeChat"
				}
			*/
			// $user 可以用的方法:
			// $user->getId();  // 对应微信的 OPENID
			// $user->getNickname(); // 对应微信的 nickname
			// $user->getName(); // 对应微信的 nickname
			// $user->getAvatar(); // 头像网址
			// $user->getOriginal(); // 原始API返回的结果
			// $user->getToken(); // access_token, 比如用于地址共享时使用
		}
	}

	/*
		2.网页授权
			2.1前端打开则跳转到授权页 由前端自行配置
			appid
			redirect_uri前端的路由首位,
			scope=snsapi_base 静默只能获取openid,
			     =snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
			https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
			2.2 由微信回跳后,获取code 和 state 参数,由前端post code给后台
				返回 token  前端存储 每次请求 放在header里
			2.3 分销地址 如 https://coupon.xp.yn.cn?store_id=1&activity_id=3&share_id=2
				假设 首页地址有参数 share_id store_id activity_id,则表示分销首页,因此
					2.3.1 未登录 则跳转官方,需要携带分销参数 登录成功后 获取token,再发送请求 share_id store_id activity_id
					2.3.2 已登录  有获取token,再发送请求 share_id store_id activity_id
					无地址参数则不发送请求
	*/

	public function get_user_info_by_code (){
		$user_id = 0;
		if(empty(request()->param('code'))){return $this->error('非法操作');}
		if(empty(request()->param('store_id'))){return $this->error('门店信息错误');}
		$store_id = request()->param('store_id');
		try{
			$app = WehcatModule::getInstance($store_id)->initWechat();
			$oauth = $app->oauth;
			// 获取 OAuth 授权结果用户信息
			$user = $oauth->user();
			$openid = $user->id;
			//如果是授权获取 则可以有
			$nickname = $user->nickname;
			$avatar = $user->avatar;
			//更新user表信息
			$save['nickname'] = $nickname;
			$save['openid'] = $openid;
			$save['avatar'] = $avatar;
			$save['status'] = 'normal';
			$save['jointime'] = $save['prevtime'] = $save['logintime'] = time();
			$save['loginip'] = $save['joinip'] = request()->ip();
			$save['verification_store_id'] = $store_id;
			$w['openid'] = $openid;
			$w['verification_store_id'] = $store_id;
			$user = Db::name('user')->where($w)->find();
			//存在更新否则新增
			if(empty($user)){
				Db::name('user')->insert($save);
			}else{
				Db::name('user')->where($w)->update($save);
			}
			//设置同域下的登录缓存
			$user = Db::name('user')->where($w)->find();
			//登录成功 存储服务器本地
			$res=$this->auth->direct($user['id']);
			//返回给前端
			$user_id = $user['id'];
		}catch(\Exception $e){
			$this->error($e->getMessage());
		}
		if($user_id !=0){

			$data['token'] = $this->auth->getToken();
			$data['user_info'] =$this->auth->getUserinfo();
			$this->success('完成',$data);
		}else{
			$this->error('code处理失败');
		}

	}



	/**注册 分销关系 如 http://coupon.cc/index.php/api/v1/wechat/register_relation?store_id=19&activity_id=3&share_id=3
	 * store_id,activity_id
	 * 关系 user表 id 和 pid
	 */
	public function register_relation(){
		//参数
		$time = time();
		$param = request()->param();
		if(!request()->isPost()){
			return $this->error('请求错误');
		}
		$my_user_id = $this->auth->id;
		if(empty($my_user_id)){return $this->error('用户信息错误');}
		if(empty($param['store_id'])){return $this->error('门店信息错误');}
		//记录门店浏览统计
		$this->store_record($param['store_id'],$my_user_id);

		if(empty($param['share_id'])){return $this->error('信息错误');}
		if(empty($param['activity_id'])){return $this->error('活动信息错误');}
		//检测是存在关系
		$w['id'] = $my_user_id;
		$myInfo = Db::name('user')->where($w)->find();
		if(empty($myInfo['pid'])){
			//更新分销关系
			//自己是代理,则点击链接无效
			$w1['user_id'] = $my_user_id;
			//$w1['verification_store_id'] = $param['store_id'];
			$role = Db::name('verification_staff')->where($w1)->find();
			if(in_array($role['type'],['1','3'])){
				return $this->error('我是代理不记录');
			}

			Db::name('user')->where($w)->update(['pid'=>$param['share_id'],'updatetime'=>$time]);
			return $this->success('更新关系');
		}else{
			if($myInfo['pid'] == $param['share_id']){
				//是我的上线
				return $this->success('是我的上线');
			}else{
				//不是我的上线
				return $this->success('不是我的上线');
			}
		}
	}

	/*
		门店分销记录

	*/
	private function store_record($store_id,$user_id){
		$data['verification_store_id'] = $store_id;
		$data['user_id'] = $user_id;
		$data['createtime'] = time();
		Db::name('verification_store_user_record')->insert($data);
	}


	/*
		3.订单支付 前端请求
			3.1 入库 订单状态
			3.2 入库完成 处理支付接口 返回给前端 成功下单的接口结构
			{"code":1,"msg":"下单成功","time":"1685349626","data":{"appId":"wx1c3cc5b4e2006be2","nonceStr":"647464fb20f0c","package":"prepay_id=wx29164027049900e6020fe5bc7628300000","signType":"MD5","paySign":"7EC048B24D643F7115DC0D6063A17E62","timestamp":"1685349627"}}
			wx.chooseWXPay({
				timestamp: <?= $config['timestamp'] ?>,
				nonceStr: '<?= $config['nonceStr'] ?>',
				package: '<?= $config['package'] ?>',
				signType: '<?= $config['signType'] ?>',
				paySign: '<?= $config['paySign'] ?>', // 支付签名
				success: function (res) {
					// 支付成功后的回调函数
				}
			});
			3.3 回调修改订单状态


	*/
	public function prepare_order($order_no = ''){
		if(empty($order_no)){
			return $this->error('预下单信息错误');
		}
		$my_user_id = $this->auth->id;

		if(empty($my_user_id)){return $this->error('用户信息错误');}
		$o_w["order_no"] = $order_no;
		$order_info = Db::name('verification_order')->where($o_w)->find();

		$user_id = $order_info['user_id'];
		$userInfo = Db::name('user')->where(['id'=>$user_id])->find();
		$out_trade_no = $order_no;
		$total_fee = $order_info['price'] * 100;
		//测试支付
		$total_fee  = mt_rand(1,10);//测试支付1分钱
		//测试结束
		$app = WehcatModule::getInstance($order_info['verification_store_id'])->initWechatPay();
		$result = $app->order->unify([
			'body' => '优惠券购买',
			'out_trade_no' => $out_trade_no,
			'total_fee' => $total_fee,
			'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
			'openid' => $userInfo['openid'],
		]);
		if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
			$prepay_id = $result['prepay_id'];
			$jssdk = $app->jssdk;
			$config = $jssdk->sdkConfig($prepay_id);
			return $config;

		}else{
			Db::name('wechat_pay_recode')->insert(['json'=>json_encode($result),'time'=>time(),'action'=>'prepare_order']);
			return $result;
		}

	}


	/*
		微信支付回调信息
		{"appid":"wx1c3cc5b4e2006be2","bank_type":"OTHERS","cash_fee":"10","fee_type":"CNY","is_subscribe":"Y","mch_id":"1609190540","nonce_str":"6477162663358","openid":"o5OQw6LSZr1gGhXWeYutDwjsu7UY","out_trade_no":"168552605462002","result_code":"SUCCESS","return_code":"SUCCESS","sign":"B3148E770FAEC4F6B6B0B40718D314DA","time_end":"20230531174105","total_fee":"10","trade_type":"JSAPI","transaction_id":"4200001852202305311195060106"}
	*/
	public function notify(){
		
		$xml = file_get_contents("php://input");

		$xmljson= json_encode(simplexml_load_string($xml, 'SimplexmlElement', LIBXML_NOCDATA ));//将对象转换个JSON
		$message = json_decode($xmljson,true);
		// 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
		Db::name('wechat_pay_recode')->insert(['json'=>json_encode($message),'time'=>time(),'action'=>'pay_notify']);
		$out_trade_no = $message['out_trade_no'];
		if ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS') {
			$o_w["order_no"] = $out_trade_no;
			$order_info = Db::name('verification_order')->where($o_w)->find();
			if($order_info['type'] != 1){
				//1. 更改状态信息
				$up['type'] = 1;
				$up['paytime'] = time();
				$up['payMode'] = '0';
				Db::name('verification_order')->where($o_w)->update($up);
				//2. 分销处理
				$this->sales_distribution($order_info);
			}
		} else {

		}
		// 返回状态
        $this->returnCode(true, 'OK');


		/*
		$xml = file_get_contents("php://input");
		$xmljson= json_encode(simplexml_load_string($xml, 'SimplexmlElement', LIBxml_NOCDATA));//将对象转换个JSON
		file_put_contents("json.txt",$xmljson);
		$xmlarray=json_decode($xmljson,true);//将json转换成数组
		file_put_contents("1_cc.log",json_encode($xmlarray),FILE_APPEND);
		*/
	}

	/**
     * 返回状态给微信服务器
     * @param boolean $returnCode
     * @param string $msg
     */
    private function returnCode($returnCode = true, $msg = null)
    {
        // 返回状态
        $return = [
            'return_code' => $returnCode ? 'SUCCESS' : 'FAIL',
            'return_msg' => $msg ?: 'OK',
        ];

        die($this->toXml($return));
    }

	/**
     * 输出xml字符
     * @param $values
     * @return bool|string
     */
    private function toXml($values)
    {
        if (!is_array($values)
            || count($values) <= 0
        ) {
            return false;
        }

        $xml = "<xml>";
        foreach ($values as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }


	/** 支付成功 则进入分销链条 2级分销
	 * 1. 上级 是代理人 则直接获得佣金 企业付款
	 * 2. 上级 是普通人 则直接获得某个门店的所有礼品券
	 * 3. 上级的上级 是代理人则直接获得佣金 企业付款
	 * 4. 上级的上级 是普通人,则直接获得某个门店的所有礼品券
	 *      A     ->    B    -> C 下单
	 *	$order_info 支付成功后的订单信息
	 */

	public function sales_distribution($order_info=[]){
		//测试
		//$order_info = Db::name('verification_order')->where("id='14'")->find();
		$time = time();
		if(empty($order_info)){ return $this->error('订单信息不存在');}
		$w['id'] = $order_info['user_id'];
		$myInfo = Db::name('user')->where($w)->find();
		//支付成功 自己领券
		$this->send_voucher($order_info['user_id'],$order_info['verification_coupon_ids'],$order_info['id'],$time);
		//是否有上级
		if(!empty($myInfo['pid'])){
			//上级
			try{
				$this->getParent($myInfo['pid'],$order_info['verification_coupon_ids'],$order_info['id']);
			}catch(\Exception $e){
				Db::name('wechat_pay_recode')->insert(['json'=>json_encode($e->getMessage()),'time'=>time(),'action'=>'sales_distribution']);
			}
			//上级的上级
			try{
				$w1['id'] = $myInfo['pid'];
				$myInfoP = Db::name('user')->where($w1)->find();
				if(!empty($myInfoP['pid'])){
					$this->getParent($myInfoP['pid'],$order_info['verification_coupon_ids'],$order_info['id']);
				}
			}catch(\Exception $e){
				Db::name('wechat_pay_recode')->insert(['json'=>json_encode($e->getMessage()),'time'=>time(),'action'=>'sales_distribution']);
			}
		}
	}

	//支付后,根据用户角色 处理对应的事情
	private function getParent($pid,$verification_coupon_ids,$order_id){

		//上级身份
		$time = time();
		$w1 = [];
		$w1['user_id'] = $pid;
		// $w1['verification_store_id'] = $verification_store_id;
		$role = Db::name('verification_staff')->where($w1)->find();
		if(in_array($role['type'],['1','3','0'])){
			//属于代理 发送红包
			$this->grant_red_packets($pid,$order_id);
		}else{
			//属于普通用户 则领取礼品券
			//$this->send_gift_certificate($pid,$verification_coupon_ids,$order_id,$time);
			//卡券发放规则
			$this->send_gift_certificate_url($pid,$verification_coupon_ids,$order_id,$time);
		}
	}

	//发放 对应活动的礼品券
	public function send_gift_certificate_url($pid,$order_id,$time){
		$order_info = Db::name('verification_order')->where(['id'=>$order_id])->find();
		$store = Db::name('verification_store')->where(['id'=>$order_info['verification_store_id']])->find();
		$activity = Db::name('verification_activity')->where(['id'=>$order_info['verification_activity_id']])->find();
		//获取门店下的礼品券
		if(!empty($activity['verification_coupon_ids'])){
			
			//判断当前父级的所有下级的订单数,是否满足 send_rule_limit 的规则
			$subIds = Db::name('user')->where(['pid'=>$pid])->column('id');
			$subOrderCount = Db::name('verification_order')->where(['user_id'=>['in',$subIds],'type'=>['>','0']])->count();
			
			//获取卡券
			//当前活动对应的所有券
			$coupon = Db::name('verification_coupon')->where(['id'=>['in',$activity['verification_coupon_ids']],'type'=>1,'send_rule_limit'=>$subOrderCount])->find();
			
			if(!empty($coupon)){
				//发送给pid用户
				$save = [];
				$save['verification_coupon_id'] = $store['verification_coupon_id'];
				$save['verification_store_id'] = $store['id'];
				$save['user_id'] = $pid;

				$save['type'] = 0;//使用情况
				$save['closetime'] = $coupon['closetime'];
				$save['receive_no'] = time().rand(1000,9999);
				$res = (new \app\api\controller\v1\Index())->build($save['receive_no']);
				$save['qr_code'] = $res;//二维码
				$save['createtime'] = $time;
				$save['verification_order_id'] = $order_id;
				$save['coupon_type'] = $coupon['type'];
				Db::name('verification_receive')->insert($save);
			}
		}
	}

	public function test_rule(){
		$pid = 23;
		$order_id = '223';
		$time = time();
		$this->send_gift_certificate_url($pid,$order_id,$time);
	}

	//发放 对应活动的礼品券
	public function send_gift_certificate($pid,$verification_coupon_ids,$order_id,$time){
		$order_info = Db::name('verification_order')->where(['id'=>$order_id])->find();
		$store = Db::name('verification_store')->where(['id'=>$order_info['verification_store_id']])->find();
		//获取门店下的礼品券
		if(!empty($store['verification_coupon_id'])){
			$coupon = Db::name('verification_coupon')->where(['id'=>$store['verification_coupon_id']])->find();
			//发送给pid用户
			$save = [];
			$save['verification_coupon_id'] = $store['verification_coupon_id'];
			$save['verification_store_id'] = $store['id'];
			$save['user_id'] = $pid;

			$save['type'] = 0;//使用情况
			$save['closetime'] = $coupon['closetime'];
			$save['receive_no'] = time().rand(1000,9999);
			$res = (new \app\api\controller\v1\Index())->build($save['receive_no']);
			$save['qr_code'] = $res;//二维码
			$save['createtime'] = $time;
			$save['verification_order_id'] = $order_id;
			$save['coupon_type'] = $coupon['type'];
			Db::name('verification_receive')->insert($save);
		}
	}
	//发放 对应活动包含的券
	public function send_voucher($pid,$verification_coupon_ids,$order_id,$time){
		$w1 = [];
		$w1['id'] = ['in',$verification_coupon_ids];
		$coupon = Db::name('verification_coupon')->where($w1)->select();
		if(!empty($coupon)){
			foreach($coupon as $k=>$v){
				$save = [];
				$save['verification_coupon_id'] = $v['id'];
				$save['verification_store_id'] = $v['verification_store_id'];
				$save['user_id'] = $pid;
				//用户是否已经领取该门店的券
				//$r = Db::name('verification_receive')->where($save)->find();
				//if(empty($r)){
					$save['type'] = 0;//使用情况
					$save['closetime'] = $v['closetime'];
					$save['receive_no'] =  time().rand(1000,9999);
					$res = (new \app\api\controller\v1\Index())->build($save['receive_no']);
					$save['qr_code'] = $res;//二维码
					$save['createtime'] = $time;
					$save['verification_order_id'] = $order_id;
					$save['coupon_type'] = $v['type'];
					Db::name('verification_receive')->insert($save);
				//}
			}
		}
	}




	// 发放红包 单位 分 最低100分,
	public function grant_red_packets($pid=0,$order_id=0){
		try{
			//测试 https://coupon.xp.yn.cn/api/v1/wechat/grant_red_packets
			//$order_id = 58;
			//$pid = 2;
			//测试结束
			$send_result = 0;
			$verification_order = Db::name('verification_order')->where(['id'=>$order_id])->find();
			$verification_store = Db::name('verification_store')->where(['id'=>$verification_order['verification_store_id']])->find();
			$user_info = Db::name('user')->where(['id'=>$pid])->find();
			$total_amount = $verification_store['commission'] * 100;
			//$total_amount = 100;
			$app = WehcatModule::getInstance($verification_order['verification_store_id'])->initWechatPay();
			$mch_billno=time().rand(10000,99999);
			$result = $app->redpack->sendNormal([
				'mch_billno'   => $mch_billno,
				'send_name'    => '佣金红包',
				're_openid'    => $user_info['openid'],
				'total_num'    => 1,  //固定为1,可不传
				'total_amount' => $total_amount,  //单位为分,不小于100
				'wishing'      => '祝福语',
				'act_name'     => '佣金分享红包到账',
				'remark'       => '感谢您的参与',
			]);

			if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
				//记录佣金表 verification_brokerage_record
				$send_result = 1;
			}
			Db::name('wechat_pay_recode')->insert(['json'=>json_encode($result),'time'=>time(),'action'=>'grant_red_packets']);
			$this->brokerage_record($verification_store,$user_info,$send_result,$verification_order,$mch_billno);
		}catch(\Exception $e){
			Db::name('wechat_pay_recode')->insert(['json'=>json_encode($result),'time'=>time(),'action'=>'grant_red_packets']);

		}
	}

	//佣金发放记录
	private function brokerage_record($verification_store,$user_info,$send_result,$verification_order,$mch_billno){
		//关于该笔订单是否有发送给这个人
		// $w_re = [];
		// $w_re['order_id'] = $verification_order['id'];
		// $w_re['send_user_id'] = $user_info['id'];
		// $r = Db::name('verification_brokerage_record')->where($w_re)->find();
		// if(!empty($r)){
		// 	return false;
		// }
		try{
			$record = [];
			$record['verification_store_id'] = $verification_store['id'];
			$record['commission'] = $verification_store['commission'];
			$record['send_user_id'] = $user_info['id'];
			$record['send_createtime'] = time();
			$record['send_result'] = $send_result;
			$record['send_reason'] = 'ID:'.$user_info['id'].'分享给ID:'.$verification_order['user_id'].',并且成功支付ID:'.$verification_order['id'];
			$record['order_id'] = $verification_order['id'];
			$record['mch_billno'] = $mch_billno;
			Db::name('verification_brokerage_record')->insert($record);
		}catch(\Exception $e){
			Db::name('wechat_pay_recode')->insert(['json'=>$e->getMessage(),'time'=>time()]);
		}

	}




}