对接接口(同步数据,上传数据)

目的:一个按钮,点击按钮,将该条数据的相关信息组装好后,去请求另一个系统的接口,以达到新增数据(同步数据)到另一个系统上去,简单的说,也就是将一个系统的数据同步到另一个系统上面的操作

步骤一:上传数据的方法编写,查询数据,组装必须数据,数据验证,放入接口方法,验证返回的信息,判断并输出到浏览器中

代码如下:

 public function uploadActHowjia(){

        $dataApiService = new DataApiService();
        // 组装门店必要的数据
        $id     = trim( input('id','','intval') );
        $act_id = trim( input('act_id','','intval') );
        //检查是否通过审核
        //$check_status   = Db::name('activity_shop')->where('id',$id)->value('status');
        $check_status   = shopModel::getActivityShopStatusValue($id);
        if( $check_status == 5){
            $this->error('已上传!不能再上传');
        }
        if( $check_status != 3){
            $this->error('相关信息尚未通过审核!');
        }
        $m_id   = shopModel::getValueByIdAndActId($id,$act_id);
        $shop   = shopModel::getInfoByIdAndActId($id,$act_id);
        if(!$shop){
            $this->error('活动门店不存在!');
        }
        //查询该活动门店的活动产品上传到好家网
        $good = shopModel::getInfosByMidAndActId($m_id,$act_id);
        if(!$good){
            $this->error('活动产品不存在!');
        }
        //查询该门店活动的活动优惠券
        $coupon = ActivityCoupon::getInfosByActIdAndMid($m_id,$act_id);
        if(!$coupon){
            $this->error('活动优惠券不存在!');
        }

        //上传活动门店
        $data_shop=array();
        $data_shop['act_id']   = trim( $shop['act_id'] ) ;                  //活动ID(必须)
        $data_shop['cat_id']   = trim( $shop['cat_id'] ) ;                  //门店分类ID(必须)
        $data_shop['shop_id']  = 0 ;                                        //对应集店网ID(必须)(暂定先为0)
        $data_shop['shop_name']    = trim( $shop['shop_name'] );            //商家名称(必须)
        $data_shop['shop_logo']    = trim( $shop['shop_logo'] );            //门店LOGO(必须)
        $data_shop['description']  = trim( $shop['description'] );
        $data_shop['keywords']     = trim( $shop['keywords'] );
        $data_shop['content']      = trim( $shop['content'] );
        $shopValidate  = Loader::validate('ActivityShop');
        if(!$shopValidate->scene('add')->check($data_shop)){
            $this->error('活动门店添加数据有误,'.$shopValidate->getError());
        }
            $s_data = $dataApiService->addActShop($data_shop);
            if($s_data['code'] != 200){
                $this->error($s_data['msg']);
            }
            //上传活动产品
            foreach( $good as $k=>$v ){
                $data_product = array();
                $data_product['act_id']     = trim( $good[$k]['act_id'] );         //活动id(必须)
                $data_product['pro_title']  = trim( $good[$k]['pro_title'] );      //产品标题(必须)
                $data_product['cat_id']     = trim( $good[$k]['cat_id'] );         //产品分类id(必须)
                $data_product['pro_attr'][] = trim( $good[$k]['pro_attr'] );       //产品标签(必须)
                $data_product['shopid']     = $id;                                 //好家网活动商家id(必须)
                $data_product['pro_pic']    = trim( $good[$k]['pro_pic'] );        //产品图片地址(必须)
                $data_product['market_price']      = trim( $good[$k]['market_price'] );
                $data_product['advance_amount']    = trim( $good[$k]['price'] );
                $data_product['pro_dec']    = trim( $good[$k]['pro_dec']);
                $data_product['content']    = trim( $good[$k]['content'] );
                //验证数据
                $productValidate = Loader::validate('ActivityProduct');
                if(!$productValidate->scene('add')->check($data_product)){
                    $this->error('活动产品添加数据有误,'.$productValidate->getError());
                }
                $p_data=$dataApiService->addActProduct($data_product);

                if($p_data['code'] != 200){
                    $this->error($p_data['msg']);
                }
            }
            //上传优惠券
            foreach( $coupon as $k=>$v ){
                $data_coupon=array();
                $data_coupon['act_id']       = trim( $coupon[$k]['act_id'] );
                $data_coupon['shop_id']      = $id;
                $data_coupon['co_name']      = trim( $coupon[$k]['co_name']);
                $data_coupon['co_description'] = trim( $coupon[$k]['co_description']);
                $data_coupon['co_content']   = trim( $coupon[$k]['co_content'] );
                $data_coupon['co_price']     = trim( $coupon[$k]['co_price'] );
                $data_coupon['co_sms_content'] = trim( $coupon[$k]['co_sms_content'] );
                $data_coupon['co_amount']    = trim( $coupon[$k]['co_amount'] );
                $data_coupon['co_starttime'] = $coupon[$k]['start_time'];
                $data_coupon['co_endtime']   = $coupon[$k]['end_time'];
                $data_coupon['starttime']    = $coupon[$k]['start_time'];
                $data_coupon['endtime']      = $coupon[$k]['end_time'];

                //验证数据
                $couponValidate = Loader::validate('ActivityCoupon');
                if(!$couponValidate->scene('add')->check($data_coupon)){
                    $this->error('优惠券添加数据有误,'.$couponValidate->getError());
                }
                $c_data=$dataApiService->addActCoupon($data_coupon);
                if($c_data['code'] != 200){
                    $this->error($c_data['msg']);
                }
            }
        $data['status'] = 5;
        $res            = shopModel::updateOneActivityShopById($id,$data);
        if($res){
            $this->success('上传成功!');
        }else{
            $this->error('上传失败!');
        }
    }

步骤二:步骤一就是基本的流程,里面的addActProduct(),addActProduct,addActCoupon()方法主要是接口的一些必要数据处理,主要是组装好接口的地址和需要添加的数据

/**
	 * 上传活动门店
	 * @param $post_data
	 * @return array
	 */
	public function addActShop($post_data){
		$_url=config('post_act_url');
		$_url.='Activityshop/addshop';//添加门店的
        return $this->requestData($_url,$post_data);
	}

	/**
	 * 上传产品
	 * @param $post_data
	 * @return array
	 */
	public function addActProduct($post_data){
		$_url=config('post_act_url');
		$_url.='Activityproduct/addProduct';//添加产品的
		return $this->requestData($_url,$post_data);
	}

	/**
	 * 上传优惠券
	 * @param $post_data
	 * @return array
	 */
	public function addActCoupon($post_data){
		$_url=config('post_act_url');
		$_url.='ActivityCoupon/addcoupon';//添加优惠券的
		return $this->requestData($_url,$post_data);
	}

步骤三:统一的requestData()方法主要是处理接口返回的值的一些逻辑处理

	/**
	 * 组装统一请求 TODO 可以用统一的,但是方便区分函数就用这样的方式
	 * @param $_url
	 * @param $post_data
	 * @return array
	 */
	private function requestData($_url,$post_data){
		//生成签名
		$r=self::makeSign();

		if (!isset($r['sign'])){
			$this->return_data['msg']='生成签名失败';
			return $this->return_data;
		}
		$_url.=("?sign=".$r['sign']."&t=".$r['timestamp']);
		$r_data = self::httpPost($_url,$post_data);
        $jsondata=json_decode($r_data);

        if ($jsondata->code==200){
			$this->return_data['data']=$jsondata->data;
			$this->return_data['code']=200;
			$this->return_data['msg']='ok';
		}else {
			$this->return_data['data']=$jsondata->data;
			$this->return_data['code']=$jsondata->code;
			$this->return_data['msg']=$jsondata->message;
		}

		return $this->return_data;
	}
/**
	 * 生成签名示例方法,建议自定义生成规则 (严格一点可以把每个请求连接 加入生成规则)
	 * @param $timestamp
	 * @param $api_key
	 * @return string
	 */
	private function makeSign(){
		$timestamp=time();
		$secert=config('myconfig.auth_api_key');
		$sign= md5($timestamp.$secert);
		$r['timestamp']=$timestamp;
		$r['sign']=$sign;
		return $r;
		
	}

步骤四:请求处理

/**
	 * 请求
	 * @param unknown $url
	 * @return mixed
	 */
	private function httpGet($url) {
	
		$ch = curl_init();
		
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$temp = curl_exec($ch);
		return $temp;
	}


	/**
	 * 用post请求
	 * @param $url
	 * @param $post_data
	 * @return mixed
	 */
	private  function httpPost($url,$post_data){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$temp = curl_exec($ch);
		return $temp;
	}

步骤五:洗洗睡。。。

    原文作者:@江江江
    原文地址: https://blog.csdn.net/qq_33273884/article/details/82893572
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