Kuaishou.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. <?php
  2. namespace App\Helper;
  3. use App\Helper\UniPlatform\BaseAPI;
  4. use App\Helper\UniPlatform\BaseUniPlatform;
  5. use Carbon\Carbon;
  6. use GuzzleHttp\Client;
  7. use GuzzleHttp\Exception\GuzzleException;
  8. /**
  9. * Class Kuaishou.
  10. *
  11. * @property string $appId
  12. * @property string $slat
  13. * @property string $secret
  14. * @property string $token
  15. * @property string $accessTokenFile
  16. * @property string $accessToken
  17. * @property string $noticeUrl
  18. * @property string $validTimestamp
  19. */
  20. class Kuaishou extends BaseUniPlatform
  21. {
  22. public function __construct(BaseAPI $api)
  23. {
  24. $this->API = $api;
  25. }
  26. /**
  27. * @param string $code
  28. *
  29. * @return array|mixed
  30. *
  31. * @throws \Exception
  32. */
  33. public function login($code = ''): array
  34. {
  35. return $this->post($this->API::LOGIN, [
  36. 'app_id' => $this->appId,
  37. 'app_secret' => $this->secret,
  38. 'js_code' => $code,
  39. ]);
  40. }
  41. public function createOrder($outOrderNo, $totalAmount, $openId): array
  42. {
  43. $data = [
  44. 'app_id' => $this->appId,
  45. 'out_order_no' => $outOrderNo,
  46. 'open_id' => $openId,
  47. 'total_amount' => intval($totalAmount * 100),
  48. 'subject' => '订单号:' . $outOrderNo,
  49. 'detail' => '快手担保支付',
  50. 'type' => 1233, // @url https://mp.kuaishou.com/docs/operate/platformAgreement/epayServiceCharge.html
  51. 'expire_time' => $this->validTimestamp,
  52. 'notify_url' => $this->noticeUrl,
  53. ];
  54. $data['sign'] = $this->getSign($data);
  55. $url = $this->API::CREATE_ORDER . '?' . http_build_query([
  56. 'app_id' => $this->appId,
  57. 'access_token' => $this->accessToken,
  58. ]);
  59. $res = $this->post(
  60. $url,
  61. $data,
  62. 'json'
  63. );
  64. return [
  65. 'order_id' => $res['order_info']['order_no'],
  66. 'order_token' => $res['order_info']['order_info_token'],
  67. ];
  68. }
  69. public function settle($orderNo, $amount)
  70. {
  71. $url = $this->API::SETTLE . '?' . http_build_query([
  72. 'app_id' => $this->appId,
  73. 'access_token' => $this->accessToken,
  74. ]);
  75. $data = [
  76. 'app_id' => $this->appId,
  77. 'out_order_no' => $orderNo,
  78. 'out_settle_no' => $orderNo,
  79. 'reason' => '主动结算',
  80. 'notify_url' => env('APP_URL') . '/api/pay/kuaishou/settle',
  81. 'settle_amount' => $amount,
  82. ];
  83. $data['sign'] = $this->getSign($data);
  84. return $this->post(
  85. $url,
  86. $data,
  87. 'json'
  88. );
  89. }
  90. public function pushOrder($openid, $orderId, $createAt): array
  91. {
  92. $data = [
  93. 'app_id' => $this->appId,
  94. 'out_order_no' => $orderId,
  95. 'out_biz_order_no' => $orderId,
  96. 'open_id' => $openid,
  97. 'order_create_time' => (int) Carbon::parse($createAt)->getPreciseTimestamp(3),
  98. 'order_status' => 11, // 支付成功 虚拟
  99. 'order_path' => 'pages/my/consume',
  100. 'product_cover_img_id' => '5acfa29b90c8234ff41ede600cad6a9b715f38871eaf5973',
  101. ];
  102. $url = $this->API::ORDER_PUSH . '?' . http_build_query([
  103. 'app_id' => $this->appId,
  104. 'access_token' => $this->accessToken,
  105. ]);
  106. return $this->post($url, $data, 'json');
  107. }
  108. public function upload()
  109. {
  110. $url = 'https://open.kuaishou.com/openapi/mp/developer/file/img/uploadWithUrl?' . http_build_query([
  111. 'app_id' => $this->appId,
  112. 'access_token' => $this->accessToken,
  113. 'url' => 'http://fourtiao.oss-cn-beijing.aliyuncs.com/zhangsiye/images/664b34c5afb8cb56d4a3cec398e64948.png',
  114. ]);
  115. return $this->post(
  116. $url,
  117. );
  118. }
  119. /**
  120. * @return string
  121. */
  122. public function getSign(array $data)
  123. {
  124. $filterArray = ['sign', 'access_token'];
  125. $rList = [];
  126. foreach ($data as $k => $v) {
  127. if (in_array($k, $filterArray)) {
  128. continue;
  129. }
  130. $value = trim(strval($v));
  131. $len = strlen($value);
  132. if ($len > 1 && '"' == substr($value, 0, 1) && '"' == substr($value, $len, $len - 1)) {
  133. $value = substr($value, 1, $len - 1);
  134. }
  135. $value = trim($value);
  136. if ('' == $value || 'null' == $value) {
  137. continue;
  138. }
  139. array_push($rList, "$k=$value");
  140. }
  141. sort($rList, SORT_STRING);
  142. $str = implode('&', $rList);
  143. $str .= $this->secret;
  144. return md5($str);
  145. }
  146. protected function getAccessToken(): string
  147. {
  148. $res = $this->post($this->API::ACCESS_TOKEN, [
  149. 'app_id' => $this->appId,
  150. 'app_secret' => $this->secret,
  151. 'grant_type' => 'client_credentials',
  152. ]);
  153. if (!isset($res['result']) || 1 != $res['result']) {
  154. throw new \Exception('获取access token 错误');
  155. }
  156. file_put_contents($this->accessTokenFile, json_encode([
  157. 'access_token' => $res['access_token'],
  158. 'expires_at' => Carbon::now()->timestamp + $res['expires_in'],
  159. ]));
  160. return $res['access_token'];
  161. }
  162. protected function setAccessFileDir(): void
  163. {
  164. $this->accessTokenDir = storage_path('app/kuaishou');
  165. }
  166. protected function setAccessFilePath(): void
  167. {
  168. $this->accessTokenFile = storage_path('app/kuaishou/kuaishou_access_token.json');
  169. }
  170. public function getNotifySign(array $data)
  171. {
  172. $req = file_get_contents('php://input');
  173. $str = $req . $this->secret;
  174. return md5($str);
  175. }
  176. /**
  177. * @param string $uri
  178. * @param array $data
  179. * @param string $type
  180. *
  181. * @throws \Exception
  182. */
  183. protected function post($uri = '', $data = [], $type = 'urlencoded'): array
  184. {
  185. try {
  186. $client = new Client();
  187. if ('urlencoded' == $type) {
  188. $url = $uri . '?' . http_build_query($data);
  189. $options = [
  190. 'verify' => false,
  191. 'headers' => ['Content-Type' => 'x-www-form-urlencoded'],
  192. ];
  193. } else {
  194. $url = $uri;
  195. $options = [
  196. 'verify' => false,
  197. 'headers' => ['Content-Type' => 'application/json'],
  198. 'body' => json_encode($data),
  199. ];
  200. }
  201. $res = $client->post($url, $options);
  202. $stringBody = (string) $res->getBody();
  203. $res = json_decode($stringBody, true);
  204. if (!isset($res['result']) || 1 != $res['result']) {
  205. throw new \Exception("请求快手API接口错误,错误码:{$res['result']},错误信息:{$res['error_msg']}");
  206. }
  207. return $res;
  208. } catch (GuzzleException $e) {
  209. \Log::error($e->getMessage());
  210. throw new \Exception($e->getMessage());
  211. }
  212. }
  213. protected function setNoticeUrl(): void
  214. {
  215. $this->noticeUrl = env('APP_URL') . '/api/pay/kuaishou/notify';
  216. }
  217. }