如何在套件crm中使用REST API发布数据

时间:2018-05-18 05:00:08

标签: php rest api suitecrm

这是我的rest.php文件

<?php
chdir('../../..');

require_once 'SugarWebServiceImplv4_1_custom.php';

$webservice_path = 'service/core/SugarRestService.php';
$webservice_class = 'SugarRestService';
$webservice_impl_class = 'SugarWebServiceImplv4_1_custom';
$registry_path = 'custom/service/v4_1_custom/registry.php';
$registry_class = 'registry_v4_1_custom';
$location = 'custom/service/v4_1_custom/rest.php';

require_once 'service/core/webservice.php';

这是我的SugarWebServiceImplv4_1_custom.php文件,其中我编写了自定义方法

<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if(!defined('sugarEntry')){
  define('sugarEntry', true);
}
require_once 'service/v4_1/SugarWebServiceImplv4_1.php';

class SugarWebServiceImplv4_1_custom extends SugarWebServiceImplv4_1
{ 
    public function custom_test($username)
    {
         $arr = array ('a'=>$username,'b'=>22,'c'=>32,'d'=>44,'e'=>55);

         return json_encode($arr);
        die;
    }
}

这是我的registry.php文件,我已经注册了我的自定义方法

<?php
    require_once 'service/v4_1/registry.php';
    class registry_v4_1_custom extends registry_v4_1
    {
        protected function registerFunction()
        {
            parent::registerFunction();

              $this->serviceClass->registerFunction('custom_test',
                                                  array(
                                                    'username'=>'xsd:string),
                                                  array(
                                                    'return'=>'tns:get_array')
                                                  );


        }
    }

问题是当我通过get方法传递数据时像这样

  

http://www.example.com/custom/service/v4_1_custom/rest.php?method=custom_test&input_type=json&response_type=json&rest_data=

     
    

{ “用户名”:“一些      用户名“}

  

我得到的结果,但我不知道如何通过IOS应用程序通过post方法传递它。我试图传递它,但我没有得到任何用户名。 我通过curl检查了响应,它正在使用curl,但我必须将它连接到IOS。 帮助将不胜感激

实际上我们正在使用Angular 5和Ionic 3为IOS构建混合应用程序 这是代码 AUTH-services.ts

public login(credentials){

        if(credentials.username === null || credentials.password === null){

            return Observable.throw("Please enter credentials");
        } else {

            this.username1 = credentials.username;
            this.password1 = credentials.password;

            return Observable.create(observer =>{
             // At this point make a request to your backend to make a real check!

            this.method1 = "custom_test";
            this.inputType = "JSON";
            this.responseType = "JSON";
            this.encryptionValue = "PLAIN";


            this.bodyData = {};    //get method calling
            console.log(JSON.stringify(this.bodyData));

             //Sending the Username and Password to the Web Server for authentication. Change the URL Get the response message
            this.servicesProvider.restApi("post","http://exmaple.com/custom/service/v4_1_custom/rest.php",this.bodyData).then(
                (res) => {
                    console.log("Response stringify :",JSON.stringify(res));
                    console.log("Response parse :", res);

                    console.log("Status :",res.status);
                    this.response = res.status;  //TODO: Replace res.username with res.message as we have to check for user exist or not.
                    if(this.response == "success out") {
                        this.success = true;

                        this.storage.set("status",this.response); //Username value stored in localstorage

                        this.currentUser = new User('Simon', 'saimon@devdactic.com');
                        observer.next(this.success);
                        observer.complete();
                    } else {
                        this.success = false;
                        observer.next(this.success);
                        observer.complete();
                    }
                } 
            ); 

    }

这是services.ts文件。这是一个常见的rest api文件,用于发送rest api请求。

restApi(method,url,data) {

      console.log("inside restApi");


    switch(method) {
      case 'post' : { 
                    console.log("Inside Post Method");
                    /*
                    return this.httpClient.post(url,data)
                    .subscribe(
                      (res:any) => {
                        console.log("POST response below");
                        console.log(res.username);
                        this.responseData = JSON.stringify(res);
                        console.log("ResponseData Value");
                        console.log(this.responseData);

                        return this.responseData;
                      }); */

                     let headers = new Headers({'content-type':'application/json'});
                     let options = new RequestOptions({ headers:this.headers });
                     this.responseFromFunction = this.http.post(url,data).toPromise()
                     .then(this.extractData)
                     .catch(this.handleError);

                     break; 

      }

      case 'get' : {
                    console.log("Inside Get Method");
                    let headers = new Headers({'content-type':'application/json'});
                    let options = new RequestOptions({ headers:this.headers });
                    this.responseFromFunction = this.http.get(url, options).toPromise()
                    .then(this.extractData)
                    .catch(this.handleError);
                    break;
      }

      case 'put' : {
                    console.log("Inside Put Method");
                    this.responseFromFunction = this.httpClient.put(url,data)
                    .subscribe((res:any) => {
                      console.log(res);
                    });
                    break;
      }

      case 'delete' : {
                        console.log("Inside Delete Method");
                        this.responseFromFunction = this.httpClient.delete(url)
                        .subscribe((res:any) => {
                          console.log(res);
                        });
                        break;

      }

      default : {
                    this.responseFromFunction = {"message":"error"};
                console.log("Unknow Method Entered. Or write method in small lowercase only"); 
                // return "Invalid Method";
                }
    }
    console.log("Outside switch case");
    console.log(this.responseFromFunction);
    return this.responseFromFunction;
  }

  private extractData(res: Response) {
  //  console.log("Resp :", res.json());
  //  console.log("Stringy :", JSON.stringify(res));
    return res.json();

  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

}

这是邮递员的回复 enter image description here

我没有得到如何在rest_data中传递用户名

1 个答案:

答案 0 :(得分:1)

如果您使用的是Angular 5,那么:

Documentation read it

发出POST请求

应用程序经常将数据发布到服务器。他们在提交表格时发帖。在以下示例中,HeroesService在向数据库添加英雄时发布。 app / heroes / heroes.service.ts(addHero)

/** POST: add a new hero to the database */
addHero (hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
    .pipe(
      catchError(this.handleError('addHero', hero))
    );
}

HttpClient.post()方法类似于get(),因为它有一个类型参数(你希望服务器返回新的英雄),它需要一个资源URL。

需要两个参数:

hero - the data to POST in the body of the request.
`httpOptions` - the method options which, in this case, specify required headers.

当然它以与上述相同的方式捕获错误。

HeroesComponent通过订阅此服务方法返回的Observable来启动实际的POST操作。 app / heroes / heroes.component.ts(addHero)

this.heroesService.addHero(newHero)
  .subscribe(hero => this.heroes.push(hero));

当服务器成功响应新添加的英雄时,该组件会将该英雄添加到显示的英雄列表中。

编辑答案:

我看到你的邮递员截图你正在传递用户名

This link will help you