Pinduoduo PHP SDK

repository·master·Indexed 42 days ago

https://github.com/justmd5/pinduoduo-sdk

A PHP SDK for interacting with the Pinduoduo Open Platform API. It supports various user roles including Merchants, Duoduo Jinbao promoters, and Logistics users, providing streamlined methods for public and OAuth-protected API calls. The SDK handles parameter signing, token management, and file uploads, requiring PHP >= 7.0.

Tokens
4K
Snippets
16
Records
16
Agent score
53%

What's inside Pinduoduo SDK

  1. Configure and initialize the PinDuoDuo client

    master

    To use the SDK, initialize the PinDuoDuo class with a configuration array. The configuration requires client_id, client_secret, and a member_type defining the user role.

    Available member_type values:

    • MERCHANT: Merchant authorization
    • H5: Mobile end
    • JINBAO: Duoduo Jinbao promoter (多多进宝推手)
    • KTT: Kuaituantuan leader (快团团团长)
    • LOGISTICS: Pinduoduo electronic shipping label user (拼多多电子面单用户)
    use \Justmd5\PinDuoDuo\PinDuoDuo;
    
    require __DIR__ . '/vendor/autoload.php';
    
    $config = [
        'client_id'    => 'xxxxxx69e3940c6b93xxxxxx',
        'client_secret' => 'c2eda0c398xxxxxxbd63ff57bf22c05xxxxxx',
        'debug'              => true,
        'member_type'        => 'JINBAO', // e.g., MERCHANT, H5, JINBAO, KTT, LOGISTICS
        'redirect_uri'       => 'https://test.xxx.com/callback',
        'log'                => [
            'name'       => 'pinduoduo',
            'file'       => __DIR__ . '/pinduoduo.log',
            'level'      => 'debug',
            'permission' => 0777,
        ],
    ];
    
    $pinduoduo = new PinDuoDuo($config);
  2. Handle OAuth authorization and token management

    master

    To access protected endpoints, follow these steps to authorize the user and obtain an access token:

    1. Get Authorization URL: Generate the URL to redirect the user to.
    2. Redirect User: Redirect the user to the generated URL.
    3. Retrieve Token: After redirection, retrieve the access token.
    4. Refresh Token (Optional): Use the refresh_token to obtain a new access token.
    5. Create Authorized Client: Use the token to create a client instance specifically for authorized API calls.
    // 1. Get the authorization URL
    $url = $pinduoduo->pre_auth->authorizationUrl();
    
    // 2. Redirect to the authorization page
    $pinduoduo->pre_auth->authorizationRedirect();
    
    // 3. Retrieve the token from the redirect callback
    $token = $pinduoduo->pre_auth->getAccessToken();
    
    // 4. Refresh the token if needed
    // $token = $pinduoduo->pre_auth->refreshToken($token['refresh_token']);
    
    // 5. Create an authorized client instance
    $pinduoduo = $pinduoduo->oauth->createAuthorization($token['token']);
  3. Call unauthenticated API endpoints

    master

    For API endpoints that do not require user authorization, use the api->request() method directly on the client instance.

    // Example: Query Duoduo Jinbao goods details (pdd.ddk.goods.detail)
    $result = $pinduoduo->api->request('pdd.ddk.goods.detail', ['goods_sign' => 'Y9X2o23Pb-lfwWc1wvfZk0N5-QNj-R7b_JlrlXGK3D']);
  4. Call authenticated API endpoints

    master

    Once you have an authorized client, you can call protected APIs. There are two ways to do this:

    Option 1: Using the auth_api property (Standard)

    $result = $pinduoduo->auth_api->request('pdd.ddk.oauth.goods.pid.query');

    Option 2: Using the fluent auth() method (Recommended)

    $result = $pinduoduo->api->auth()->request('pdd.ddk.goods.pid.query');
    // Recommended way to call authorized APIs
    $result = $pinduoduo->api->auth()->request('pdd.ddk.goods.pid.query');
  5. Initiate Pinduoduo OAuth authorization flow

    master

    To start the OAuth process, use the PreAuth class. You can either generate the authorization URL to build your own redirect logic or use authorizationRedirect to perform an immediate HTTP header redirect to the Pinduoduo authorization page.

    Supported member_type values (configured in the main PinDuoDuo instance) determine which authorization endpoint is used:

    • MERCHANT: Pinduoduo Shop (Web)
    • H5: Pinduoduo Shop (H5 Mobile)
    • JINBAO: Jinbao Promoter (Web)
    • KTT: KTT Captain (Web)
    • LOGISTICS: Pinduoduo Electronic Waybill User (Web)
    use Justmd5\PinDuoDuo\PinDuoDuo;
    use Justmd5\PinDuoDuo\Oauth\PreAuth;
    
    // Assuming $app is an initialized PinDuoDuo instance
    $preAuth = new PreAuth($app);
    
    // Option 1: Get the URL to use in your own redirect logic
    $url = $preAuth->authorizationUrl('your_custom_state', 'optional_view');
    
    // Option 2: Perform an immediate redirect
    $preAuth->authorizationRedirect('your_custom_state');
  6. Exchange authorization code for an access token

    master

    After a user authorizes your application, Pinduoduo will redirect them back to your redirect_uri with a code parameter. Use getAccessToken() to exchange this code for a usable access token.

    If you are calling this method within the callback controller that handles the redirect, you can omit the $code parameter, and the SDK will attempt to retrieve it from the current request.

    // In your callback controller
    $accessToken = $preAuth->getAccessToken($codeFromRequest, $stateFromRequest);
  7. Execute Pinduoduo API requests with request()

    master

    The request method is the primary way to interact with the Pinduoduo platform. It handles parameter signing, authentication tokens, and supports both standard JSON responses and file uploads.

    Parameters:

    • string $type: The API interface name.
    • array $params: Request parameters (excluding common parameters which are handled automatically).
    • string $data_type: The response format, either 'JSON' or 'XML' (defaults to 'JSON').
    • string $version: The API version (defaults to 'V1').

    Key Behaviors:

    • Authentication: If the Api instance was initialized with $needToken = true or if you call auth(true) before the request, the access_token and client_id are automatically injected into the parameters.
    • File Uploads: If the $params array contains a 'file' key, the SDK automatically switches the target URL to UPLOAD_URL and uses the upload HTTP method.
    • Data Handling: Boolean values in $params are converted to 'true'/'false' strings, and arrays are automatically json_encoded to ensure compatibility with the Pinduoduo API.
    // Example of a standard JSON request
    $response = $api->request('api_name', ['param1' => 'value1'], 'JSON');
    
    // Example of a file upload request
    $response = $api->request('upload_api_name', ['file' => '/path/to/file.jpg']);
  8. Register the Pinduoduo SDK via Pimple ServiceProvider

    master

    The SDK provides a ServiceProvider implementation for the Pimple dependency injection container. When registered, it sets up the core services required to interact with the Pinduoduo API.

    Key services registered to the container:

    • access_token: An AccessToken instance used for managing authentication. It requires client_id and client_secret to be configured in the container.
    • api: The standard Api instance for making authorized requests.
    • auth_api: An Api instance specifically configured for authentication-related requests (initialized with true for auth mode).
    use Justmd5\PinDuoDuo\ServiceProvider;
    use Pimple\Container;
    
    $container = new Container();
    // Ensure client_id and client_secret are configured in your container/config before registering
    $container['client_id'] = 'YOUR_CLIENT_ID';
    $container['client_secret'] = 'YOUR_CLIENT_SECRET';
    
    $container->register(new ServiceProvider());
    
    // Accessing services
    $api = $container['api'];
    $accessToken = $container['access_token'];
  9. Enable authentication with auth()

    master

    By default, an Api instance may not include an access token in its requests. Use the auth() method to enable automatic injection of the access_token and client_id into the request parameters. This is required for most authorized Pinduoduo platform interfaces.

    Returns $this to allow method chaining.

    $api->auth(true)->request('some_authorized_api', $params);
  10. Refresh an expired access token

    master

    When an access token expires, use the refreshToken() method to obtain a new one using a valid refresh token. This requires the refresh_token string provided by Pinduoduo during the initial token exchange.

    $newTokens = $preAuth->refreshToken($oldRefreshToken, $state);
  11. Authorize the SDK using createAuthorization()

    master

    To perform authorized API calls, you must associate an access token with the main PinDuoDuo instance. Use the Oauth class to create an authorization state. The createAuthorization method takes a $token string and an optional $expires integer (defaulting to 86399 seconds). This method configures the internal AccessToken using the client_id and client_secret from your existing PinDuoDuo configuration and returns the updated PinDuoDuo instance.

    // Assuming $app is an already instantiated Justmd5\PinDuoDuo\PinDuoDuo instance
    $oauth = new Justmd5\PinDuoDuo\Oauth\Oauth($app);
    
    // Authorize the app with a token
    $app = $oauth->createAuthorization('YOUR_ACCESS_TOKEN', 86399);
    
    // $app is now ready to make authorized requests