PayExtra.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace app\extra\weMini;
  3. use app\extra\tools\CodeExtend;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Exception\GuzzleException;
  6. use WeChat\Contracts\DataArray;
  7. use WeChat\Contracts\Tools;
  8. use WeChat\Exceptions\InvalidArgumentException;
  9. class PayExtra
  10. {
  11. /**
  12. * 商户配置
  13. */
  14. protected $config = [];
  15. public function setConfig(array $options)
  16. {
  17. $options['nonce_str'] = CodeExtend::createNoncestr();
  18. $this->config = $options;
  19. return $this;
  20. }
  21. public function createOrder(array $options): array
  22. {
  23. $options = array_merge($this->config,$options);
  24. $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
  25. $options['sign_type'] = "MD5";
  26. $options['sign'] = $this->getPaySign($options);
  27. $client = new Client();
  28. try {
  29. $resp = $client->post($url, [
  30. "header" => $client,
  31. 'body' => CodeExtend::arr2xml($options)
  32. ]);
  33. } catch (GuzzleException $e) {
  34. return [];
  35. }
  36. return CodeExtend::xml2arr($resp->getBody());
  37. }
  38. /**
  39. * 创建JsApi及H5支付参数
  40. * @param string $prepayId 统一下单预支付码
  41. * @return array
  42. */
  43. public function createParamsForJsApi($prepayId)
  44. {
  45. $option = [];
  46. $option["appId"] = $this->config['appid'];
  47. $option["timeStamp"] = (string)time();
  48. $option["nonceStr"] = CodeExtend::createNoncestr();
  49. $option["package"] = "prepay_id={$prepayId}";
  50. $option["signType"] = "MD5";
  51. $option["paySign"] = $this->getPaySign($option, 'MD5');
  52. $option['timestamp'] = $option['timeStamp'];
  53. return $option;
  54. }
  55. /**
  56. * 生成支付签名
  57. * @param array $data 参与签名的数据
  58. * @param string $signType 参与签名的类型
  59. * @param string $buff 参与签名字符串前缀
  60. * @return string
  61. */
  62. public function getPaySign(array $data, $signType = 'MD5', $buff = '')
  63. {
  64. ksort($data);
  65. if (isset($data['sign'])) unset($data['sign']);
  66. foreach ($data as $k => $v) {
  67. if ('' === $v || null === $v) continue;
  68. $buff .= "{$k}={$v}&";
  69. }
  70. $buff .= ("key=" . $this->config['mch_key']);
  71. if (strtoupper($signType) === 'MD5') {
  72. return strtoupper(md5($buff));
  73. }
  74. return strtoupper(hash_hmac('SHA256', $buff, $this->config['mch_key']));
  75. }
  76. }