Giter Club home page Giter Club logo

youzan-sdk's Introduction

Youzan SDK

有赞 SDK (支持有赞所有版本)

base on foundation-sdk

Requirement

Installation

// 有赞云最新版支持
composer require hanson/youzan-sdk -vvv

Usage

自用型应用

<?php

$youzan = new \Hanson\Youzan\Youzan([
    'client_id' => '',
    'client_secret' => '',
    'debug' => true, // 调试模式
    'kdt_id' => '', // 店铺ID(仅自用模式下填写)
    'exception_as_array' => true, // 错误返回数组还是异常
    'version' => '4.0.0',
    'log' => [
        'name' => 'youzan',
        'file' => __DIR__.'/youzan.log',
        'level'      => 'debug',
        'permission' => 0777,
    ]
]);

// 获取订单
$result = $youzan->request('youzan.trade.get', ['tid' => 'xxx']);

// 获取门店信息(你可以设置调用api的版本)
$result = $youzan->setVersion('3.0.0')->request('youzan.shop.get');

工具型应用

<?php

$youzan = new \Hanson\Youzan\Youzan([
    'client_id' => '',
    'client_secret' => '',
    'dev_client_id' => '工具型有容器的开发环境 client id', // 仅在 is_dev=true 时有用
    'dev_client_secret' => '工具型有容器的开发环境 client secret', // 仅在 is_dev=true 时有用
    'is_dev' => true, // 默认 false
    'debug' => true,
    'redirect_uri' => 'http://xxx.com',
    'exception_as_array' => true,
    'version' => '4.0.0',
    'log' => [
        'name' => 'youzan',
        'file' => __DIR__.'/youzan.log',
        'level'      => 'debug',
        'permission' => 0777,
    ]
]);

// 解密消息
$youzan->decrypt->decrypt($message);

/**
* 切换开发模式
 *
 * 新版有赞云工具型有容器应用中,同一应用测试环境与正式环境的 client_id 和 client_secret都不一样,故此添加了 dev_client_id,dev_client_secret 和此方法,用于切换不同环境下的开发,默认为false,正式开发可以不调用此方法
 */
$youzan->setDev(true);

// 使用配置中的 prod_client_secret 进行解密
$youzan->decrypt->decryptWithProd($message);

// 获取授权 URL
$url = $youzan->pre_auth->authorizationUrl();

// 重定向到授权页面
$youzan->pre_auth->authorizationRedirect();

// 在重定向页面,你可以获取此次授权账号的 token
$token = $youzan->pre_auth->getAccessToken();

// 也可以通过上面得到的 refresh_token 去刷新令牌
$token = $youzan->pre_auth->refreshToken($token['refresh_token']);

// 创建授权应用
$youzan = $youzan->oauth->createAuthorization($token['token']);

// 店铺信息
$result = $youzan->request('youzan.shop.get');

// 上传图片(4.0以上版本)
$result = $youzan->request('youzan.materials.storage.platform.img.upload', [], ['image' => [file_get_contents('https://i.loli.net/2018/12/17/5c17334487566.jpg')]]);

消息推送

<?php
// 消息结构体
$data = $youzan->push->parse();

// 开发者自行选择性处理,把 "null" 与 "" 转为 null,建议使用
// $data = Helper::toNull($data);

$response = $youzan->push->response();

// $response 为 `Symfony\Component\HttpFoundation\Response` 实例
// 对于需要直接输出响应的框架,或者原生 PHP 环境下
$response->send();

// 而 Laravel 中直接返回即可:
return $response;

升级指南

4.* -> 5.*

* 4.* 的时候会对 api response 做处理,只返回 $response['response'] 部分
* 5.* 以后默认原样返回 youzan api 的 response,不再二次处理,请注意更新业务代码

3.* -> 4.*

* 构造函数设置了 `$config['exception_as_array'] = true;` 错误会返回包含 `error_response` 键名的数组(以前没有)
* 上传图片为 `$youzan->request('youzan.materials.storage.platform.img.upload', [], ['image' => [$bytes]]);`

Help

QQ 群: 570769430

License

MIT

youzan-sdk's People

Contributors

bolechen avatar chao avatar hanson avatar qbhy avatar ruitaozhang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

youzan-sdk's Issues

最新一次 composer update 后生产环境代码报错

怀疑是否跟最近一次的 hanson/foundation-sdk 升级有关


   TypeError

  Argument 1 passed to Hanson\Foundation\Http::__construct() must be an instance of Hanson\Foundation\Foundation, null given, called in /Volumes/Dev/youzan-social-app/vendor/hanson/foundation-sdk/src/AbstractAPI.php on line 32

  at vendor/hanson/foundation-sdk/src/Http.php:55
    51|     /**
    52|      * Http constructor.
    53|      * @param  Foundation  $app
    54|      */
  > 55|     public function __construct(Foundation $app)
    56|     {
    57|         $this->app = $app;
    58|     }
    59|

      +3 vendor frames
  4   app/Jobs/Youzan/YouzanScrmSyncJob.php:87
      Hanson\Youzan\Youzan::request("youzan.scrm.customer.card.delete")

      +22 vendor frames
  27  app/User.php:401
      Illuminate\Foundation\Bus\PendingDispatch::__destruct()

php 8.1 怎么才能支持呢?

依赖有点多,不知道怎么解决呢

 /Volumes/Dev/laravel9/ [master*] composer require hanson/youzan-sdk:dev-master -vv

./composer.json has been updated
Running composer update hanson/youzan-sdk
Loading composer repositories with package information
Updating dependencies
Dependency resolution completed in 0.001 seconds
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires hanson/youzan-sdk dev-master -> satisfiable by hanson/youzan-sdk[dev-master].
    - hanson/youzan-sdk dev-master requires hanson/foundation-sdk ^3.0 | ^4.0 | ^5.0 -> found hanson/foundation-sdk[3.0.0, 3.0.1, 3.0.2, 3.0.3, 3.0.4, 3.0.5, 3.1, 4.0, 4.0.1, 4.0.2, 4.0.3, 5.0.0, 5.0.1] but it conflicts with your root composer.json require (dev-master).

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

composer 安装失败

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for symfony/http-foundation (locked at v4.0.8) -> satisfiable by symfony/http-foundation[v4.0.8].
- hanson/youzan-sdk 2.0.0 requires hanson/foundation-sdk ^1.0 -> satisfiable by hanson/foundation-sdk[1.0.0].
- hanson/youzan-sdk 2.0.1 requires hanson/foundation-sdk ^1.0 -> satisfiable by hanson/foundation-sdk[1.0.0].
- hanson/youzan-sdk 2.0.2 requires hanson/foundation-sdk ^1.0 -> satisfiable by hanson/foundation-sdk[1.0.0].
- hanson/youzan-sdk 2.0.3 requires hanson/foundation-sdk ^1.0 -> satisfiable by hanson/foundation-sdk[1.0.0].
- Conclusion: don't install hanson/foundation-sdk 1.0.0
- Installation request for hanson/youzan-sdk ^2.0 -> satisfiable by hanson/youzan-sdk[2.0.0, 2.0.1, 2.0.2, 2.0.3].

批量创建商品时经常会出现异常

PHP Fatal error: Uncaught GuzzleHttp\Exception\ConnectException: cURL error 52: Empty reply from server (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:185
Stack trace:
#0 /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(149): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array)
#1 /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(102): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#2 /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#3 /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php(28): GuzzleHttp\Handler\CurlHandler->__invoke(Object(GuzzleHttp\Psr7\Requ in /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 185

Fatal error: Uncaught GuzzleHttp\Exception\ConnectException: cURL error 52: Empty reply from server (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:185
Stack trace:
#0 /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(149): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array)
#1 /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(102): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#2 /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory))
#3 /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/Proxy.php(28): GuzzleHttp\Handler\CurlHandler->__invoke(Object(GuzzleHttp\Psr7\Requ in /data/youzan_api/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 185

Api类接口出错时返回的数据已经变了,请更新

/**
     * 请求API
     *
     * @param $method
     * @param array $params
     * @param string $version
     * @param array $files
     * @return array
     * @throws YouzanException
     */
    public function request($method, $params = [], $version = '3.0.0', $files = [])
    {
        $url = $this->url($method, $version);

        $http = $this->getHttp();

        $params['access_token'] = $this->accessToken->getToken();

        $response = $files ? $http->upload($url, $params, $files) : $http->post($url, $params);

        $result = json_decode(strval($response->getBody()), true);

        if (isset($result['error_response'])) {
            throw new YouzanException($result['error_response']['msg'], $result['error_response']['code']);
        }

        return $result['response'];
    }

有赞返回的error_response中已经没有msg,现在是message

异常示例
{
  "error_response": {
    "code": 103011024,
    "message": "退款记录不存在"
  }
}

有赞服务器异常返回。

在使用获得客户信息的接口的时候,如果客户不存在有赞居然不返回任何信息,只返回一个空数组。

例如:

$youzan->request('youzan.scrm.customer.get', [ 'account' => '{"account_type":"Mobile", "account_id":"18xxxxxx"}'], [], '3.1.0');

经过调试服务器仅返回:[]

所以程序会出现以下提示:

PHP Notice:  Undefined index: response in /var/www/html/vendor/hanson/youzan-sdk/src/Api.php on line 51

建议,改进下Api.php对这种异常进行下捕捉。

调用报错

HttpException in AbstractAPI.php line 105:
无效的时间参数
in AbstractAPI.php line 105
at AbstractAPI->checkAndThrow(array('error_response' => array('code' => 40003, 'msg' => '无效的时间参数'))) in AbstractAPI.php line 77
at AbstractAPI->parseJSON('upload', 'kdt.item.add', array('https://open.youzan.com/api/entry/kdt.item/1.0.0/add', array('title' => '产品名称', 'price' => '899.99', 'post_fee' => '0', 'app_id' => '2c61af3095a3518214', 'method' => 'kdt.item.add', 'timestamp' => '2017-03-05 13:03:40', 'v' => '1.0', 'sign' => '08292161416d28a4415f0be84f31bbf6'), array('images' => array('/home/vagrant/Code/demo/app/Http/Controllers', '/home/vagrant/Code/demo/app/Http/Controllers')))) in Product.php line 90
at Product->add(array('title' => '产品名称', 'price' => '899.99', 'post_fee' => '0'), array('images' => array('/home/vagrant/Code/demo/app/Http/Controllers', '/home/vagrant/Code/demo/app/Http/Controllers'))) in YouZanController.php line 32
at YouZanController->test()

Laravel 中 push 消息直接返回会报错

按文档说明 Laravel 中在控制器中可以直接返回

return $youzan->push->response();

实际情况报错如下

production.ERROR: Return value of App\Http\Controllers\YouzanYunController::push() must be an instance of Illuminate\Http\JsonResponse, instance of Symfony\Component\HttpFoundation\Response returned {"exception":"[object] (TypeError(code: 0): Return value of App\\Http\\Controllers\\YouzanYunController::push() must be an instance of Illuminate\\Http\\JsonResponse, instance of Symfony\\Component\\HttpFoundation\\Response returned

参数 Token 无效

这个报错很奇怪,我甚至怀疑是有赞更新了接口。
报错的地址:src/Youzan.php:57@request() 方法,再往后就是 src/Api.php:50 抛出错误了。只有一个参数 Token 无效的报错。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.