search
HomeBackend DevelopmentPHP TutorialImplement WeChat scan code payment php code sharing

Scan QR code payment has become a popular method of transaction. In this article, we mainly share with you the php code to implement WeChat scan QR code payment, hoping to help everyone.

1. You need to use WeChat to scan the QR code to pay,
payment file pay.php

<?phpinclude("../../../config/conn.php");//数据库//sql先插入订单到数据库//读取订单号//$ddbh="测试订单号";///直接访问本页面测试ini_set(&#39;date.timezone&#39;,&#39;Asia/Shanghai&#39;);$mchid = &#39;149651642&#39;;          //微信支付商户$appid = &#39;wxc35486954de04f5&#39;;  //公众号APPID $apiKey = &#39;6ac2b9ef5a7c1190&#39;;//设置API密钥$wxPay = new WxpayService($mchid,$appid,$apiKey);$outTradeNo = $ddbh;     //你商城的商品订单号$payAmount = 1;          //金额,单位:元$orderName = &#39;wxpay&#39;;    //订单标题$notifyUrl = weburl."notify.php";     //付款成功后的回调地址(不要有问号),可直接放根目录$payTime = time(); 
$arr = $wxPay->createJsBizPackage($payAmount,$outTradeNo,$orderName,$notifyUrl,$payTime);//生成二维码$url2 = $arr[&#39;code_url&#39;];//echo "<img  src="/static/imghwm/default1.png"  data-src="<?=weburl? alt="Implement WeChat scan code payment php code sharing" >tem/getqr.php?u=<?=urlencode($url2)?>&size=9"  class="lazy"  src=&#39;{$url}&#39; style=&#39;width:300px;&#39;>";class WxpayService{
    protected $mchid;    protected $appid;    protected $apiKey;    public function __construct($mchid, $appid, $key)
    {
        $this->mchid = $mchid;        $this->appid = $appid;        $this->apiKey = $key;
    }    /**
     * 发起订单
     * @param float $totalFee 收款总费用 单位元
     * @param string $outTradeNo 唯一的订单号
     * @param string $orderName 订单名称
     * @param string $notifyUrl 支付结果通知url 不要有问号
     * @param string $timestamp 订单发起时间
     * @return array
     */
    public function createJsBizPackage($totalFee, $outTradeNo, $orderName, $notifyUrl, $timestamp)
    {
        $config = array(            &#39;mch_id&#39; => $this->mchid,            &#39;appid&#39; => $this->appid,            &#39;key&#39; => $this->apiKey,
        );        //$orderName = iconv(&#39;GBK&#39;,&#39;UTF-8&#39;,$orderName);
        $unified = array(            &#39;appid&#39; => $config[&#39;appid&#39;],            &#39;attach&#39; => &#39;pay&#39;,             //商家数据包,原样返回,如果填写中文,请注意转换为utf-8
            &#39;body&#39; => $orderName,            &#39;mch_id&#39; => $config[&#39;mch_id&#39;],            &#39;nonce_str&#39; => self::createNonceStr(),            &#39;notify_url&#39; => $notifyUrl,            &#39;out_trade_no&#39; => $outTradeNo,            &#39;spbill_create_ip&#39; => &#39;127.0.0.1&#39;,            &#39;total_fee&#39; => intval($totalFee * 100),       //单位 转为分
            &#39;trade_type&#39; => &#39;NATIVE&#39;,
        );        $unified[&#39;sign&#39;] = self::getSign($unified, $config[&#39;key&#39;]);        $responseXml = self::curlPost(&#39;https://api.mch.weixin.qq.com/pay/unifiedorder&#39;, self::arrayToXml($unified));        $unifiedOrder = simplexml_load_string($responseXml, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);        if ($unifiedOrder === false) {            die(&#39;parse xml error&#39;);
        }        if ($unifiedOrder->return_code != &#39;SUCCESS&#39;) {            die($unifiedOrder->return_msg);
        }        if ($unifiedOrder->result_code != &#39;SUCCESS&#39;) {            die($unifiedOrder->err_code);
        }        $codeUrl = (array)($unifiedOrder->code_url);        if(!$codeUrl[0]) exit(&#39;get code_url error&#39;);        $arr = array(            "appId" => $config[&#39;appid&#39;],            "timeStamp" => $timestamp,            "nonceStr" => self::createNonceStr(),            "package" => "prepay_id=" . $unifiedOrder->prepay_id,            "signType" => &#39;MD5&#39;,            "code_url" => $codeUrl[0],
        );        $arr[&#39;paySign&#39;] = self::getSign($arr, $config[&#39;key&#39;]);        return $arr;
    }    public function notify()
    {
        $config = array(            &#39;mch_id&#39; => $this->mchid,            &#39;appid&#39; => $this->appid,            &#39;key&#39; => $this->apiKey,
        );        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];        $postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);        if ($postObj === false) {            die(&#39;parse xml error&#39;);
        }        if ($postObj->return_code != &#39;SUCCESS&#39;) {            die($postObj->return_msg);
        }        if ($postObj->result_code != &#39;SUCCESS&#39;) {            die($postObj->err_code);
        }        $arr = (array)$postObj;        unset($arr[&#39;sign&#39;]);        if (self::getSign($arr, $config[&#39;key&#39;]) == $postObj->sign) {            echo &#39;<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>&#39;;            return $postObj;
        }
    }    /**
     * curl get
     *
     * @param string $url
     * @param array $options
     * @return mixed
     */
    public static function curlGet($url = &#39;&#39;, $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        $data = curl_exec($ch);
        curl_close($ch);        return $data;
    }    public static function curlPost($url = &#39;&#39;, $postData = &#39;&#39;, $options = array())
    {
        if (is_array($postData)) {            $postData = http_build_query($postData);
        }        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);        $data = curl_exec($ch);
        curl_close($ch);        return $data;
    }    public static function createNonceStr($length = 16)
    {
        $chars = &#39;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&#39;;        $str = &#39;&#39;;        for ($i = 0; $i < $length; $i++) {            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }        return $str;
    }    public static 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;
    }    /**
     * 获取签名
     */
    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);        $unSignParaString = self::formatQueryParaMap($params, false);        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));        return $signStr;
    }    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);        foreach ($paraMap as $k => $v) {            if (null != $v && "null" != $v) {                if ($urlEncode) {                    $v = urlencode($v);
                }                $buff .= $k . "=" . $v . "&";
            }
        }        $reqPar = &#39;&#39;;        if (strlen($buff) > 0) {            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }        return $reqPar;
    }
}?><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1" /> <title><?=$g_webname?>微信支付</title><input type="hidden" id="wpay" value="<?php echo  $url2; ?>"/></head><body><img  src="/static/imghwm/default1.png"  data-src="<?=weburl? alt="Implement WeChat scan code payment php code sharing" >tem/getqr.php?u=<?=urlencode($url2)?>&size=9"  class="lazy"    style="max-width:90%" /></body></html>

