Home > Backend Development > PHP Tutorial > How to use PHP for WeChat development and application integration

How to use PHP for WeChat development and application integration

王林
Release: 2023-08-03 22:42:01
Original
1403 people have browsed it

Title: How to use PHP for WeChat development and application integration

Introduction:
With the rapid development of the mobile Internet, WeChat has become an important part of people's daily life. Through the development of WeChat public accounts, we can realize functions such as interaction with users, information push, and payment. This article will introduce how to use PHP for WeChat development and application integration to help readers get started quickly.

1. Create a WeChat public account
First of all, we need to have a WeChat public account, which can be applied through the WeChat public platform. After the application is successful, we will obtain an AppID and AppSecret for subsequent development and integration work.

2. PHP environment preparation
Before developing WeChat, we need to ensure that the PHP environment has been configured on the server. We can confirm whether the PHP environment is normal through the following command:

php -v
Copy after login

If the PHP version information can be displayed correctly, the PHP environment is ready.

3. WeChat request verification
Before interacting with the WeChat official account, we first need to verify WeChat's request. The specific verification steps are as follows:

  1. Receive request
    We use PHP’s $_GET global variable to receive request parameters from WeChat. The specific code is as follows:
$signature = $_GET['signature'];
$timestamp = $_GET['timestamp'];
$nonce = $_GET['nonce'];
$echostr = $_GET['echostr'];

// 此处可以进行其他业务逻辑的处理

echo $echostr;
Copy after login
  1. Verify signature
    Will receive the $timestamp, $nonce and AppTokenCarry out dictionary sorting, then use the SHA1 algorithm to generate a signature, compare it with the $signature sent from WeChat, and determine the legality of the request:
$token = 'YourAppToken'; // 替换为你的AppToken

$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);

if ($tmpStr == $signature) {
    // 验证通过,返回true
    return true;
} else {
    // 验证失败,返回false
    return false;
}
Copy after login

4. WeChat messages Interaction
After completing the request verification, we can start message interaction with the WeChat official account. Specific code examples are as follows:

  1. Receive messages
    We use PHP's $GLOBALS['HTTP_RAW_POST_DATA'] global variables to receive message data sent by users. The code is as follows:
$postData = $GLOBALS['HTTP_RAW_POST_DATA'];

if (!empty($postData)) {
    $postObj = simplexml_load_string($postData, 'SimpleXMLElement', LIBXML_NOCDATA);

    $msgType = $postObj->MsgType;
    $content = $postObj->Content;

    // 在这里可以根据不同的消息类型进行相应的逻辑处理
}
Copy after login
  1. Reply message
    According to requirements, we can use the corresponding XML format data to reply to the user's message. The code example is as follows:
function replyTextMessage($fromUsername, $toUsername, $content) {
    $time = time();

    $response = sprintf(
        '<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[%s]]></Content>
        </xml>',
        $toUsername,
        $fromUsername,
        $time,
        $content
    );

    echo $response;
}
Copy after login

The above is a simple WeChat message interaction process, which can be expanded and optimized according to actual needs.

5. WeChat payment integration
In addition to message interaction, we can also integrate WeChat payment through PHP. The specific steps are as follows:

  1. Get prepay_id
    We need to send an XML data containing order information to the WeChat payment interface to obtain prepay_id. The code example is as follows:
function getPrepayId($outTradeNo, $totalFee, $notifyUrl) {
    $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
    $data = array(
        'appid' => 'YourAppID', // 替换为你的AppID
        'mch_id' => 'YourMchID', // 替换为你的MchID
        'nonce_str' => str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890'),
        'body' => '订单支付',
        'out_trade_no' => $outTradeNo,
        'total_fee' => $totalFee,
        'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
        'notify_url' => $notifyUrl,
        'trade_type' => 'JSAPI',
        'openid' => 'UserOpenID' // 替换为用户的OpenID
    );

    // 计算签名
    ksort($data);
    $string = http_build_query($data) . '&key=YourKey'; // 替换为你的Key
    $data['sign'] = strtoupper(md5($string));

    // 发送请求
    $xml = '<xml>';
    foreach ($data as $key => $value) {
        $xml .= sprintf('<%s>%s</%s>', $key, $value, $key);
    }
    $xml .= '</xml>';

    $response = file_get_contents($url, false, stream_context_create(array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-Type: text/xml',
            'content' => $xml
        )
    )));

    // 解析结果
    $responseObj = simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA);

    return $responseObj->prepay_id;
}
Copy after login
  1. JSAPI payment signature
    After obtaining payment-related information through prepay_id, we also need to use this information to perform JSAPI payment signature. The code example is as follows:
function getPaySign($prepayId, $appId, $timeStamp, $nonceStr) {
    $data = array(
        'appId' => $appId,
        'timeStamp' => $timeStamp,
        'nonceStr' => $nonceStr,
        'package' => 'prepay_id=' . $prepayId,
        'signType' => 'MD5'
    );

    // 计算签名
    ksort($data);
    $string = http_build_query($data) . '&key=YourKey'; // 替换为你的Key
    $sign = strtoupper(md5($string));

    return $sign;
}
Copy after login

Through the above code, we have implemented the message interaction and payment integration functions of the WeChat official account. Readers can expand and optimize according to specific needs to achieve more interesting functions.

Conclusion:
Through the introduction of this article, we have learned the basic process of how to use PHP for WeChat development and application integration. I hope readers can deepen their understanding of WeChat development through practice and flexibly apply it in actual projects. I wish you all more success in your WeChat development journey!

The above is the detailed content of How to use PHP for WeChat development and application integration. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template