<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

use app\common\library\Token;
use think\Db;
use app\common\model\UserDeviceInfo;
use onlogin\onlogin;

use addons\epay\library\Service;
//use addons\epay\library\Wechat;
use app\common\library\Wechat;

/**
 * 会员接口,登录,注册,修改资料等
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin','wechatlogin', 'register', 'resetpwd', 'changemobile', 'onlogin','getUserOpenid_gzh','jssdkBuildConfig'];
    protected $noNeedRight = '*';

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

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = input('account');
        $password = input('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = $this->userInfo('return');
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    //非首次注册男性用户每次打开app,系统自动推送女性(公会)打招呼消息3人次。
    private function firstopen_send($oneuser){
        //找出公会的人
        $map = [
            'gh_id'  => ['gt',0],
            'gender'  => 0,
        ];
        $ghuser = Db::name('user')->where($map)->orderRaw('rand()')->limit(3)->column('id');
        //dump($ghuser);

        //随机取出一句话
        $oneword = Db::name('plantask_accost')->orderRaw('rand()')->limit(3)->column('title');
        //dump($oneword);

        $tenim = new \app\common\library\Tenim;

        for($i = 0;$i < 3;$i++){
            $ghuser_one  = isset($ghuser[$i])  ? $ghuser[$i]  : $ghuser[array_rand($ghuser)];
            $oneword_one = isset($oneword[$i]) ? $oneword[$i] : $oneword[array_rand($oneword)];
            $tenim->sendMessageToUser($ghuser_one,$oneuser,$oneword_one);
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {

        $mobile = input('mobile');
        $captcha = input('captcha');

        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status == -1) {
                $this->error('账户已注销');
            }
            if ($user->status != 1) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);


        } else {
            $extend = [
//                'register_from' => input('register_from',''),
            ];
            $ret = $this->auth->register('', '', '', $mobile, $extend);

        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = $this->userInfo('return');
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    /*public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = $this->userInfo('return');
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }*/

    //微信登录+注册
    public function wechatlogin(){
        $nickname = input('nickname','');
        $avatar = input('avatar','');
        $gender = input('gender',1);
        $wechat_openid = input('wechat_openid','');

        if (!$wechat_openid) {
            $this->error(__('Invalid parameters'));
        }
        if($gender != 1){
            $gender = 0;
        }

        $user = \app\common\model\User::getByOpenid($wechat_openid);
        if ($user) {
            if ($user->status != 1) {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);


        } else {
            if (!$nickname || !$avatar) {
                $this->error(__('Invalid parameters'));
            }

            $reg_data = [
                'nickname'=>$nickname,
                'avatar'=>$avatar,
                'gender'=>$gender,
                'register_from' => input('register_from',''),
            ];
            $ret = $this->auth->openid_register($wechat_openid,$reg_data);

        }
        if ($ret) {
            $data = $this->userInfo('return');
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 运营商一键登录
     */
    public function onLogin()
    {
        $accessToken = input('accessToken');// 运营商预取号获取到的token
        $token = input('tokenT');// 易盾返回的token
        if (!$accessToken || !$token) {
            $this->error("参数获取失败!");
        }

        $params = array(
            // 运营商预取号获取到的token
            "accessToken" => $accessToken,
            // 易盾返回的token
            "token"       => $token
        );

        // 获取密钥配置
        $configInfo = config("onLogin");
        $onlogin = new onlogin($configInfo["secretid"], $configInfo["secretkey"], $configInfo["businessid"]);

        $onret = $onlogin->check($params);

//        $ret = [];
//        $ret["code"] = 200;
//        $ret["msg"] = "ok";
//        $ret["data"] = [
//            "phone" => "17574504021",
//            "resultCode" => 0
//        ];

        if ($onret["code"] == 200) {
            $mobile = $onret["data"]["phone"];
            if (empty($mobile)) {
                // 取号失败,建议进行二次验证,例如短信验证码
                $this->error("取号登录失败,请用验证码方式登录!");
            } else {
                // 取号成功, 执行登录等流程
                // 用户登录逻辑 === 开始

                $user = \app\common\model\User::getByMobile($mobile);
                if ($user) {
                    if ($user->status != 1) {
                        $this->error(__('Account is locked'));
                    }
                    //如果已经有账号则直接登录
                    $ret = $this->auth->direct($user->id);
                    $is_register = 0;


                } else {

                    $ret = $this->auth->register('', '', '', $mobile, []);
                    $is_register = 1;

                }


                if ($ret) {
                    $this->success(__('Logged in successful'), $this->auth->getUserinfo());
                } else {
                    $this->error($this->auth->getError());
                }
                // 用户登录逻辑 === 结束
            }
        } else {
            $this->error("登录失败,请用验证码方式登录!");
        }
    }

    //用户详细资料
    public function userInfo($type = 1){
        $info = $this->auth->getUserinfo();
        if($type == 'return'){
            return $info;
        }
        $this->success(__('success'),$info);
    }



    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        //退出im
//        $tenIm = new Tenim();
//        $tenIm->loginoutim($this->auth->id);

        //修改用户活跃0
        Db::name('user')->where('id',$this->auth->id)->update(['is_active' => 0]);

        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $field_array = ['nickname','introcode','gender','birthday','attribute','shoesize','height','weight','bio','avatar','photo_images','tag_ids','hide_is_finishinfo'/*,'wechat_account'*/];

        $data = [];
        foreach($field_array as $key => $field){

            //前端传不了post,改了
            /*if(!request()->has($field,'post')){
                continue;
            }*/
            if(!input('?'.$field)){
                continue;
            }

            $newone = input($field);

            if($field == 'avatar'){
                $newone = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
            }
            if($field == 'photo_images'){
                $newone = input('photo_images', '', 'trim,strip_tags,htmlspecialchars');
            }

            $data[$field] = $newone;
        }

        if(isset($data['birthday'])){
            $data['birthday'] = strtotime($data['birthday']);
        }

        if(isset($data['tag_ids'])){
            $data['tag_ids'] = implode(',',explode(',',$data['tag_ids']));
        }
        if(isset($data['introcode'])){
            $intro_user = Db::name('user')->where('introcode',$data['introcode'])->value('id');
            if(!$intro_user){
                $this->error('不存在的邀请人');
            }
            unset($data['introcode']);//别人的邀请码,不能改了自己的
            $data['intro_uid'] = $intro_user;
        }
        //dump($data);
        if(empty($data)){
            $this->error('没有任何改变');
        }

        //默认头像
        //现在没头像,也没穿头像,但是却传了性别
        if($this->auth->avatar == config('site.domain_cdnurl').'/avatar.png' && isset($data['gender']) && $data['avatar'] == config('site.domain_cdnurl').'/avatar.png'){
            if($data['gender'] == 1){
                $data['avatar'] = 'https://meet-1251365327.cos.ap-beijing.myqcloud.com/uploads/20220314/f9277fba97fd76d9ecfc63b506a3674a.png';
            }else{
                $data['avatar'] = 'https://meet-1251365327.cos.ap-beijing.myqcloud.com/uploads/20220314/5030460c05c86774f60123ffea7b78a1.png';
            }
        }
        //默认头像

        Db::startTrans();
        $update_rs = Db::name('user')->where('id',$this->auth->id)->update($data);
        if($update_rs === false){
            Db::rollback();
            $this->error('修改资料失败');
        }

        //tag任务赠送金币
        //上传头像加5金币
        /*if(isset($data['avatar'])){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,1);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }*/
        //上传本人语音介绍 10金币
        /*if(isset($data['audio_bio'])){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,6);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }*/
        //上传本人五张照片 10金币
        /*if(isset($data['photo_images']) && count(explode(',',$data['photo_images'])) >= 5){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,8);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }*/

        //所有资料完成
        /*$user_info = Db::name('user')->where('id',$this->auth->id)->find();
        if($user_info['avatar'] && $user_info['nickname'] && $user_info['mobile'] && $user_info['audio_bio'] && $user_info['photo_images']){
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,5);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
        }*/

        Db::commit();
        $this->success();
    }
    /**
     * 修改会员权限
     */
    public function setpower()
    {
        $is_vip = $this->is_vip($this->auth->id);
        if(!$is_vip){
            $this->error('VIP才能设置隐私权限');
        }

        $data = [
            'yinsi'   => input('yinsi',0),
            'yinshen' => input('yinshen',0),
            'wuhen'   => input('wuhen',0),
        ];

        $update_rs = Db::name('user_power')->where('id',$this->auth->id)->update($data);

        $this->success();
    }

    public function set_status_switch(){

    }

    /*
     * 修改用户的坐标
     * */
    public function change_longlat(){
        $longitude = input_post('longitude');
        $latitude  = input_post('latitude');
        $cityname  = input_post('cityname');
        if(empty($longitude) || empty($latitude) || empty($cityname)){
            $this->error();
        }

        $data = [
            'longitude' => $longitude,
            'latitude'  => $latitude,
            'cityname'  => $cityname,
        ];
        Db::name('user')->where('id',$this->auth->id)->update($data);
        $this->success();
    }


    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $oldcaptcha = $this->request->request('oldcaptcha');
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$oldcaptcha || !$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if($user->mobile == $mobile){
            $this->error('新手机号不能与旧手机号相同');
        }
        if (\app\common\model\User::where('mobile', $mobile)->find()) {
            $this->error(__('Mobile already exist'));
        }
        $result = Sms::check($user->mobile, $oldcaptcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($user->mobile, 'changemobile');
        Sms::flush($mobile, 'changemobile');
        $this->success();
    }
    /**
     * 微信注册来的,绑定手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function bindmobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');

        if(!empty($this->auth->mobile)){
            $this->error('已经绑定了手机号');
        }
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->find()) {
            $this->error('该手机号已被其他用户绑定');
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success('success',$this->userInfo('return'));
    }

    /**
     * 微信注册来的,绑定手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    /*public function bindopenid()
    {
        $user = $this->auth->getUser();
        $wechat_openid = $this->request->request('wechat_openid');

        if(!empty($this->auth->wechat_openid)){
            $this->error('已经绑定了微信号');
        }
        if (!$wechat_openid) {
            $this->error(__('Invalid parameters'));
        }

        if (\app\common\model\User::where('wechat_openid', $wechat_openid)->find()) {
            $this->error('该微信号已被其他用户绑定');
        }

        $user->wechat_openid = $wechat_openid;
        $user->save();

        $this->success('success',$this->userInfo('return'));
    }*/

    /**
     * 手机注册来的,绑定微信
     *
     * @ApiMethod (POST)
     * @param string $wechat_openid
     */
    public function bindopenid()
    {
        Db::startTrans();
        try {
            $code =  $this->request->param('code','');
            if(!$code){
                throw new Exception(__('Invalid parameters'));
            }
            //微信
            $wechat = new Wechat();
            $openid = $wechat->getOpenid($code);

            if(!$openid){
                throw new Exception('openid获取失败');
            }

            $user = model('User')->find($this->auth->id);
            if(!empty($user['wechat_openid'])/* && $openid != $user['openid']*/){
                throw new Exception('已经绑定了微信号');
            }
            $otherUserWhere['wechat_openid'] = $openid;
            $otherUserWhere['id'] = ['neq',$this->auth->id];
            $otherUser = model('User')->where($otherUserWhere)->find();
            if (!empty($otherUser)) {
                throw new Exception('该微信已被其他用户绑定过');
            }

            $user->wechat_openid = $openid;
            $userRes = $user->save();
            if (!$userRes) {
                throw new Exception('绑定微信失败');
            }
            Db::commit();
            $this->success('success',$this->userInfo('return'));
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }



    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        //$type = input("type");
        $type = 'mobile';
        $mobile = input("mobile");
        $email = input("email");
        $newpassword = input("newpassword");
        $captcha = input("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 修改密码
     *
     * @ApiMethod (POST)
     * @param string $newpassword 新密码
     * @param string $oldpassword 旧密码
     */
    public function changepwd(){
        $newpassword = input('newpassword');
        $oldpassword = input('oldpassword','');

        if (!$newpassword) {
            $this->error(__('Invalid parameters'));
        }
        if($this->auth->password && empty($oldpassword)){
            $this->error('原密码必填');
        }

        if(empty($this->auth->password)){
            $ret = $this->auth->changepwd($newpassword, '', true);
        }else{
            $ret = $this->auth->changepwd($newpassword,$oldpassword,false);
        }

        if ($ret) {
            $this->success('设置密码成功');
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 记录当前登陆的设备ID,设备信息,IP等
     */
    public function changeDeviceIp()
    {
        // 接口防并发
        if (!$this->apiLimit(1, 5000)) {
            return ;
        }

        $user = $this->auth->getUser();
        $ip = request()->ip();
        $deviceId = $this->request->request('device_id','');
        $phoneModel = $this->request->request('phone_model','');
        $brand = $this->request->request('brand','');
        $apiVersion = $this->request->request('api_version','');
        $deviceOs = $this->request->request('device_os','');

        if ($ip !== $user->loginip){
            $update = [];
            $update['id'] = $user->id;
            $update['loginip'] = $ip;
            \app\common\model\User::update($update);
        }

        $userDeviceInfo = UserDeviceInfo::get(['user_id'=>$user->u_id]);
        if (empty($userDeviceInfo)){
            $userDeviceInfo = new UserDeviceInfo();
            $userDeviceInfo->user_id = $user->u_id;
        }
        $userDeviceInfo->device_os = $deviceOs;
        $userDeviceInfo->device_id = $deviceId;
        $userDeviceInfo->phone_model = $phoneModel;
        $userDeviceInfo->brand = $brand;
        $userDeviceInfo->api_version = $apiVersion;
        $userDeviceInfo->save();

        //首页接口调用,这里不反回信息
//        $this->success("更新成功!");
    }

    //假注销
    public function cancleUser(){
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        //退出im
//        $tenIm = new Tenim();
//        $tenIm->loginoutim($this->auth->id);

        Db::name('user')->where('id',$this->auth->id)->update(['status'=>-1]);

        $this->auth->logout();
        $this->success('注销成功');
    }

    //修改用户活跃1
    public function useractive(){
        Db::name('user')->where('id',$this->auth->id)->update(['is_active' => 1,'active_time' => time()]);
        $this->success('success');
    }

    //APP 转化数据统计方案(即:APP 上报对接方案): 广告主上报激活数据,亿米平台搭建服务系统关联点击&下载数据和广告主提供的所有激活数据,将激活数据归因到对应广告。
    public function yimi_advert(){
        //http://trail.e.mi.com/global/log?appId={appid}&info={data}&conv_type={convType}&customer_id={customerId}
        $api_url      = 'http://trail.e.mi.com/global/log?';
        $api_url_test = 'http://trail.e.mi.com/global/test?';

        //应用id 1453045
        //秘钥A(encrypt_key):ZxdIaVHvFqSQYzWD
        //秘钥B(sign_key):uaeWeunykLRnkyLw
        $sign_key = 'uaeWeunykLRnkyLw'; //真的
        $encrypt_key = 'ZxdIaVHvFqSQYzWD';//真的

        $appid = '1453045';
        $conv_type = 'APP_REGISTER';
        $customer_id = '292232';

        //推荐模式
        /*$imei = md5('imei');
        $data = [
            'imei' => '91b9185dba1772851dd02b276a6c969e',
            'oaid' => '5fb96f268628810c',
            'conv_time' => '1504687208890',
            'client_ip' => '127.0.0.1',
            'ua' => 'Dalvik/2.1.0 (Linux; U; Android 11; M2012K11AC Build/RKQ1.200826.002)',
        ];*/

        //采用模式4
        /*
        $ua = input('ua','','trim');
        if(empty($ua)){
            return true;
        }
        $data = [
            'conv_time' => time().substr(microtime(),2,3),
            'client_ip' => request()->ip(),
            'ua' => $ua,
        ];
        */

        //采用模式3
        $oaid = input('oaid','','trim');
        if(empty($oaid)){
            return true;
        }
        $data = [
            'oaid' => $oaid,
            'conv_time' => time().substr(microtime(),2,3),
            'client_ip' => request()->ip(),
        ];

        $data_query = http_build_query($data);
        //dump($data_query);

        $property = $sign_key.'&'.urlencode($data_query);
        //dump($property);

        $signature = md5($property);
        //dump($signature);

        $base_data = $data_query .'&sign='.urlencode($signature);
        //echo $base_data;

        $info = urlencode(base64_encode($this->xor_enc($base_data, $encrypt_key)));
        //dump($info);

        $request_url = $api_url.'appId='.$appid.'&info='.$info.'&customer_id='.$customer_id.'&conv_type='.$conv_type;
        //echo $request_url;

        $result = curl_get($request_url);
        //dump($result);
        //日志
        $log = [
            'param' => $base_data,
            'url'   => $request_url,
            'result'=> $result,
            'createtime' => time(),
        ];
        Db::name('yimi_advert')->insertGetId($log);

        return true;
    }

    //亿米 异或加密,解密
    public function xor_enc($str,$key)
    {
        $crytxt = '';
        $keylen = strlen($key);
        for($i=0;$i<strlen($str);$i++)
        {
            $k = $i%$keylen;
            $crytxt .= $str[$i] ^ $key[$k];
        }
        return $crytxt;
    }

    //公众号获取openid
    public function getUserOpenid_gzh(){
        $configValue = Service::getConfig('wechat');

        $wechat = new Wechat($configValue['app_id'],$configValue['app_secret']);
        $rs = $wechat->getOpenid();
        $this->success('success',$rs);
    }
    /**
     * 微信内H5-JSAPI支付
     *
     */
    public function jssdkBuildConfig() {
        $url = $this->request->request("url");

        $configValue = Service::getConfig('wechat');
        $wechat = new Wechat($configValue['app_id'],$configValue['app_secret']);

        $sign = $wechat->getSignPackage(urldecode($url));
        $this->success("获取成功!",$sign);
    }



}