ByteDance.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. * @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 ByteDance extends BaseUniPlatform
  22. {
  23. public function __construct(BaseAPI $api)
  24. {
  25. $this->API = $api;
  26. }
  27. /**
  28. * 获取 access token
  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. * @param $outOrderNo
  49. * @param $totalAmount
  50. * @param $openId
  51. * @return array|mixed
  52. * @throws \Exception
  53. */
  54. public function createOrder($outOrderNo, $totalAmount, $openId): array
  55. {
  56. $data = [
  57. 'app_id' => $this->appId,
  58. 'out_order_no' => $outOrderNo,
  59. 'total_amount' => intval($totalAmount * 100),
  60. 'subject' => "订单号:".$outOrderNo,
  61. 'body' => '抖音担保支付',
  62. 'valid_time' => $this->validTimestamp,
  63. 'sign' => $this->secret
  64. //'notify_url' => $notifyUrl, // 可以不设置 使用小程序后台设置的回调
  65. ];
  66. $data = array_filter($data);
  67. $data['sign'] = $this->getSign($data);
  68. return $this->post(
  69. $this->API::CREATE_ORDER,
  70. $data
  71. );
  72. }
  73. /**
  74. * 结算
  75. * @param $outOrderNo
  76. * @return array|mixed|string[]
  77. * @throws \Exception
  78. */
  79. public function settle($outOrderNo)
  80. {
  81. $data = [
  82. 'app_id' => $this->appId,
  83. 'out_settle_no' => $outOrderNo,
  84. 'out_order_no' => $outOrderNo,
  85. 'settle_desc' => '主动结算',
  86. ];
  87. $data = array_filter($data);
  88. $data['sign'] = $this->getSign($data);
  89. return $this->post(
  90. $this->API::SETTLE,
  91. $data
  92. );
  93. }
  94. /**
  95. * @param array $data
  96. * @return string
  97. */
  98. public function getSign(array $data)
  99. {
  100. $rList = [];
  101. foreach ($data as $k => $v) {
  102. if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id")
  103. continue;
  104. $value = trim(strval($v));
  105. $len = strlen($value);
  106. if ($len > 1 && substr($value, 0, 1) == "\"" && substr($value, $len, $len - 1) == "\"")
  107. $value = substr($value, 1, $len - 1);
  108. $value = trim($value);
  109. if ($value == "" || $value == "null")
  110. continue;
  111. array_push($rList, $value);
  112. }
  113. array_push($rList, $this->slat);
  114. sort($rList, SORT_STRING);
  115. return md5(implode('&', $rList));
  116. }
  117. /**
  118. * @param array $data
  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. $filtered[] =
  133. 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. * @return array|mixed
  172. * @throws \Exception
  173. */
  174. public function login($code = ''): array
  175. {
  176. return $this->post($this->API::LOGIN, [
  177. 'appid' => $this->appId,
  178. 'secret' => $this->secret,
  179. 'code' => $code,
  180. ]);
  181. }
  182. /**
  183. * @return array|mixed
  184. * @throws \Exception
  185. */
  186. public function generateQrcode()
  187. {
  188. $userId = \user()->id;
  189. return $this->post($this->API::CREATE_QRCODE, [
  190. 'appname' => 'douyin',
  191. 'access_token' => $this->accessToken,
  192. 'path' =>urlencode('pages/index/index?'."user_id=$userId"),
  193. 'width' => 600,
  194. ]);
  195. }
  196. /**
  197. * 接口请求
  198. *
  199. * @param string $uri
  200. * @param array $data
  201. * @return array|mixed
  202. * @throws \Exception
  203. */
  204. protected function post($uri = '', $data = []) : array
  205. {
  206. try {
  207. $client = new Client();
  208. $res = $client->post($uri, [
  209. 'verify' => false,
  210. 'headers' => ['Content-Type' => 'application/json'],
  211. 'body' => json_encode($data)
  212. ]);
  213. $stringBody = (string)$res->getBody();
  214. $res = json_decode($stringBody, true);
  215. // 生成二维码接口是直接放回 buffer的
  216. if(empty($res) && $uri == $this->API::CREATE_QRCODE){
  217. return [$stringBody];
  218. }
  219. if(isset($res['err_no']) && !empty($res['err_no'])){
  220. throw new \Exception("请求字节跳动API接口错误,错误码:{$res['err_no']},错误信息:{$res['err_tips']}");
  221. }
  222. if(isset($res['err_code']) && !empty($res['err_code'])){
  223. throw new \Exception("请求字节跳动API接口错误,错误码:{$res['err_msg']},错误信息:{$res['err_msg']}");
  224. }
  225. return $res['data']?? $res;
  226. } catch (GuzzleException $e) {
  227. \Log::error($e->getMessage());
  228. throw new \Exception($e->getMessage());
  229. }
  230. }
  231. protected function setAccessFileDir(): void
  232. {
  233. $this->accessTokenDir = storage_path('app/bytedance');
  234. }
  235. protected function setAccessFilePath(): void
  236. {
  237. $this->accessTokenFile = storage_path('app/bytedance/bytedance_access_token.json');
  238. }
  239. protected function setNoticeUrl(): void
  240. {
  241. $this->noticeUrl = env('APP_URL').'/api/pay/bytedance/notify';
  242. }
  243. }