首页 > 解决方案 > 如何在套件 crm 中使用 REST API 发布数据

问题描述

这是我的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);
  }

}

这是邮递员的回复 在此处输入图像描述

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

标签: phprestapisuitecrm

解决方案


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

文档阅读它

发出 POST 请求

应用程序经常将数据 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));

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

编辑答案:

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

这个链接可以帮助你


推荐阅读