2. Callback file notify.php

<?phpinclude("../../../config/conn.php");

ini_set(&#39;date.timezone&#39;,&#39;Asia/Shanghai&#39;);
error_reporting(0);$mchid = &#39;149651542&#39;;          //微信支付商户号$appid = &#39;wxc35486954de04f5&#39;;  //公众号APPID$apiKey = &#39;6ac2b9e5&#39;;   //API密钥$wxPay = new WxpayService($mchid,$appid,$apiKey);$result = $wxPay->notify();//file_put_contents(&#39;2.txt&#39;,json_encode($result));//测试结果//$result[&#39;transaction_id&#39;]为微信交易号 if($result){    if(array_key_exists("return_code", $result)
&& array_key_exists("result_code", $result)&& $result["return_code"] == "SUCCESS"&& $result["result_code"] == "SUCCESS"){    //file_put_contents(&#39;1.txt&#39;,1);$sj=date("Y-m-d H:i:s");$uip=$_SERVER["REMOTE_ADDR"];$sql="select * from yjcode_dingdang where bh=&#39;".$result[&#39;out_trade_no&#39;]."&#39; and ifok=0";mysql_query("SET NAMES &#39;GBK&#39;");$res=mysql_query($sql);if($row=mysql_fetch_array($res)){
 updatetable("yjcode_dingdang","sj=&#39;".$sj."&#39;,uip=&#39;".$uip."&#39;,alipayzt=&#39;TRADE_SUCCESS&#39;,ddzt=&#39;交易成功&#39;,ifok=1 ,wxddbh=".$result[&#39;transaction_id&#39;]." where id=".$row[id]); $money1=$row[&#39;money1&#39;];
 PointIntoM($row[&#39;userid&#39;],"微信充值".$money1."元",$money1);
 PointUpdateM($row[userid],$money1);
}            return true;
        }


}else{    echo &#39;pay error&#39;;
}class WxpayService{
    protected $mchid;    protected $appid;    protected $apiKey;    public function __construct($mchid, $appid, $key)
    {
        $this->mchid = $mchid;        $this->appid = $appid;        $this->apiKey = $key;
    }    public function notify()
    {
        $config = array(            &#39;mch_id&#39; => $this->mchid,            &#39;appid&#39; => $this->appid,            &#39;key&#39; => $this->apiKey,
        );        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];        $postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);        if ($postObj === false) {            die(&#39;parse xml error&#39;);
        }        if ($postObj->return_code != &#39;SUCCESS&#39;) {            die($postObj->return_msg);
        }        if ($postObj->result_code != &#39;SUCCESS&#39;) {            die($postObj->err_code);
        }        $arr = (array)$postObj;        unset($arr[&#39;sign&#39;]);        if (self::getSign($arr, $config[&#39;key&#39;]) == $postObj->sign) {            echo &#39;<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>&#39;;            return $arr;
        }
    }    /**
     * 获取签名
     */
    public static function getSign($params, $key)
    {
        ksort($params, SORT_STRING);        $unSignParaString = self::formatQueryParaMap($params, false);        $signStr = strtoupper(md5($unSignParaString . "&key=" . $key));        return $signStr;
    }    protected static function formatQueryParaMap($paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);        foreach ($paraMap as $k => $v) {            if (null != $v && "null" != $v) {                if ($urlEncode) {                    $v = urlencode($v);
                }                $buff .= $k . "=" . $v . "&";
            }
        }        $reqPar = &#39;&#39;;        if (strlen($buff) > 0) {            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }        return $reqPar;
    }
}

Related recommendations:

nodejs implements the WeChat code scanning payment function

After the PC side WeChat scanning code payment is successful, it will automatically jump to the PHP version code sharing

WeChat scan code payment mode

The above is the detailed content of Implement WeChat scan code payment php code sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool