当前位置:首页 > PHP教程 > php高级应用 > 列表

php实现微信支付之企业付款

发布:smiling 来源: PHP粉丝网  添加日期:2021-09-21 19:33:13 浏览: 评论:0 

网上的很多PHP微信支付接入教程都颇为复杂,且需要配置和引入较多的文件,本人通过整理后给出一个单文件版的,希望可以给各位想接入微信支付的带来些许帮助和借鉴意义。

直接运行该文件即可给指定的微信用户转账。

需要注意的事项:

1.微信企业付款到零钱要求必传证书,需要到这里账户中心->账户设置->API安全->下载证书,然后修改代码中的证书路径

2.该文件需放到支付授权目录下,可以在微信支付商户平台->产品中心->开发配置中设置。

3.如提示签名错误可以通过微信支付签名验证工具进行验证:微信公众平台支付接口调试工具

4.错误码参照:参照地址

代码如下:

  1. <?php 
  2. /** 
  3.  * 关于微信企业付款的说明 
  4.  * 1.微信企业付款要求必传证书,需要到https://pay.weixin.qq.com 账户中心->账户设置->API安全->下载证书,证书路径在第207行和210行修改 
  5.  * 2.错误码参照 :https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2 
  6.  */ 
  7. header('Content-type:text/html; Charset=utf-8'); 
  8. $mchid = 'xxxxx';  //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送 
  9. $appid = 'xxxxx'; //微信支付申请对应的公众号的APPID 
  10. $appKey = 'xxxxx'; //微信支付申请对应的公众号的APP Key 
  11. $apiKey = 'xxxxx'; //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥 
  12.  
  13. //①、获取当前访问页面的用户openid(如果给指定用户转账,则直接填写指定用户的openid) 
  14. $wxPay = new WxpayService($mchid,$appid,$appKey,$apiKey); 
  15. $openId = $wxPay->GetOpenid(); //获取openid 
  16. if(!$openId) exit('获取openid失败'); 
  17. //②、付款 
  18. $outTradeNo = uniqid(); //订单号 
  19. $payAmount = 1;  //转账金额,单位:元。转账最小金额为1元 
  20. $trueName = '张三';  //收款人真实姓名 
  21. $result = $wxPay->createJsBizPackage($openId,$payAmount,$outTradeNo,$trueName); 
  22. echo 'success'; 
  23. class WxpayService 
  24. { 
  25.  protected $mchid; 
  26.  protected $appid; 
  27.  protected $appKey; 
  28.  protected $apiKey; 
  29.  public $data = null; 
  30.  
  31.  public function __construct($mchid, $appid, $appKey,$key) 
  32.  { 
  33.  $this->mchid = $mchid; 
  34.  $this->appid = $appid; 
  35.  $this->appKey = $appKey; 
  36.  $this->apiKey = $key; 
  37.  } 
  38.  
  39.  /** 
  40.  * 通过跳转获取用户的openid,跳转流程如下: 
  41.  * 1、设置自己需要调回的url及其其他参数,跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize 
  42.  * 2、微信服务处理完成之后会跳转回用户redirect_uri地址,此时会带上一些参数,如:code 
  43.  * @return 用户的openid 
  44.  */ 
  45.  public function GetOpenid() 
  46.  { 
  47.  //通过code获得openid 
  48.  if (!isset($_GET['code'])){ 
  49.   //触发微信返回code码 
  50.   $scheme = $_SERVER['HTTPS']=='on' ? 'https://' : 'http://'; 
  51.   $baseUrl = urlencode($scheme.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING']); 
  52.   $url = $this->__CreateOauthUrlForCode($baseUrl); 
  53.   Header("Location: $url"); 
  54.   exit(); 
  55.  } else { 
  56.   //获取code码,以获取openid 
  57.   $code = $_GET['code']; 
  58.   $openid = $this->getOpenidFromMp($code); 
  59.   return $openid; 
  60.  } 
  61.  } 
  62.  
  63.  /** 
  64.  * 通过code从工作平台获取openid机器access_token 
  65.  * @param string $code 微信跳转回来带上的code 
  66.  * @return openid 
  67.  */ 
  68.  public function GetOpenidFromMp($code) 
  69.  { 
  70.  $url = $this->__CreateOauthUrlForOpenid($code); 
  71.  $res = self::curlGet($url); 
  72.  //取出openid 
  73.  $data = json_decode($res,true); 
  74.  $this->data = $data; 
  75.  $openid = $data['openid']; 
  76.  return $openid; 
  77.  } 
  78.  
  79.  /** 
  80.  * 构造获取open和access_toke的url地址 
  81.  * @param string $code,微信跳转带回的code 
  82.  * @return 请求的url 
  83.  */ 
  84.  private function __CreateOauthUrlForOpenid($code) 
  85.  { 
  86.  $urlObj["appid"] = $this->appid; 
  87.  $urlObj["secret"] = $this->appKey; 
  88.  $urlObj["code"] = $code; 
  89.  $urlObj["grant_type"] = "authorization_code"; 
  90.  $bizString = $this->ToUrlParams($urlObj); 
  91.  return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString; 
  92.  } 
  93.  
  94.  /** 
  95.  * 构造获取code的url连接 
  96.  * @param string $redirectUrl 微信服务器回跳的url,需要url编码 
  97.  * @return 返回构造好的url 
  98.  */ 
  99.  private function __CreateOauthUrlForCode($redirectUrl) 
  100.  { 
  101.  $urlObj["appid"] = $this->appid; 
  102.  $urlObj["redirect_uri"] = "$redirectUrl"; 
  103.  $urlObj["response_type"] = "code"; 
  104.  $urlObj["scope"] = "snsapi_base"; 
  105.  $urlObj["state"] = "STATE"."#wechat_redirect"; 
  106.  $bizString = $this->ToUrlParams($urlObj); 
  107.  return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString; 
  108.  } 
  109.  
  110.  /** 
  111.  * 拼接签名字符串 
  112.  * @param array $urlObj 
  113.  * @return 返回已经拼接好的字符串 
  114.  */ 
  115.  private function ToUrlParams($urlObj) 
  116.  { 
  117.  $buff = ""; 
  118.  foreach ($urlObj as $k => $v) 
  119.  { 
  120.   if($k != "sign") $buff .= $k . "=" . $v . "&"; 
  121.  } 
  122.  $buff = trim($buff, "&"); 
  123.  return $buff; 
  124.  } 
  125.  
  126.  /** 
  127.  * 企业付款 
  128.  * @param string $openid 调用【网页授权获取用户信息】接口获取到用户在该公众号下的Openid 
  129.  * @param float $totalFee 收款总费用 单位元 
  130.  * @param string $outTradeNo 唯一的订单号 
  131.  * @param string $orderName 订单名称 
  132.  * @param string $notifyUrl 支付结果通知url 不要有问号 
  133.  * @param string $timestamp 支付时间 
  134.  * @return string 
  135.  */ 
  136.  public function createJsBizPackage($openid, $totalFee, $outTradeNo,$trueName) 
  137.  { 
  138.  $config = array( 
  139.   'mch_id' => $this->mchid, 
  140.   'appid' => $this->appid, 
  141.   'key' => $this->apiKey, 
  142.  ); 
  143.  $unified = array( 
  144.   'mch_appid' => $config['appid'], 
  145.   'mchid' => $config['mch_id'], 
  146.   'nonce_str' => self::createNonceStr(), 
  147.   'openid' => $openid, 
  148.   'check_name'=>'FORCE_CHECK', //校验用户姓名选项。NO_CHECK:不校验真实姓名,FORCE_CHECK:强校验真实姓名 
  149.   're_user_name'=>$trueName,   //收款用户真实姓名(不支持给非实名用户打款) 
  150.   'partner_trade_no' => $outTradeNo, 
  151.   'spbill_create_ip' => '127.0.0.1', 
  152.   'amount' => intval($totalFee * 100), //单位 转为分 
  153.   'desc'=>'付款',  //企业付款操作说明信息 
  154.  ); 
  155.  $unified['sign'] = self::getSign($unified, $config['key']); 
  156.  $responseXml = $this->curlPost('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers', self::arrayToXml($unified)); 
  157.  $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA); 
  158.  if ($unifiedOrder === false) { 
  159.   die('parse xml error'); 
  160.  } 
  161.  if ($unifiedOrder->return_code != 'SUCCESS') { 
  162.   die($unifiedOrder->return_msg); 
  163.  } 
  164.  if ($unifiedOrder->result_code != 'SUCCESS') { 
  165.   die($unifiedOrder->err_code); 
  166.  } 
  167.  return true; 
  168.  } 
  169.  
  170.  public static function curlGet($url = '', $options = array()) 
  171.  { 
  172.  $ch = curl_init($url); 
  173.  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  174.  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
  175.  if (!emptyempty($options)) { 
  176.   curl_setopt_array($ch, $options); 
  177.  } 
  178.  //https请求 不验证证书和host 
  179.  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
  180.  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 
  181.  $data = curl_exec($ch); 
  182.  curl_close($ch); 
  183.  return $data; 
  184.  } 
  185.  
  186.  public function curlPost($url = '', $postData = '', $options = array()) 
  187.  { 
  188.  if (is_array($postData)) { 
  189.   $postData = http_build_query($postData); 
  190.  } 
  191.  $ch = curl_init(); 
  192.  curl_setopt($ch, CURLOPT_URL, $url); 
  193.  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  194.  curl_setopt($ch, CURLOPT_POST, 1); 
  195.  curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); 
  196.  curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数 
  197.  if (!emptyempty($options)) { 
  198.   curl_setopt_array($ch, $options); 
  199.  } 
  200.  //https请求 不验证证书和host 
  201.  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
  202.  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 
  203.  
  204.  //第一种方法,cert 与 key 分别属于两个.pem文件 
  205.  //默认格式为PEM,可以注释 
  206.  curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM'); 
  207.  curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/cert/apiclient_cert.pem'); 
  208.  //默认格式为PEM,可以注释 
  209.  curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM'); 
  210.  curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/cert/apiclient_key.pem'); 
  211.  //第二种方式,两个文件合成一个.pem文件 
  212. // curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem'); 
  213.  $data = curl_exec($ch); 
  214.  curl_close($ch); 
  215.  return $data; 
  216.  } 
  217.  
  218.  public static function createNonceStr($length = 16) 
  219.  { 
  220.  $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 
  221.  $str = ''; 
  222.  for ($i = 0; $i < $length; $i++) { 
  223.   $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); 
  224.  } 
  225.  return $str; 
  226.  } 
  227.  public static function arrayToXml($arr) 
  228.  { 
  229.  $xml = "<xml>"; 
  230.  foreach ($arr as $key => $val) { 
  231.   if (is_numeric($val)) { 
  232.   $xml .= "<" . $key . ">" . $val . "</" . $key . ">"; 
  233.   } else 
  234.   $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">"; 
  235.  } 
  236.  $xml .= "</xml>"; 
  237.  return $xml; 
  238.  } 
  239.  
  240.  public static function getSign($params, $key) 
  241.  { 
  242.  ksort($params, SORT_STRING); 
  243.  $unSignParaString = self::formatQueryParaMap($params, false); 
  244.  $signStr = strtoupper(md5($unSignParaString . "&key=" . $key)); 
  245.  return $signStr; 
  246.  } 
  247.  protected static function formatQueryParaMap($paraMap, $urlEncode = false) 
  248.  { 
  249.  $buff = ""; 
  250.  ksort($paraMap); 
  251.  foreach ($paraMap as $k => $v) { 
  252.   if (null != $v && "null" != $v) { 
  253.   if ($urlEncode) { 
  254.    $v = urlencode($v); 
  255.   } 
  256.   $buff .= $k . "=" . $v . "&"; 
  257.   } 
  258.  } 
  259.  $reqPar = ''; 
  260.  if (strlen($buff) > 0) { 
  261.   $reqPar = substr($buff, 0, strlen($buff) - 1); 
  262.  } 
  263.  return $reqPar; 
  264.  } 
  265. } 
  266. ?>

Tags: php微信支付 php企业付款

分享到: