ByteDance.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 ByteDance.
  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 ByteDance extends BaseUniPlatform
  21. {
  22. public function __construct(BaseAPI $api)
  23. {
  24. $this->API = $api;
  25. }
  26. /**
  27. * 获取 access token.
  28. *
  29. * @throws \Exception
  30. */
  31. protected function getAccessToken(): string
  32. {
  33. $res = $this->post($this->API::ACCESS_TOKEN, [
  34. 'grant_type' => 'client_credential',
  35. 'appid' => $this->appId,
  36. 'secret' => $this->secret,
  37. ]);
  38. if (!empty($res['err_no'])) {
  39. throw new \Exception('获取access token 错误');
  40. }
  41. file_put_contents($this->accessTokenFile, json_encode([
  42. 'access_token' => $res['access_token'],
  43. 'expires_at' => $res['expiresAt'],
  44. ]));
  45. return $res['access_token'];
  46. }
  47. /**
  48. * @return array|mixed
  49. *
  50. * @throws \Exception
  51. */
  52. public function createOrder($outOrderNo, $totalAmount, $openId): array
  53. {
  54. $data = [
  55. 'app_id' => $this->appId,
  56. 'out_order_no' => $outOrderNo,
  57. 'total_amount' => intval($totalAmount * 100),
  58. 'subject' => '订单号:' . $outOrderNo,
  59. 'body' => '抖音担保支付',
  60. 'valid_time' => $this->validTimestamp,
  61. 'sign' => $this->secret,
  62. // 'notify_url' => $notifyUrl, // 可以不设置 使用小程序后台设置的回调
  63. ];
  64. $data = array_filter($data);
  65. $data['sign'] = $this->getSign($data);
  66. return $this->post(
  67. $this->API::CREATE_ORDER,
  68. $data
  69. );
  70. }
  71. /**
  72. * 结算.
  73. *
  74. * @return array|mixed|string[]
  75. *
  76. * @throws \Exception
  77. */
  78. public function settle($outOrderNo)
  79. {
  80. $data = [
  81. 'app_id' => $this->appId,
  82. 'out_settle_no' => $outOrderNo,
  83. 'out_order_no' => $outOrderNo,
  84. 'settle_desc' => '主动结算',
  85. ];
  86. $data = array_filter($data);
  87. $data['sign'] = $this->getSign($data);
  88. return $this->post(
  89. $this->API::SETTLE,
  90. $data
  91. );
  92. }
  93. /**
  94. * @return string
  95. */
  96. public function getSign(array $data)
  97. {
  98. $rList = [];
  99. foreach ($data as $k => $v) {
  100. if ('other_settle_params' == $k || 'app_id' == $k || 'sign' == $k || 'thirdparty_id' == $k) {
  101. continue;
  102. }
  103. $value = trim(strval($v));
  104. $len = strlen($value);
  105. if ($len > 1 && '"' == substr($value, 0, 1) && '"' == substr($value, $len, $len - 1)) {
  106. $value = substr($value, 1, $len - 1);
  107. }
  108. $value = trim($value);
  109. if ('' == $value || 'null' == $value) {
  110. continue;
  111. }
  112. array_push($rList, $value);
  113. }
  114. array_push($rList, $this->slat);
  115. sort($rList, SORT_STRING);
  116. return md5(implode('&', $rList));
  117. }
  118. /**
  119. * @return string
  120. */
  121. public function getNotifySign(array $data)
  122. {
  123. $filtered = [];
  124. foreach ($data as $key => $value) {
  125. if (in_array($key, ['msg_signature', 'type'])) {
  126. continue;
  127. }
  128. $value = trim(strval($value));
  129. $len = strlen($value);
  130. if ($len > 1 && '"' == substr($value, 0, 1) && '"' == substr($value, $len, $len - 1)) {
  131. $value = substr($value, 1, $len - 1);
  132. }
  133. $filtered[] = is_string($value)
  134. ? trim($value)
  135. : $value;
  136. }
  137. $filtered[] = trim($this->token);
  138. sort($filtered, SORT_STRING);
  139. return sha1(trim(implode('', $filtered)));
  140. }
  141. public function pushOrder($openid, $orderId, $goods, $status)
  142. {
  143. $data = [
  144. 'access_token' => $this->accessToken,
  145. 'open_id' => $openid,
  146. 'order_type' => 0, // 0:普通小程序订单(非 POI 订单),
  147. 'order_status' => 1,
  148. 'app_name' => 'douyin',
  149. 'update_time' => (int) Carbon::now()->getPreciseTimestamp(3),
  150. 'order_detail' => json_encode([
  151. 'order_id' => $orderId,
  152. 'create_time' => (int) Carbon::now()->getPreciseTimestamp(3),
  153. 'status' => $status, // 已支付 待支付
  154. 'amount' => 1,
  155. 'total_price' => $goods['price'] * 100,
  156. 'detail_url' => 'pages/my/consume',
  157. 'item_list' => [
  158. [
  159. 'item_code' => (string) $goods['id'], // 商品ID,
  160. 'img' => 'https://zhengda.oss-cn-chengdu.aliyuncs.com/zhangsiye/images/26474488be1b83e2fcb0b9475508a9bb.png',
  161. 'title' => $goods['title'],
  162. 'price' => $goods['price'] * 100,
  163. ],
  164. ],
  165. ], JSON_UNESCAPED_UNICODE),
  166. ];
  167. return $this->post($this->API::ORDER_PUSH, $data);
  168. }
  169. /**
  170. * @param string $code
  171. *
  172. * @return array|mixed
  173. *
  174. * @throws \Exception
  175. */
  176. public function login($code = ''): array
  177. {
  178. return $this->post($this->API::LOGIN, [
  179. 'appid' => $this->appId,
  180. 'secret' => $this->secret,
  181. 'code' => $code,
  182. ]);
  183. }
  184. /**
  185. * @return array|mixed
  186. *
  187. * @throws \Exception
  188. */
  189. public function generateQrcode()
  190. {
  191. $userId = \user()->id;
  192. return $this->post($this->API::CREATE_QRCODE, [
  193. 'appname' => 'douyin',
  194. 'access_token' => $this->accessToken,
  195. 'path' => urlencode('pages/index/index?' . "user_id=$userId"),
  196. 'width' => 600,
  197. ]);
  198. }
  199. /**
  200. * 接口请求
  201. *
  202. * @param string $uri
  203. * @param array $data
  204. *
  205. * @return array|mixed
  206. *
  207. * @throws \Exception
  208. */
  209. protected function post($uri = '', $data = []): array
  210. {
  211. try {
  212. $client = new Client();
  213. $res = $client->post($uri, [
  214. 'verify' => false,
  215. 'headers' => ['Content-Type' => 'application/json'],
  216. 'body' => json_encode($data),
  217. ]);
  218. $stringBody = (string) $res->getBody();
  219. $res = json_decode($stringBody, true);
  220. // 生成二维码接口是直接放回 buffer的
  221. if (empty($res) && $uri == $this->API::CREATE_QRCODE) {
  222. return [$stringBody];
  223. }
  224. if (isset($res['err_no']) && !empty($res['err_no'])) {
  225. throw new \Exception("请求字节跳动API接口错误,错误码:{$res['err_no']},错误信息:{$res['err_tips']}");
  226. }
  227. if (isset($res['err_code']) && !empty($res['err_code'])) {
  228. throw new \Exception("请求字节跳动API接口错误,错误码:{$res['err_msg']},错误信息:{$res['err_msg']}");
  229. }
  230. return $res['data'] ?? $res;
  231. } catch (GuzzleException $e) {
  232. \Log::error($e->getMessage());
  233. throw new \Exception($e->getMessage());
  234. }
  235. }
  236. protected function setAccessFileDir(): void
  237. {
  238. $this->accessTokenDir = storage_path('app/bytedance');
  239. }
  240. protected function setAccessFilePath(): void
  241. {
  242. $this->accessTokenFile = storage_path('app/bytedance/bytedance_access_token.json');
  243. }
  244. protected function setNoticeUrl(): void
  245. {
  246. $this->noticeUrl = env('APP_URL') . '/api/pay/bytedance/notify';
  247. }
  248. }