Wechat.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php namespace Pay\Lib;
  2. use Dever;
  3. Dever::apply('sdk/wechat', 'pay');
  4. class Wechat extends Core
  5. {
  6. public function __construct($config)
  7. {
  8. $project = Dever::project('pay');
  9. $this->config = new \WxPayConfig();
  10. # 通知接口
  11. $config['notify'] = $this->url($config['type'], $config['id']);
  12. # 证书
  13. $config['ssl'] = array
  14. (
  15. 'cert' => Dever::local($config['file_cert']),
  16. 'key' => Dever::local($config['file_key']),
  17. );
  18. $config['ip'] = (isset($config['ip']) && $config['ip']) ? $config['ip'] : Dever::ip();
  19. $this->config->set($config['appid'], $config['appsecret'], $config['mchid'], $config['notify'], $config['key'], $config['ssl'], $config['type'], $config['timeout'], $config['ip']);
  20. }
  21. /**
  22. * 通知
  23. */
  24. public function notify()
  25. {
  26. $this->log('支付回调-初始化', file_get_contents("php://input"));
  27. $callback = new Callback();
  28. $result = $callback->Handle($this->config, false);
  29. }
  30. # 查询订单
  31. public function search($order_id)
  32. {
  33. $info = Dever::db('pay/order')->one(array('order_id' => $order_id, 'status' => 2));
  34. if ($info) {
  35. $this->updateOrder($info['order_id'], 1);
  36. return $info;
  37. } else {
  38. $input = new \WxPayOrderQuery();
  39. $input->SetOut_trade_no($order_id);
  40. $result = \WxPayApi::orderQuery($this->config, $input);
  41. if (isset($result['transaction_id']) && isset($result['out_trade_no']) && isset($result['trade_state_desc'])) {
  42. $this->updateOrder($result['out_trade_no'], $result['cash_fee']);
  43. }
  44. return $result;
  45. }
  46. }
  47. # 退款
  48. public function refundByOrder($order_id)
  49. {
  50. $info = Dever::db('pay/order')->one(array('order_id' => $order_id));
  51. if ($info && ($info['status'] == 1 || $info['status'] == 2 || $info['status'] == 5)) {
  52. $this->refund($info['order_id'], $info['cash']);
  53. Dever::db('pay/order')->update(array('where_id' => $info['id'], 'status' => 5));
  54. return $result;
  55. }
  56. return false;
  57. }
  58. # 退款
  59. public function refund($order_id, $cash)
  60. {
  61. $out_trade_no = $order_id;
  62. $cash = $cash * 100;
  63. $total_fee = $cash;
  64. $refund_fee = $cash;
  65. $input = new \WxPayRefund();
  66. $input->SetOut_trade_no($out_trade_no);
  67. $input->SetTotal_fee($total_fee);
  68. $input->SetRefund_fee($refund_fee);
  69. $input->SetOut_refund_no($out_trade_no . '_' . time());
  70. $input->SetOp_user_id($this->config->GetMerchantId());
  71. $result = \WxPayApi::refund($this->config, $input);
  72. return $result;
  73. }
  74. /**
  75. * 获取统一下单的基本信息
  76. */
  77. public function order($account_id, $project_id, $uid, $username, $product_id, $name, $cash, $openid = false, $type = 1, $order_id = false)
  78. {
  79. $trade_type = $this->getType($type);
  80. $order_id = $this->createOrder($uid, $username, $account_id, $project_id, $product_id, $name, $cash, $this->config->GetType(), $order_id);
  81. $tools = new \JsApiPay($this->config);
  82. $input = new \WxPayUnifiedOrder();
  83. $input->SetBody($name);
  84. $input->SetAttach($name);
  85. $input->SetOut_trade_no($order_id);
  86. $input->SetTotal_fee($cash * 100);
  87. $input->SetTime_start(date("YmdHis"));
  88. $input->SetTime_expire(date("YmdHis", time() + $this->config->GetTimeOut()));
  89. //$input->SetGoods_tag($name);
  90. $input->SetNotify_url($this->config->GetNotifyUrl());
  91. $input->SetTrade_type($trade_type);
  92. $input->SetProduct_id($product_id);
  93. if ($type != 4 && $openid != -1) {
  94. $openid = $openid ? $openid : $tools->GetOpenid();
  95. $input->SetOpenid($openid);
  96. }
  97. if ($type == 2) {
  98. # 下单信息
  99. $this->updateOrderParam($order_id, $input);
  100. return $input;
  101. } else {
  102. $order = \WxPayApi::unifiedOrder($this->config, $input);
  103. # 下单信息
  104. $order['time'] = '' . time() . '';
  105. $order['order_id'] = $order_id;
  106. $order['sign_type'] = $this->config->GetSignType();
  107. unset($order['mch_id']);
  108. $this->updateOrderParam($order_id, $order);
  109. return $order;
  110. }
  111. }
  112. /**
  113. * 获取二维码支付
  114. */
  115. public function qrcode($order, $refer)
  116. {
  117. $notify = new \NativePay();
  118. $result = $notify->GetPayUrl($order);
  119. $url = $result['code_url'];
  120. return $url;
  121. }
  122. /**
  123. * 获取小程序支付
  124. */
  125. public function applet($order)
  126. {
  127. if (isset($order['prepay_id'])) {
  128. $string = 'appId='.$this->config->GetAppId().'&nonceStr='.$order['nonce_str'].'&package=prepay_id='.$order['prepay_id'].'&signType='.$order['sign_type'].'&timeStamp='.$order['time'].'&key='.$this->config->GetKey();
  129. $this->log('支付签名-applet', $string);
  130. if($order['sign_type'] == "MD5"){
  131. $string = md5($string);
  132. } else {
  133. $string = hash_hmac("sha256", $string, $this->config->GetKey());
  134. }
  135. $order['sign'] = $string;
  136. }
  137. return $order;
  138. }
  139. /**
  140. * 获取app支付
  141. */
  142. public function app($order)
  143. {
  144. if (isset($order['prepay_id'])) {
  145. $order['partnerid'] = $this->config->GetMerchantId();
  146. $order['package_string'] = 'Sign=WXPay';
  147. $string = array();
  148. $string['appid'] = $this->config->GetAppId();
  149. $string['partnerid'] = $order['partnerid'];
  150. $string['prepayid'] = $order['prepay_id'];
  151. $string['package'] = $order['package_string'];
  152. $string['noncestr'] = $order['nonce_str'];
  153. $string['timestamp'] = $order['time'];
  154. ksort($string);
  155. $string = str_replace('%3D', '=', http_build_query($string));
  156. $string .= '&key=' . $this->config->GetKey();
  157. $this->log('支付签名-app', $string);
  158. if($order['sign_type'] == "MD5"){
  159. $string = md5($string);
  160. } else {
  161. $string = hash_hmac("sha256", $string, $this->config->GetKey());
  162. }
  163. $order['sign'] = $string;
  164. }
  165. return $order;
  166. }
  167. /**
  168. * 获取页面支付
  169. */
  170. public function page($order, $refer)
  171. {
  172. if (isset($order['mweb_url'])) {
  173. $url = $order['mweb_url'] . '&redirect_url=' . $refer;
  174. if (!$url) {
  175. $location = 'window.open("' . $url . '")';
  176. } else {
  177. $location = 'location.href="' . $url . '"';
  178. }
  179. return '<script type="text/javascript">'.$location.'</script>';
  180. }
  181. $refer = urldecode($refer);
  182. if (strstr($refer, 'callback.')) {
  183. $callback = str_replace('callback.', '', $refer);
  184. $callback = $callback . '()';
  185. } else {
  186. $callback = 'location.href = "'.$refer.'";';
  187. }
  188. $tools = new \JsApiPay($this->config);
  189. $info = $tools->GetJsApiParameters($order);
  190. $html = '<script type="text/javascript">
  191. function jsApiCall()
  192. {
  193. WeixinJSBridge.invoke(
  194. "getBrandWCPayRequest",
  195. '.$info.',
  196. function(res){
  197. //WeixinJSBridge.log(res.err_msg);
  198. if(res.err_msg == "get_brand_wcpay_request:ok")
  199. {
  200. '.$callback.'
  201. } else {
  202. alert("支付失败");
  203. //alert(res.err_code+res.err_desc+res.err_msg);
  204. }
  205. }
  206. );
  207. }
  208. function callpay()
  209. {
  210. if (typeof WeixinJSBridge == "undefined"){
  211. if( document.addEventListener ){
  212. document.addEventListener("WeixinJSBridgeReady", jsApiCall, false);
  213. }else if (document.attachEvent){
  214. document.attachEvent("WeixinJSBridgeReady", jsApiCall);
  215. document.attachEvent("onWeixinJSBridgeReady", jsApiCall);
  216. }
  217. }else{
  218. jsApiCall();
  219. }
  220. }
  221. callpay();
  222. </script>';
  223. return $html;
  224. }
  225. private function getType($type)
  226. {
  227. switch ($type) {
  228. case 1:
  229. $type = 'JSAPI';
  230. break;
  231. case 2:
  232. $type = 'NATIVE';
  233. break;
  234. case 3:
  235. $type = 'APP';
  236. break;
  237. case 4:
  238. $type = 'MWEB';
  239. break;
  240. }
  241. return $type;
  242. }
  243. }
  244. class Callback extends \WxPayNotify
  245. {
  246. public function NotifyProcess($objData, $config, &$msg)
  247. {
  248. $data = $objData->GetValues();
  249. $obj = Dever::load('pay/lib/core');
  250. $obj->log('支付回调-获取数据', $data);
  251. $callback = function($msg = '') use ($obj, $data) {
  252. if ($msg) {
  253. $msg = $data['transaction_id'] . ':' . $msg;
  254. }
  255. $obj->updateOrder($data['out_trade_no'], $data['cash_fee'], $msg);
  256. };
  257. if(!array_key_exists("transaction_id", $data)){
  258. $msg = '输入参数不正确';
  259. $callback($msg);
  260. return false;
  261. }
  262. # 参数校验
  263. if(!array_key_exists("return_code", $data)
  264. ||(array_key_exists("return_code", $data) && $data['return_code'] != "SUCCESS")) {
  265. $msg = $data['return_code'] . '(异常)';
  266. $callback($msg);
  267. return false;
  268. }
  269. # 进行签名验证
  270. try {
  271. $checkResult = $objData->CheckSign($config);
  272. if($checkResult == false){
  273. $msg = '签名错误';
  274. $callback($msg);
  275. return false;
  276. }
  277. } catch(Exception $e) {
  278. $msg = '签名异常';
  279. $callback($msg);
  280. return false;
  281. }
  282. # 查询订单,判断订单真实性
  283. /*
  284. if(!$this->Queryorder($data["transaction_id"])){
  285. $msg = '订单查询失败';
  286. $callback($msg);
  287. return false;
  288. }
  289. */
  290. # 处理业务逻辑
  291. $callback();
  292. return true;
  293. }
  294. }