Home Backend Development PHP Tutorial Detailed explanation of WeChat red envelope implementation on WeChat

Detailed explanation of WeChat red envelope implementation on WeChat

Jul 16, 2017 pm 04:32 PM
accomplish Red envelope Detailed explanation

本文实例讲述了PHP微信公众号开发之微信红包实现方法。分享给大家供大家参考,具体如下:

这几天遇到了一个客户 要给他们的微信公众平台上添加微信现金红包功能,是个二次开发的功能,顺手百度一下,原来不复杂。就着手开发功能了。现将开发的过程和需求贴出来分享一下:

一.需求:

粉丝通过在客户的公众平台点击他们公司的订单,然后给这个订单返现五元,发到订单的这个微信号上。

二.开发想法:

1:先拿到关注这个粉丝的openid,openid是关注某个公众号的微信标识,这样就可以定位到这个人是订单的操作者了。

2:发送xml数据请求微信服务器。

代码有两个php文件

1.oauth2.php

<?php
$code=$_GET[&#39;code&#39;];
$state=$_GET[&#39;state&#39;];
$appid=&#39;XXXX&#39;;
$appsecret=&#39;XXXXXXXX&#39;;//
if (empty($code)) $this->error(&#39;授权失败&#39;);
$token_url=&#39;https://api.weixin.qq.com/sns/oauth2/access_token?appid=&#39;.$appid&#39;&secret=&#39;.$appsecret.&#39;&code=&#39;.$code.&#39;&grant_type=authorization_code&#39;;
$token=json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
echo &#39;<h1>错误1</h1>&#39;.$token->errcode;
echo &#39;<br/><h2>错误信息1:</h2>&#39;.$token->errmsg;
exit;
}
session_start();
$_SESSION[&#39;openid&#39;]= $token->openid;
header(&#39;location:http://www.XXXXXXX.com/XXXXX/XXXXXX/XXXXXX/hongbao.php&#39;);//要跳转的文件路径
?>
Copy after login

2.hongbao.php

<?php
//XXXXX。。是需要开发者自己填写的内容,注意不要泄密
 // 从session中获取到openid;
$openid=$_SESSION["openid"];
    if(empty($openid))
    {
header(&#39;location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=XXXXXXXX&redirect_uri=http://www.XXXXXXX.com/oauth2.php&respose_type=code&scope=snsapi_base&state=XXXX&connect_redirect=1#wechat_redirect&#39;);
    }
}
// 关键的函数
public function weixin_red_packet(){
  // 请求参数
  // 随机字符串
  $data[&#39;nonce_str&#39;]=$this->get_unique_value();
  //商户号,输入你的商户号
  $data[&#39;mch_id&#39;]="XXXXXXX";
  //商户订单号,可以按要求自己组合28位的商户订单号
  $data[&#39;mch_billno&#39;]=$data[&#39;mch_id&#39;].date("ymd")."XXXXXX".rand(1000,9999);
  //公众帐号appid,输入自己的公众号appid
  $data[&#39;wxappid&#39;]="XXXXXXX";
  //商户名称
  $data[&#39;send_name&#39;]="XXXXX";
  //用户openid,输入待发红包的用户openid
  session_start();
  $data[&#39;re_openid&#39;]=$_SESSION["openid"];
  //付款金额
  $data[&#39;total_amount&#39;]="XXXX";
  //红包发放总人数
  $data[&#39;total_num&#39;]="XXXX";
  //红包祝福语
  $data[&#39;wishing&#39;]="XXXX";
  //IP地址
  $data[&#39;client_ip&#39;]=$_SERVER[&#39;LOCAL_ADDR&#39;];
  //活动名称
  $data[&#39;act_name&#39;]="XXXXX";
  //备注
  $data[&#39;remark&#39;]="XXXXX";
  // 生成签名
  //对数据数组进行处理
  //API密钥,输入自己的K 微信商户号里面的K
  $appsecret="XXXXXXXXXXXXXX"; //
  $data=array_filter($data);
  ksort($data);
  $str="";
  foreach($data as $k=>$v){
    $str.=$k."=".$v."&";
  }
  $str.="key=".$appsecret;
  $data[&#39;sign&#39;]=strtoupper(MD5($str));
  /*
    发红包操作过程:
      1.将请求数据转换成xml
      2.发送请求
      3.将请求结果转换为数组
      4.将请求信息和请求结果录入到数据库中
      4.判断是否通信成功
      5.判断是否转账成功
   */
  //发红包接口地址
  $url="api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
  //将请求数据由数组转换成xml
  $xml=$this->arraytoxml($data);
  //进行请求操作
  $res=$this->curl($xml,$url);
  //将请求结果由xml转换成数组
  $arr=$this->xmltoarray($res);
}
// 生成32位唯一随机字符串
private function get_unique_value(){
  $str=uniqid(mt_rand(),1);
  $str=sha1($str);
  return md5($str);
}
// 将数组转换成xml
private function arraytoxml($arr){
  $xml="<xml>";
  foreach($arr as $k=>$v){
    $xml.="<".$k.">".$v."</".$k.">";
  }
  $xml.="</xml>";
  return $xml;
}
// 将xml转换成数组
private function xmltoarray($xml){
  //禁止引用外部xml实体
  libxml_disable_entity_loader(true);
  $xmlstring=simplexml_load_string($xml,"SimpleXMLElement",LIBXML_NOCDATA);
  $arr=json_decode(json_encode($xmlstring),true);
  return $arr;
}
//进行curl操作
private function curl($param="",$url) {
  $postUrl = $url;
  $curlPost = $param;
  //初始化curl
  $ch = curl_init();
  //抓取指定网页
  curl_setopt($ch, CURLOPT_URL,$postUrl);
  //设置header
  curl_setopt($ch, CURLOPT_HEADER, 0);
  //要求结果为字符串且输出到屏幕上
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  //post提交方式
  curl_setopt($ch, CURLOPT_POST, 1);
  // 增加 HTTP Header(头)里的字段
  curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
  // 终止从服务端进行验证
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  //证书放到网站根目录的cert文件夹底下
  curl_setopt($ch,CURLOPT_SSLCERT,dirname(FILE).DIRECTORY_SEPARATOR.
        &#39;cert&#39;.DIRECTORY_SEPARATOR.&#39;apiclient_cert.pem&#39;);
    curl_setopt($ch,CURLOPT_SSLKEY,dirname(FILE).DIRECTORY_SEPARATOR.
        &#39;cert&#39;.DIRECTORY_SEPARATOR.&#39;apiient_key.pem&#39;);
    curl_setopt($ch,CURLOPT_CAINFO,dirname(FILE).DIRECTORY_SEPARATOR.
        &#39;cert&#39;.DIRECTORY_SEPARATOR.&#39;rootca.pem&#39;);
  //运行curl
  $data = curl_exec($ch);
  //关闭curl
  curl_close($ch);
  return $data;
}
?>
Copy after login

The above is the detailed content of Detailed explanation of WeChat red envelope implementation on WeChat. 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 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)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

Where is the Alipay red envelope code? Where is the Alipay red envelope code? Apr 25, 2024 am 10:20 AM

1. Open the Alipay app, click on the search box at the top, and enter [make money with red envelopes]. 2. Click [Go and Share to Earn Cash] or [Earn Cash Rewards Immediately] to generate a red envelope code for making money. 3. Users can choose to save the money-making red envelope code to the photo album, or share it directly with friends such as WeChat/Alipay/QQ. 4. Users can also choose to copy the password and share it with friends on various social software.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

See all articles