Wechat.php 9.0 KB

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