PHP implementation of wechat app online payment function (code example)

Time:2021-4-27

Applet access address: payfee.php   If the TP framework is used to deal with the background, it can be written as a method

include 'WeixinPay.php';
$appid=''; // App ID
$openid= $_POST['id'];
$mch_ id=''; // Wechat payment merchant payment number
$key=''; // API key
$out_trade_no = $mch_id. time();
$total_fee = $_POST['fee'];
if (empty($total_ Fee // deposit
  $body ='top up deposit ';
  $total_fee = floatval(99*100);
} else {
   $body = recharge balance;
   $total_fee = floatval($total_fee*100);
 }
$weixinpay = new WeixinPay($appid,$openid,$mch_id,$key,$out_trade_no,$body,$total_fee);
$return=$weixinpay->pay();
echo json_encode($return);

Weixinpay.php wechat applet payment class all the parameters required by wechat applet have been written

/*
 *Small program wechat payment
 */
class WeixinPay {
  protected $appid;
  protected $mch_id;
  protected $key;
  protected $openid;
  protected $out_trade_no;
  protected $body;
  protected $total_fee;
  function __construct($appid, $openid, $mch_id, $key,$out_trade_no,$body,$total_fee) {
    $this->appid = $appid;
    $this->openid = $openid;
    $this->mch_id = $mch_id;
    $this->key = $key;
    $this->out_trade_no = $out_trade_no;
    $this->body = $body;
    $this->total_fee = $total_fee;
  }
  public function pay() {
    //Unified ordering interface
    $return = $this->weixinapp();
    return $return;
  }
  //Unified ordering interface
  private function unifiedorder() {
    $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
    $parameters = array(
      'appid' = > $this - > appid, // applet ID
      'mch_ id' => $this->mch_ ID, // merchant number
      'nonce_ STR '= > $this - > createnoncestr(), // random string
//'body' = >'test ', // product description
      'body' => $this->body,
//      'out_ trade_ No '= >'2018013106125348' // merchant order number
      'out_trade_no'=> $this->out_trade_no,
//      'total_ Fee '= > floatval (0.01 * 100), // total amount in cents
      'total_fee' => $this->total_fee,
      'spbill_ create_ ip' => $_ SERVER['REMOTE_ Addr '], // terminal IP
      // 'spbill_ create_ IP '= >'192.168.0.161' // terminal IP
      'notify_ url' => ' https://www.weixin.qq.com/wxpay/notify.php '// the notification address ensures normal access to the Internet
      'openid' = > $this - > openid, // user ID
      'trade_ Type '= >'jsapi' // transaction type
    );
    //Unified order signing
    $parameters['sign'] = $this->getSign($parameters);
    $xmlData = $this->arrayToXml($parameters);
    $return = $this->xmlToArray($this->postXmlCurl($xmlData, $url, 60));
    return $return;
  }
  private static function postXmlCurl($xml, $url, $second = 30) 
  {
    $ch = curl_init();
    //Set timeout
    curl_setopt($ch, CURLOPT_TIMEOUT, $second);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_ setopt($ch, CURLOPT_ SSL_ VERIFYHOST, FALSE); // Strict verification
    //Set header
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    //Require the result to be a string and output to the screen
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    //Post submission method
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
    curl_setopt($ch, CURLOPT_TIMEOUT, 40);
    set_time_limit(0);
    //Run curl
    $data = curl_exec($ch);
    //Return results
    if ($data) {
      curl_close($ch);
      return $data;
    } else {
      $error = curl_errno($ch);
      curl_close($ch);
      Throw new wxpayexception ("curl error, error code: $error");
    }
  }
  //Array to XML
  private function arrayToXml($arr) {
    $xml = "<xml>";
    foreach ($arr as $key => $val) {
      if (is_array($val)) {
        $xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
      } else {
        $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
      }
    }
    $xml .= "</xml>";
    return $xml;
  }
  //XML to array
  private function xmlToArray($xml) {
    //Prohibit referencing external XML entities 
    libxml_disable_entity_loader(true);
    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    $val = json_decode(json_encode($xmlstring), true);
    return $val;
  }
  //Wechat applet interface
  private function weixinapp() {
    //Unified ordering interface
    $unifiedorder = $this->unifiedorder();
//    print_r($unifiedorder);
    $parameters = array(
      'appid' = > $this - > appid, // applet ID
      'timestamp '= > ". Time ().", // timestamp
      'noncestr' = > $this - > createnoncestr(), // random string
      'package' => 'prepay_ id=' . $unifiedorder['prepay_ ID '], // packet
      'signtype '= >'md5' // signature method
    );
    //Signature
    $parameters['paySign'] = $this->getSign($parameters);
    return $parameters;
  }
  //Function: generate random string, no longer than 32 bits
  private function createNoncestr($length = 32) {
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str = "";
    for ($i = 0; $ i < $length; $ i++) { $str .= substr($chars, mt_ rand(0, strlen($chars) - 1), 1); }  return $str; } // Function: generate signature private function getsign ($obj) {foreach ($obj as $k = > $V){
      $Parameters[$k] = $v;
    }
    //Signature步骤一:按字典序排序参数
    ksort($Parameters);
    $String = $this->formatBizQueryParaMap($Parameters, false);
    //Signature步骤二:在string后加入KEY
    $String = $String . "&key=" . $this->key;
    //Signature步骤三:MD5加密
    $String = md5($String);
    //Signature步骤四:所有字符转为大写
    $result_ = strtoupper($String);
    return $result_;
  }
  ///Function: format parameters, signature process needs to use
  private function formatBizQueryParaMap($paraMap, $urlencode) {
    $buff = "";
    ksort($paraMap);
    foreach ($paraMap as $k => $v) {
      if ($urlencode) {
        $v = urlencode($v);
      }
      $buff .= $k . "=" . $v . "&";
    }
    $reqPar = '';
    if (strlen($buff) > 0) {
      $reqPar = substr($buff, 0, strlen($buff) - 1);
    }
    return $reqPar;
  }
}

