Home Backend Development PHP Tutorial Usage examples of the WeChat red envelope sending interface in PHP version

Usage examples of the WeChat red envelope sending interface in PHP version

Jun 01, 2018 am 10:25 AM
php Example usage

This article mainly introduces the usage of the WeChat red envelope sending interface in the PHP version, and analyzes the related usage skills of PHP's WeChat red envelope sending interface in the form of examples. Friends in need can refer to the

WeChat red envelope function I believe All my friends know it, but if we want to integrate red envelopes into the website, how do we do it? Here the editor will share with you a test example of the php WeChat red envelope sending interface. I hope the article can help all my friends

The following is a class, how to use:

$arr['openid']='ojgTTt8oF9VdYcGsJMACHpA-jy1U';
      $arr['hbname']="提现申请";
      $arr['body']="您的提现申请已经成功";
      $arr['fee']=1;
$comm = new Common_util_pub();
$re = $comm->sendhongbaoto($arr);
var_dump($re);
Copy after login

Note that the certificate location and the key set in the merchant backend need to be modified.

<?php
header("Content-type: text/html; charset=utf-8");
class Common_util_pub
{
  /**
* hbname 红包名称 fee 红包金额 /元 body 内容 openid 微信用户id
* @param undefined $arr
*
* @return
*/
public function sendhongbaoto($arr){
//$comm = new Common_util_pub();
$data[&#39;mch_id&#39;] = &#39;120005402&#39;;
$data[&#39;mch_billno&#39;] = &#39;120005402&#39;.date("Ymd",time()).date("His",time()).rand(1111,9999);
$data[&#39;nonce_str&#39;] = self::createNoncestr();
$data[&#39;re_openid&#39;] = $arr[&#39;openid&#39;];
$data[&#39;wxappid&#39;] = &#39;wx8axxxxxbac4905&#39;;
$data[&#39;nick_name&#39;] = $arr[&#39;hbname&#39;];
$data[&#39;send_name&#39;] = $arr[&#39;hbname&#39;];
$data[&#39;total_amount&#39;] = $arr[&#39;fee&#39;]*100;
$data[&#39;min_value&#39;] = $arr[&#39;fee&#39;]*100;
$data[&#39;max_value&#39;] = $arr[&#39;fee&#39;]*100;
$data[&#39;total_num&#39;] = 1;
$data[&#39;client_ip&#39;] = $_SERVER[&#39;REMOTE_ADDR&#39;];
$data[&#39;act_name&#39;] = &#39;测试活动&#39;;
$data[&#39;remark&#39;] = &#39;备注一下&#39;;
$data[&#39;wishing&#39;] = $arr[&#39;body&#39;];
if(!$data[&#39;re_openid&#39;]) {
   $rearr[&#39;return_msg&#39;]=&#39;缺少用户openid&#39;;
   return $rearr;
}
$data[&#39;sign&#39;] = self::getSign($data);
$xml = self::arrayToXml($data);
//var_dump($xml);
$url ="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
$re = self::wxHttpsRequestPem($xml,$url);
$rearr = self::xmlToArray($re);
return $rearr;
}
function trimString($value)
  {
    $ret = null;
    if (null != $value)
    {
      $ret = $value;
      if (strlen($ret) == 0)
      {
        $ret = null;
      }
    }
    return $ret;
  }
  /**
   * 作用:产生随机字符串,不长于32位
   */
  public 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 formatBizQueryParaMap($paraMap, $urlencode)
  {
    $buff = "";
    ksort($paraMap);
    foreach ($paraMap as $k => $v)
    {
      if($urlencode)
      {
        $v = urlencode($v);
      }
      //$buff .= strtolower($k) . "=" . $v . "&";
      $buff .= $k . "=" . $v . "&";
    }
    $reqPar;
    if (strlen($buff) > 0)
    {
      $reqPar = substr($buff, 0, strlen($buff)-1);
    }
    return $reqPar;
  }
  /**
   * 作用:生成签名
   */
  public function getSign($Obj)
  {
    foreach ($Obj as $k => $v)
    {
      $Parameters[$k] = $v;
    }
    //签名步骤一:按字典序排序参数
    ksort($Parameters);
    $String = $this->formatBizQueryParaMap($Parameters, false);
    //echo &#39;【string1】&#39;.$String.&#39;</br>&#39;;
    //签名步骤二:在string后加入KEY
    $String = $String."&key="."254554sefg4exxxxxxxxs5cds1"; // 商户后台设置的key
    //echo "【string2】".$String."</br>";
    //签名步骤三:MD5加密
    $String = md5($String);
    //echo "【string3】 ".$String."</br>";
    //签名步骤四:所有字符转为大写
    $result_ = strtoupper($String);
    //echo "【result】 ".$result_."</br>";
    return $result_;
  }
  /**
   * 作用:array转xml
   */
  public 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;
  }
  /**
   * 作用:将xml转为array
   */
  public function xmlToArray($xml)
  {
    //将XML转为array
    $array_data = json_decode(json_encode(simplexml_load_string($xml, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA)), true);
    return $array_data;
  }
   public function wxHttpsRequestPem( $vars,$url, $second=30,$aHeader=array()){
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理,如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, &#39;10.206.30.98&#39;);
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        //以下两种方式需选择一种
        //第一种方法,cert 与 key 分别属于两个.pem文件
        //默认格式为PEM,可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,&#39;PEM&#39;);
        curl_setopt($ch,CURLOPT_SSLCERT,dirname(__FILE__).&#39;/hongbao/apiclient_cert.pem&#39;);
        //默认格式为PEM,可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,&#39;PEM&#39;);
        curl_setopt($ch,CURLOPT_SSLKEY,dirname(__FILE__).&#39;/hongbao/apiclient_key.pem&#39;);
        curl_setopt($ch,CURLOPT_CAINFO,&#39;PEM&#39;);
        curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).&#39;/hongbao/rootca.pem&#39;);
        //第二种方式,两个文件合成一个.pem文件
        //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().&#39;/all.pem&#39;);
        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }
        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }
        else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }
}
?>
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php Detailed explanation of the four methods of parsing xml

in PHP Summary of password encryption solutions

php array_multisort Detailed explanation and examples of sorting arrays

The above is the detailed content of Usage examples of the WeChat red envelope sending interface in PHP version. For more information, please follow other related articles on the PHP Chinese website!

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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1251
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles