Kuaishou.php 7.3 KB

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