Wechat app payment PHP

Time:2020-5-14
<?php
/**
 *Wechat app payment
 *
 * @license    
 * @link       
* @since      
*/
class wxAppPay
{
   Private $key ='8102b2a111111176d9f381ec6f837 '; // the merchant ID is the 32-bit API key set by the key on the wechat merchant platform
   Private $appid ='wxbca550502a91e9a '; // appid applied in wechat open platform 
   Private $mchid = '1000000'; // merchant number
   Private $payurl ='https://api.mch.weixin.qq.com/pay/unifiedor '; // unified order request interface

/*
    *Total fee
    *Out trade no
    *Notify "URL callback address
*/
public function doPay($params)
{
    $postData = array();
    $postData['appid']     = $this->appid;
    $postData['mch_id']     = $this->mchId;
    $postData['nonce_str'] = $this->createNoncestr();
    $postData ['body '] =' app payment ';   
    $postData['out_trade_no']     = date("YmdHis");     
    $postData['total_fee']     = $params['total_fee'];  
    $postData["spbill_create_ip"] = $_SERVER["REMOTE_ADDR"]; 
    $postData['notify_url'] = $params['notify_url'];
    $postData['trade_type'] = 'APP';
    $postData["sign"] = $this->createSign($postData);

     //Converting arrays to XML format
       $xmlData = $this->arrayToXml($postData);

       $res = $this->curl_post($this->payUrl, $xmlData); 
       $res = simplexml_load_string($res,NULL,LIBXML_NOCDATA);

    //Generate formal payment parameters
    $data = array();
    $data['appid'] = $this->appid;
    $data['noncestr'] = $postData['nonce_str'];
    //Wechat modifies interface parameters, otherwise IOS message parsing fails
    $data['package'] = 'Sign=WXPay';
    $data['partnerid'] = $this->mchId;
    $data['prepayid'] = (string)$res->prepay_id;
    $data['timestamp'] = time();
    $data ['sign '] = $this - > createsign ($data); // step on the pit. You must sign again here. You can't use the above one or the returned one
    return $data;
}

//Send curl post
private function curl_post($url = '', $param = array(),$headers = array()){ 
    if (empty($url)) {
        return false;
    }
    $ch = curl init(); // initialize curl
    Curl_setopt ($ch, curlopt_url, $URL); // grab the specified web page
    Curl_setopt ($ch, curlopt_header, 0); // set header
    curl_ setopt($ch, CURLOPT_ Returntransfer, 1); // the result is required to be a string and output to the screen
    Curl_setopt ($ch, curlopt_post, 1); // post submission method
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
             
    if($headers) curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    $data = curl_exec ($CH); // run curl
    curl_close($ch);
    return $data;
}


//Generate signature
private function createSign($params)
{
    //Signature step 1: sort parameters in dictionary order
    ksort($params);
    $String = $this->formatBizQueryParaMap($params, false);

    //Signature step 2: add key after string
    $String = $String."&key=".$this->key;
      
    //Signature step 3: MD5 encryption
    $String = md5($String);

    //Step 4: change all characters to uppercase
    $result_ = strtoupper($String);

    return $result_;

}

//Sort parameters in dictionary order
private function formatBizQueryParaMap($params,$urlencode=false)
{
    ksort($params);
    $buff = '';
    foreach($params as $key=>$val)
    {
        $buff .= $key . "=" . $val . "&";
    }
    $reqPar = substr($buff, 0, strlen($buff)-1);
    return $reqPar;
}

//Convert array to XML 
private function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach($arr as $key=>$val)
    {
        if(is_numeric($val))
            $xml .= '<' . $key .'>' . $val . '</' . $key . '>';
        else
            $xml .= "<".$key."><![CDATA[".$val."]]></".$key.">";
    }

    $xml .="</xml>";
    return $xml;
}


//Random string
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;
}  

}

call
$payObj = new wxAppPay();
$params = array(
‘total_fee’ => 100,
‘out_trade_no’ => date(‘YmdHis’),
‘notify’url’ = > ‘your own callback address’
);
$data = $payObj->doPay();

Small pit tip: if there is no problem with the parameters, it is also said that the signature is successful on the signature tool. Most likely, it’s the API key. Just reset the key.
If you need a certificate, you can also obtain the certificate in the background of this merchant.