Applet page request processing:

wx.request({
   url: ' https://yourhost.com/wxpay/payfee.php '// change to your own link
   data:{
    ID: app.globaldata.openid, // get the user's openid
    fee:100 // commodity price
   },
   header: {
    'Content-Type': 'application/x-www-form-urlencoded'
   },
   method: 'POST',
   success: function (res) {
    console.log(res.data);
    Console.log ('transfer payment ');
    wx.requestPayment({
     'timeStamp': res.data.timeStamp,
     'nonceStr': res.data.nonceStr,
     'package': res.data.package,
     'signType': 'MD5',
     'paySign': res.data.paySign,
     'success': function (res) {
      console.log('success');
      wx.showToast({
       Title: 'payment successful',
       icon: 'success',
       duration: 3000
      });
     },
     'fail': function (res) {
      console.log(res);
     },
     'complete': function (res) {
      console.log('complete');
     }
    });
   },
   fail: function (res) {
    console.log(res.data)
   }
  });

Callback URL: notify.php

$postXml = $GLOBALS["HTTP_ RAW_ POST_ DATA"]; // Receive wechat parameters 
//If the parameter is not accepted, file can be used_ get_ contents(" php://input ");  It seems that $globals has been abandoned in the advanced version of PHP
if (empty($postXml)) {
  return false;
}
 
//Convert XML format to array
function xmlToArray($xml) {
  //Prohibit referencing external XML entities 
  libxml_disable_entity_loader(true);
  $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
  $val = json_decode(json_encode($xmlstring), true);
  return $val;
}

$attr = xmlToArray($postXml);
$total_fee = $attr['total_fee'];
$open_id = $attr['openid'];
$out_trade_no = $attr['out_trade_no'];
$time = $attr['time_end'];

So: after wechat’s asynchronous notification, we also need to return a message to the wechat server, but all the data formats of wechat are XML, so we can return a data to wechat.

echo exit(‘<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>’);

summary

This article about the online payment function of PHP wechat app is introduced here. For more related online payment content of PHP wechat app, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!