Core.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace Cmbc\Api;
  3. use Cmbc\Setting;
  4. abstract class Core
  5. {
  6. protected $param = array();
  7. protected $data = array();
  8. protected $setting = null;
  9. protected $error = array();
  10. protected $method = 'post';
  11. abstract protected function init();
  12. abstract public function request($request, $tool = false);
  13. abstract public function response($response);
  14. public function __construct(Setting $setting)
  15. {
  16. $this->setting = $setting;
  17. $this->init();
  18. $this->param['appId'] = $this->setting->getAppId();
  19. $this->param['mhtSubMchId'] = $this->setting->getSubMchId();
  20. }
  21. protected function setParam($key, $default = false, $isMust = true)
  22. {
  23. if (!$this->data) {
  24. $this->setError('param data is not exists');
  25. } else {
  26. if (!isset($this->data[$key]) && $default) {
  27. $this->data[$key] = $default;
  28. }
  29. if (isset($this->data[$key])) {
  30. if (!$this->data[$key] || $this->data[$key] == 0) {
  31. if ($default) {
  32. $this->data[$key] = $default;
  33. }
  34. }
  35. if ($isMust == true && !$this->data[$key] && $this->data[$key] != 0) {
  36. $this->setError('param data ['.$key.'] is not value');
  37. }
  38. $this->param[$key] = $this->data[$key];
  39. }
  40. }
  41. return $this;
  42. }
  43. protected function createSignature($type = 'MD5')
  44. {
  45. ksort($this->param);
  46. $signature_string = '';
  47. foreach ($this->param as $k => $v) {
  48. if ($v || $v == 0) {
  49. $signature_string .= $k . '=' . $v . '&';
  50. }
  51. }
  52. $signature_string = substr($signature_string, 0, -1);
  53. $method = strtoupper($type);
  54. $secret = $method($this->setting->getAppSecret());
  55. return $method($signature_string . '&' . $secret);
  56. }
  57. protected function curl()
  58. {
  59. $curl = curl_init();
  60. curl_setopt($curl, CURLOPT_URL, $this->api);
  61. curl_setopt($curl, CURLOPT_HEADER, false);
  62. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  63. if ($this->method == 'post' && $this->param) {
  64. curl_setopt($curl, CURLOPT_POST, 1);
  65. curl_setopt($curl, CURLOPT_POSTFIELDS, $this->param);
  66. }
  67. $data = curl_exec($curl);
  68. curl_close($curl);
  69. parse_str($data, $result);
  70. if (isset($result['responseCode']) && $result['responseCode'] == 'A002') {
  71. # 失败
  72. }
  73. print_r($result);die;
  74. return false;
  75. }
  76. protected function setError($msg)
  77. {
  78. $this->error[] = $msg;
  79. }
  80. protected function getError()
  81. {
  82. $number = count($this->error);
  83. if ($number > 0) {
  84. $msg = $this->error[0];
  85. return $msg;
  86. }
  87. return false;
  88. }
  89. }