PHP code example of wwtg99 / jsonrpc

1. Go to this page and download the library: Download wwtg99/jsonrpc library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wwtg99 / jsonrpc example snippets


Wwtg99\JsonRpc\Provider\JsonRpcServiceProvider::class

'JsonRpc' => Wwtg99\JsonRpc\Facades\JsonRpc::class

JsonRpc::bind('method1', function($request) {
    $method = $request->getMethod();
    $params = $request->getParams();
    $p = $request->parseParam('name');  //get param name
    $id = $request->getId();
    
    //some process...
    
    //return result array, request id will be added automatically
    return [1, 2, 3];
    //Or use JsonRpcResponse
    return new JsonRpcResponse($id, [1, 2, 3]);
    //return error
    return new JsonRpcResponse($id, null, ['code'=>1, 'message'=>'error']);
});

// Or use handler instance
$ph = resolve('ProcessHandler');
$ph->bind('method1', function($request) {
    return [1, 2, 3];
});

namespace Test;
class BindingTest {
    public function test1($request) 
    {
        return [1, 2, 3];
    }
}
JsonRpc::bind('method2', 'Test\BindingTest@test1');
// Or $ph->bind('method2', 'Test\BindingTest@test1');

//you should disable VerifyCsrfToken middleware if use post method
Route::match(['GET', 'POST'], '/json_rpc', function() {
    $res = JsonRpc::parse(request());
    //other process
    return response()->json($res);
});

Route::match(['GET', 'POST'], '/json_rpc', function (\Illuminate\Http\Request $request) {
    return Wwtg99\JsonRpc\Provider\JsonRpcRouter::parse($request);
});

//get client
$cli = new JsonRpcClient($url);  //default method is post, return type json
//use get method
//$cli = new JsonRpcClient($url, ['http_method'=>'get']);
//use raw string return instead of json
//$cli = new JsonRpcClient($url, ['return_type'=>'string']);

//build requests
$req1 = new JsonRpcRequest('method1', 1, [1, 2, 3]);
$req1 = new JsonRpcRequest('method1', 2, [1, 2, 3]);

//send one request
$res = $cli->send($req1);
//send batch requests
$res = $cli->appendRequest($req1)->appendRequest($req2)->send();
//send notify
$cli->notify('method2', ['a'=>'b'])